Algorithm Search⌘K

Algorithmresearch

Discrete Gaussian mechanism

Also called discrete Gaussian noise, discrete Gaussian sampler.

Adds integer noise with mass proportional to exp(-y^2/(2 sigma^2)), drawn by an exact sampler with only random integers and rational arithmetic, which avoids the flaws of float noise.

Time
O(1) expected
Space
O(1) extra
Where
b = the number of bits of sigma^2 and of the output
Properties
randomizedexactrandomized
Origin
Clement L. Canonne, Gautam Kamath, Thomas Steinke, 2020

The discrete Gaussian mechanism answers an integer-valued query ff by releasing f(x)+Yf(x) + Y, where the noise YY is an integer with Pr⁡[Y=y]\Pr[Y = y] proportional to e−y2/(2σ2)e^{-y^2/(2\sigma^2)}. This distribution, written NZ(0,σ2)N_{\mathbb Z}(0, \sigma^2), is the discrete Gaussian. It gives the same privacy as the continuous Gaussian mechanism: for sensitivity Δ\Delta it is Δ2/(2σ2)\Delta^2/(2\sigma^2)-zCDP. Its main value is that it can be sampled exactly with only uniform random integers and rational arithmetic, with no floating point numbers, no exp⁡\exp and no square root. Mironov showed in 2012 that float implementations of continuous noise can leak through the low-order bits of their outputs. An exact integer sampler removes that whole class of problems. Canonne, Kamath and Steinke gave the analysis and the sampler in 2020. The same distribution is central in lattice-based cryptography, where it is sampled for a different purpose (see Gaussian sampling over lattices).

In plain words

To hide one person's effect on a count, we add a random whole number to it. Small numbers near zero are likely, and large ones are rare, in the bell shape of the normal curve. This gives the same protection as normal noise with fractions.

The important part is how the random number is drawn. A computer that draws a fraction with limited precision can leave traces in the last digits that point to the true answer. This method draws only whole numbers, by a series of fair choices and exact fractions, so the result has exactly the intended distribution. It needs a few rounds on average.

The problem

Input: the true answer v=f(x)∈Zv = f(x) \in \mathbb Z of a query with integer values and sensitivity Δ∈Z≥1\Delta \in \mathbb Z_{\ge 1}, and a rational σ2>0\sigma^2 > 0. Output: v+Yv + Y with Y∼NZ(0,σ2)Y \sim N_{\mathbb Z}(0, \sigma^2), where

Pr⁡[Y=y]=e−y2/(2σ2)∑z∈Ze−z2/(2σ2),y∈Z.\Pr[Y = y] = \frac{e^{-y^2/(2\sigma^2)}}{\sum_{z \in \mathbb Z} e^{-z^2/(2\sigma^2)}}, \qquad y \in \mathbb Z.

The output law must be exact, given a source of uniform random integers, and the computation must use only exact integer and rational arithmetic. The model is the word RAM.

The algorithm

  1. DISCRETE-GAUSSIAN-MECHANISM(v, sigma2) ▷ v = f(x) in Z, sigma2 > 0 rational
  2. 1t <- floor(sqrt(sigma2)) + 1 ▷ the least integer with t^2 > sigma2
  3. 2loop
  4. 3Y <- DISCRETE-LAPLACE(t) ▷ Pr[Y = y] proportional to exp(-|y|/t)
  5. 4gamma <- (|Y| - sigma2/t)^2 / (2 sigma2)
  6. 5C <- BERNOULLI-EXP(gamma) ▷ 1 with probability exp(-gamma)
  7. 6if C = 1 then return v + Y

Line L1 picks the scale of a discrete Laplace proposal. It is computed without a square root, as the least integer tt with t2>σ2t^2 > \sigma^2. Lines L2 to L6 are rejection sampling: line L3 proposes YY from the discrete Laplace distribution, and lines L4 and L5 accept it with probability e−γe^{-\gamma}. The product of the two weights is e−∣y∣/t−γ=e−y2/(2σ2)⋅e−σ2/(2t2)e^{-|y|/t - \gamma} = e^{-y^2/(2\sigma^2)} \cdot e^{-\sigma^2/(2t^2)}, where the second factor does not depend on yy. So an accepted YY has exactly the discrete Gaussian law. Each round accepts with probability above 0.290.29.

The two subroutines are Algorithms 1 and 2 of Canonne, Kamath and Steinke.

  • BERNOULLI-EXP(γ\gamma) returns 1 with probability e−γe^{-\gamma} for rational γ≥0\gamma \ge 0. For γ≤1\gamma \le 1: set K=1K = 1, and while a draw from Bernoulli(γ/K)(\gamma/K) is 1, increase KK; return 1 if KK is odd. The probability that KK is odd is ∑j(−γ)j/j!=e−γ\sum_j (-\gamma)^j/j! = e^{-\gamma}. For γ>1\gamma > 1: run the case γ=1\gamma = 1 up to ⌊γ⌋\lfloor\gamma\rfloor times and return 0 at the first 0; then return BERNOULLI-EXP(γ−⌊γ⌋)(\gamma - \lfloor\gamma\rfloor). A Bernoulli(n/d)(n/d) draw is "a uniform integer in {0,…,d−1}\{0, \ldots, d-1\} is below nn".
  • DISCRETE-LAPLACE(tt) draws UU uniform in {0,…,t−1}\{0, \ldots, t-1\} and keeps it with probability e−U/te^{-U/t}; draws V≥0V \ge 0 by counting 1s from BERNOULLI-EXP(1)(1) until the first 0; sets X=U+tVX = U + tV, which is geometric with ratio e−1/te^{-1/t}; draws a fair sign; starts again if the sign is negative and X=0X = 0; and returns the signed XX.

The tests of the code on this site pass a seeded generator so that each run repeats. A deployment must use a cryptographic source of randomness, such as the operating system generator, and must keep the exact arithmetic (Mironov 2012; Canonne, Kamath and Steinke 2020).

Example

Let v=10v = 10 and σ2=4\sigma^2 = 4. Line L1 gives t=3t = 3, since 22=42^2 = 4 is not above σ2\sigma^2 but 32=93^2 = 9 is. Suppose that the proposals are Y=−5Y = -5 and then Y=2Y = 2, and that the Bernoulli draws are 0 and then 1.

round YY (L3) γ\gamma (L4) e−γe^{-\gamma} CC (L5) action (L6)
1 −5-5 (5−4/3)2/8=121/72(5 - 4/3)^2/8 = 121/72 0.1863 0 reject, go to L3
2 2 (2−4/3)2/8=1/18(2 - 4/3)^2/8 = 1/18 0.9460 1 return 10+2=1210 + 2 = 12

A proposal of Y=0Y = 0 would get γ=(4/3)2/8=2/9\gamma = (4/3)^2/8 = 2/9. The exact probabilities of the output noise are Pr⁡[Y=0]=0.199471\Pr[Y = 0] = 0.199471, Pr⁡[Y=±1]=0.176033\Pr[Y = \pm 1] = 0.176033 and Pr⁡[Y=±2]=0.120985\Pr[Y = \pm 2] = 0.120985, and its variance agrees with σ2=4\sigma^2 = 4 to about 15 digits, from below.

For a count with Δ=1\Delta = 1, this release is 1/81/8-zCDP. Theorem 7 of Canonne, Kamath and Steinke gives the exact δ\delta at ε=1\varepsilon = 1: δ=0.0072488\delta = 0.0072488. The continuous Gaussian with σ=2\sigma = 2 has δ=0.0068296\delta = 0.0068296 at the same ε\varepsilon, so the discrete version is almost the same.

Correctness

Theorem (Canonne, Kamath and Steinke). Given a perfect source of uniform random integers, DISCRETE-GAUSSIAN-MECHANISM stops with probability 1 and returns v+Yv + Y with Y∼NZ(0,σ2)Y \sim N_{\mathbb Z}(0, \sigma^2) exactly. If ff has sensitivity Δ\Delta, the mechanism is Δ2/(2σ2)\Delta^2/(2\sigma^2)-zCDP, and its tight (ε,δ)(\varepsilon, \delta) curve is

δ(ε)=Pr⁡[Y>εσ2Δ−Δ2]−eεPr⁡[Y>εσ2Δ+Δ2].\delta(\varepsilon) = \Pr\left[Y > \frac{\varepsilon\sigma^2}{\Delta} - \frac{\Delta}{2}\right] - e^{\varepsilon}\Pr\left[Y > \frac{\varepsilon\sigma^2}{\Delta} + \frac{\Delta}{2}\right].

The proof in proofs/correctness.md checks the two subroutines, then the rejection step of lines L4 and L5, and then the privacy claim. For privacy, completing the square gives

Dα(NZ(μ,σ2)∥NZ(0,σ2))=αμ22σ2+1α−1ln⁡∑ye−(y−αμ)2/(2σ2)∑ye−y2/(2σ2),D_\alpha(N_{\mathbb Z}(\mu, \sigma^2)\|N_{\mathbb Z}(0, \sigma^2)) = \frac{\alpha\mu^2}{2\sigma^2} + \frac{1}{\alpha - 1}\ln\frac{\sum_y e^{-(y - \alpha\mu)^2/(2\sigma^2)}}{\sum_y e^{-y^2/(2\sigma^2)}},

and the Poisson summation formula shows that the last ratio is at most 1. It equals 1 when αμ\alpha\mu is an integer.

Proof: The discrete Gaussian sampler is exact and the mechanism is zCDPfull

We work in the word RAM with exact rational arithmetic and assume a source of independent uniform random integers: a call with argument d≥1d \ge 1 returns each of 0,…,d−10, \ldots, d-1 with probability 1/d1/d. For rational p=n/d∈[0,1]p = n/d \in [0, 1], the draw "a uniform integer in {0,…,d−1}\{0, \ldots, d-1\} is below nn" is a Bernoulli(p)(p) draw. For σ2>0\sigma^2 > 0 write w(y)=e−y2/(2σ2)w(y) = e^{-y^2/(2\sigma^2)} and Zσ=∑y∈Zw(y)Z_\sigma = \sum_{y \in \mathbb Z} w(y), so that NZ(0,σ2)N_{\mathbb Z}(0, \sigma^2) has mass w(y)/Zσw(y)/Z_\sigma at yy.

A loop whose rounds are independent and succeed with the same probability s>0s > 0 stops with probability 1, after a geometric number of rounds with mean 1/s1/s, and its output has the law of one round conditioned on success. We use this fact for each rejection loop.

Lemma 1 (BERNOULLI-EXP, 0≤γ≤10 \le \gamma \le 1). The procedure that sets K=1K = 1, increases KK while a Bernoulli(γ/K)(\gamma/K) draw is 1, and returns 1 if KK is odd, stops with probability 1 and returns 1 with probability e−γe^{-\gamma}.

Proof. Each γ/K≤1\gamma/K \le 1, so each draw is valid. The event K>kK > k is that the first kk draws are 1, so Pr⁡[K>k]=∏j=1kγ/j=γk/k!\Pr[K > k] = \prod_{j=1}^{k}\gamma/j = \gamma^k/k!, which tends to 0; the procedure stops with probability 1. Then Pr⁡[K=k]=γk−1/(k−1)!−γk/k!\Pr[K = k] = \gamma^{k-1}/(k-1)! - \gamma^k/k!, and

Pr⁡[K odd]=∑k odd(γk−1(k−1)!−γkk!)=∑j≥0(−γ)jj!=e−γ,\Pr[K \text{ odd}] = \sum_{k \text{ odd}}\left(\frac{\gamma^{k-1}}{(k-1)!} - \frac{\gamma^k}{k!}\right) = \sum_{j \ge 0}\frac{(-\gamma)^j}{j!} = e^{-\gamma},

where the series converges absolutely. The expected number of draws is E[K]=∑k≥0Pr⁡[K>k]=eγ≤eE[K] = \sum_{k \ge 0}\Pr[K > k] = e^{\gamma} \le e. □\square

Lemma 2 (BERNOULLI-EXP, γ>1\gamma > 1). For rational γ>1\gamma > 1, running the case γ=1\gamma = 1 up to ⌊γ⌋\lfloor\gamma\rfloor times, returning 0 at the first 0, and else returning BERNOULLI-EXP(γ−⌊γ⌋)(\gamma - \lfloor\gamma\rfloor), returns 1 with probability e−γe^{-\gamma}.

Proof. The result is 1 exactly when all ⌊γ⌋+1\lfloor\gamma\rfloor + 1 independent calls return 1. By Lemma 1 this has probability (e−1)⌊γ⌋e−(γ−⌊γ⌋)=e−γ(e^{-1})^{\lfloor\gamma\rfloor}e^{-(\gamma - \lfloor\gamma\rfloor)} = e^{-\gamma}. □\square

Lemma 3 (DISCRETE-LAPLACE). For an integer t≥1t \ge 1, DISCRETE-LAPLACE(t)(t) stops with probability 1 and returns YY with Pr⁡[Y=y]=1−e−1/t1+e−1/te−∣y∣/t\Pr[Y = y] = \frac{1 - e^{-1/t}}{1 + e^{-1/t}}e^{-|y|/t} for y∈Zy \in \mathbb Z.

Proof. Consider one round. UU is uniform in {0,…,t−1}\{0, \ldots, t-1\} and is kept with probability e−U/te^{-U/t} (Lemma 1), so Pr⁡[U=u,kept]=e−u/t/t\Pr[U = u, \text{kept}] = e^{-u/t}/t. VV counts the 1s before the first 0 of independent Bernoulli(e−1)(e^{-1}) draws, so Pr⁡[V=v]=(1−e−1)e−v\Pr[V = v] = (1 - e^{-1})e^{-v}. Every x≥0x \ge 0 is u+tvu + tv for exactly one pair with 0≤u<t0 \le u < t, so

Pr⁡[X=x,kept]=1−e−1te−u/t−v=c e−x/t,c=1−e−1t.\Pr[X = x, \text{kept}] = \frac{1 - e^{-1}}{t}e^{-u/t - v} = c\,e^{-x/t}, \qquad c = \frac{1 - e^{-1}}{t}.

The sign BB is fair and independent. The round fails when B=1B = 1 and X=0X = 0. For y>0y > 0 the round returns yy when X=yX = y and B=0B = 0; for y<0y < 0, when X=−yX = -y and B=1B = 1; for y=0y = 0, when X=0X = 0 and B=0B = 0. In all three cases Pr⁡[round returns y]=c2e−∣y∣/t\Pr[\text{round returns } y] = \frac c2 e^{-|y|/t}. This is positive and summable, so the round succeeds with a fixed probability s>0s > 0, and the output of the loop has mass proportional to e−∣y∣/te^{-|y|/t}. Normalizing, ∑ye−∣y∣/t=(1+e−1/t)/(1−e−1/t)\sum_y e^{-|y|/t} = (1 + e^{-1/t})/(1 - e^{-1/t}). □\square

Lemma 4 (lines L1 to L6 sample exactly). DISCRETE-GAUSSIAN-MECHANISM(v,σ2)(v, \sigma^2) stops with probability 1 and returns v+Yv + Y with Y∼NZ(0,σ2)Y \sim N_{\mathbb Z}(0, \sigma^2).

Proof. Line L1 gives an integer t≥1t \ge 1; the argument below works for every such tt. In one round, line L3 gives Y=yY = y with probability cte−∣y∣/tc_t e^{-|y|/t} by Lemma 3, and lines L4 and L5 accept it with probability e−γ(y)e^{-\gamma(y)} by Lemmas 1 and 2, where γ(y)=(∣y∣−σ2/t)2/(2σ2)≥0\gamma(y) = (|y| - \sigma^2/t)^2/(2\sigma^2) \ge 0 is rational. Expanding the square,

∣y∣t+γ(y)=∣y∣t+y22σ2−∣y∣t+σ22t2=y22σ2+σ22t2.\frac{|y|}{t} + \gamma(y) = \frac{|y|}{t} + \frac{y^2}{2\sigma^2} - \frac{|y|}{t} + \frac{\sigma^2}{2t^2} = \frac{y^2}{2\sigma^2} + \frac{\sigma^2}{2t^2}.

So Pr⁡[round returns y]=cte−σ2/(2t2)w(y)\Pr[\text{round returns } y] = c_t e^{-\sigma^2/(2t^2)}w(y), a constant times w(y)w(y). The success probability of a round is cte−σ2/(2t2)Zσ>0c_t e^{-\sigma^2/(2t^2)}Z_\sigma > 0, so the loop stops with probability 1, and the accepted YY has mass w(y)/Zσw(y)/Z_\sigma. Line L6 returns v+Yv + Y. □\square

Lemma 5 (theta sums). For every real cc, ∑y∈Zw(y−c)≤∑y∈Zw(y)\sum_{y \in \mathbb Z} w(y - c) \le \sum_{y \in \mathbb Z} w(y), with equality when cc is an integer.

Proof. The Fourier transform of ww is w^(ξ)=2πσ e−2π2σ2ξ2\hat w(\xi) = \sqrt{2\pi}\sigma\,e^{-2\pi^2\sigma^2\xi^2}. By the Poisson summation formula, which applies because ww and w^\hat w decay faster than any power,

∑y∈Zw(y−c)=2πσ∑k∈Ze−2π2σ2k2cos⁡(2πkc).\sum_{y \in \mathbb Z} w(y - c) = \sqrt{2\pi}\sigma\sum_{k \in \mathbb Z}e^{-2\pi^2\sigma^2k^2}\cos(2\pi kc).

Every term is at most its value at c=0c = 0, because cos⁡(2πkc)≤1\cos(2\pi kc) \le 1 and the weights are positive. For integer cc all cosines are 1. □\square

Lemma 6 (Renyi divergence). Let P=μ+NZ(0,σ2)P = \mu + N_{\mathbb Z}(0, \sigma^2) and Q=NZ(0,σ2)Q = N_{\mathbb Z}(0, \sigma^2) for an integer μ\mu. Then Dα(P∥Q)≤αμ2/(2σ2)D_\alpha(P\|Q) \le \alpha\mu^2/(2\sigma^2) for every α>1\alpha > 1, with equality when αμ\alpha\mu is an integer.

Proof. For each yy, completing the square gives α(y−μ)2+(1−α)y2=(y−αμ)2−α(α−1)μ2\alpha(y - \mu)^2 + (1 - \alpha)y^2 = (y - \alpha\mu)^2 - \alpha(\alpha - 1)\mu^2. Hence

∑yP(y)αQ(y)1−α=1Zσ∑yw(y−μ)αw(y)1−α=eα(α−1)μ2/(2σ2) ∑yw(y−αμ)Zσ.\sum_y P(y)^{\alpha}Q(y)^{1-\alpha} = \frac{1}{Z_\sigma}\sum_y w(y - \mu)^{\alpha}w(y)^{1-\alpha} = e^{\alpha(\alpha - 1)\mu^2/(2\sigma^2)}\,\frac{\sum_y w(y - \alpha\mu)}{Z_\sigma}.

Take 1α−1ln⁡\frac{1}{\alpha - 1}\ln of both sides. The ratio is at most 1 by Lemma 5, with equality when αμ\alpha\mu is an integer. □\square

Theorem. DISCRETE-GAUSSIAN-MECHANISM is exact, and for a query ff with integer values and sensitivity Δ\Delta it is Δ2/(2σ2)\Delta^2/(2\sigma^2)-zCDP. For neighbors with ∣f(x)−f(x′)∣=Δ|f(x) - f(x')| = \Delta, its smallest δ\delta at ε≥0\varepsilon \ge 0 is

δ(ε)=Pr⁡[Y>εσ2Δ−Δ2]−eεPr⁡[Y>εσ2Δ+Δ2],Y∼NZ(0,σ2).\delta(\varepsilon) = \Pr\left[Y > \frac{\varepsilon\sigma^2}{\Delta} - \frac{\Delta}{2}\right] - e^{\varepsilon}\Pr\left[Y > \frac{\varepsilon\sigma^2}{\Delta} + \frac{\Delta}{2}\right], \qquad Y \sim N_{\mathbb Z}(0, \sigma^2).

Proof. Exactness is Lemma 4. For neighbors x,x′x, x', let d=f(x)−f(x′)d = f(x) - f(x'), an integer with ∣d∣≤Δ|d| \le \Delta. The output laws are f(x′)+d+NZ(0,σ2)f(x') + d + N_{\mathbb Z}(0, \sigma^2) and f(x′)+NZ(0,σ2)f(x') + N_{\mathbb Z}(0, \sigma^2). A shift of both laws by −f(x′)-f(x') does not change the divergence, so by Lemma 6, Dα(M(x)∥M(x′))≤αd2/(2σ2)≤αΔ2/(2σ2)D_\alpha(M(x)\|M(x')) \le \alpha d^2/(2\sigma^2) \le \alpha\Delta^2/(2\sigma^2) for all α>1\alpha > 1. The other order has shift −d-d, and the same bound holds. This is the definition of Δ2/(2σ2)\Delta^2/(2\sigma^2)-zCDP with ξ=0\xi = 0.

For the δ\delta curve, take the case f(x′)=f(x)+Δf(x') = f(x) + \Delta and shift so that M(x)M(x) has law p(y)=w(y)/Zσp(y) = w(y)/Z_\sigma and M(x′)M(x') has law q(y)=p(y−Δ)q(y) = p(y - \Delta); the case f(x′)=f(x)−Δf(x') = f(x) - \Delta is the mirror image under y↦−yy \mapsto -y. The smallest δ\delta is the hockey-stick divergence ∑y(p(y)−eεq(y))+\sum_y (p(y) - e^{\varepsilon}q(y))_+, reached at the set where the privacy loss ℓ(y)=ln⁡(p(y)/q(y))\ell(y) = \ln(p(y)/q(y)) is above ε\varepsilon. Here

ℓ(y)=(y−Δ)2−y22σ2=Δ2−2Δy2σ2,\ell(y) = \frac{(y - \Delta)^2 - y^2}{2\sigma^2} = \frac{\Delta^2 - 2\Delta y}{2\sigma^2},

so ℓ(y)>ε\ell(y) > \varepsilon exactly when y<ay < a with a=Δ/2−εσ2/Δa = \Delta/2 - \varepsilon\sigma^2/\Delta. Then

δ(ε)=Pr⁡[Y<a]−eεPr⁡[Y+Δ<a]=Pr⁡[Y>−a]−eεPr⁡[Y>Δ−a],\delta(\varepsilon) = \Pr[Y < a] - e^{\varepsilon}\Pr[Y + \Delta < a] = \Pr[Y > -a] - e^{\varepsilon}\Pr[Y > \Delta - a],

by the symmetry of YY, and −a=εσ2/Δ−Δ/2-a = \varepsilon\sigma^2/\Delta - \Delta/2 and Δ−a=εσ2/Δ+Δ/2\Delta - a = \varepsilon\sigma^2/\Delta + \Delta/2. Canonne, Kamath and Steinke (Theorem 7) also show that pairs with ∣d∣<Δ|d| < \Delta do not need a larger δ\delta, so this curve is the tight guarantee of the mechanism whenever a pair with ∣d∣=Δ|d| = \Delta exists. ■\blacksquare

Complexity

In the word RAM with rationals of O(b)O(b) bits, the expected cost is O(1)O(1) arithmetic operations (Canonne, Kamath and Steinke, Theorem 32). Each round of lines L2 to L6 accepts with probability above 0.290.29, so the expected number of rounds is below 3.53.5. A call of DISCRETE-LAPLACE succeeds in each of its rounds with probability at least (1−e−1)/2(1 - e^{-1})/2, and the counting loop for VV runs about 0.580.58 times on average. BERNOULLI-EXP(γ)(\gamma) for γ≤1\gamma \le 1 makes at most ee draws on average, and for larger γ\gamma it stops at the first 0 from Bernoulli(e−1)(e^{-1}). Extra space is O(1)O(1) numbers. The run time depends on the noise drawn, so it is not constant.

Properties

  • Exact. The output law is exactly v+NZ(0,σ2)v + N_{\mathbb Z}(0, \sigma^2), not an approximation, if the random integers are uniform.
  • Same privacy as the continuous Gaussian. Δ2/(2σ2)\Delta^2/(2\sigma^2)-zCDP, the same as Proposition 1.6 of Bun and Steinke for continuous noise. The δ\delta for a given ε\varepsilon is close to the continuous one, and slightly larger for small σ\sigma.
  • Variance at most σ2\sigma^2 (Corollary 17 of Canonne, Kamath and Steinke), and very close to σ2\sigma^2 once σ≥1\sigma \ge 1.
  • Integer output. Counts stay integers; no rounding step is needed.

Variants and improvements

  • Vectors. For a query with values in Zd\mathbb Z^d, add independent discrete Gaussian noise to each coordinate. The privacy depends on the ℓ2\ell_2 sensitivity, as for the continuous mechanism.
  • Discrete Laplace. The subroutine DISCRETE-LAPLACE is on its own a pure DP mechanism for integer queries, the two-sided geometric mechanism, with exact sampling.
  • Snapping. Mironov's snapping mechanism keeps float Laplace noise but rounds and clamps the output, which also defends against the low-bit leak.
  • Other samplers. Samplers from lattice cryptography (for example table-based and constant-time samplers) also draw discrete Gaussians; they target other trade-offs, such as constant run time.

When to use it

Use the discrete Gaussian mechanism for integer queries, such as counts and histograms, when the accounting is in zCDP or Renyi DP and the release needs a sampler that is provably exact. It is the natural replacement for float Gaussian noise in production systems. For pure ε\varepsilon-DP use discrete Laplace noise instead.

Pitfalls

  • Floats at lines L4 and L5. Computing e−γe^{-\gamma} in floating point and comparing it with a float uniform brings back the rounding errors that the method exists to remove. Keep γ\gamma a rational and use BERNOULLI-EXP.
  • A seeded generator at line L3. The exact algorithm is only as good as its random integers. A seeded pseudorandom generator is fine for tests and wrong for a release; use a cryptographic source.
  • Run time at line L2. The number of rounds, and the work inside BERNOULLI-EXP, depend on the noise value. If an observer can time the release, the time can leak information about the noise. A deployment that exposes timing should hide it, for example by drawing the noise ahead of time, away from the request path.
  • Wrong scale at line L1. Computing tt with a float square root can be off by one for large σ2\sigma^2. Any positive integer tt keeps the output exact, but a poor tt makes the loop slow; use the integer test t2>σ2t^2 > \sigma^2.
  • Sensitivity in the wrong norm. The zCDP bound uses the ℓ2\ell_2 sensitivity, and for a single integer query it must be an integer bound on ∣f(x)−f(x′)∣|f(x) - f(x')|.

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.

discrete_gaussian_mechanism.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-gaussian-mechanism/. The authors are listed in prov/70PG4J.jsonl.
"""The discrete Gaussian mechanism with the exact sampler of Canonne, Kamath
and Steinke (NeurIPS 2020).

The noise has P[Y = y] proportional to exp(-y^2 / (2 sigma^2)) on the
integers. The sampler uses only uniform random integers and exact rational
arithmetic (fractions.Fraction): no floats, no exp, no sqrt. It is
Algorithm 1 (Bernoulli(exp(-gamma))), Algorithm 2 (discrete Laplace) and
Algorithm 3 (discrete Gaussian by rejection) of their paper.

The tests pass a seeded random.Random so that each run repeats. That is for
study only. A deployment needs a cryptographic source of randomness, for
example secrets.SystemRandom(), which has the same randrange method, and it
needs exact sampling as here: float noise from a seeded generator leaks
through its low-order bits (Mironov 2012; Canonne, Kamath and Steinke 2020).
The code assumes the word RAM, with operations on rationals of moderate size.
"""

from __future__ import annotations

import math
import random
from fractions import Fraction
from typing import Union

Rational = Union[int, Fraction]


def _as_positive_fraction(sigma2: Rational) -> Fraction:
    if isinstance(sigma2, bool) or not isinstance(sigma2, (int, Fraction)):
        raise TypeError("sigma2 must be an int or a Fraction, not a float")
    s = Fraction(sigma2)
    if s <= 0:
        raise ValueError("sigma2 must be positive")
    return s


def bernoulli(p: Fraction, rng: random.Random) -> int:
    """Return 1 with probability exactly p. Precondition: 0 <= p <= 1. Cost: O(1)."""
    if not 0 <= p <= 1:
        raise ValueError("p must be in [0, 1]")
    return 1 if rng.randrange(p.denominator) < p.numerator else 0


def _bernoulli_exp_neg_unit(gamma: Fraction, rng: random.Random) -> int:
    """Return 1 with probability exp(-gamma), for 0 <= gamma <= 1.

    Draw A_k ~ Bernoulli(gamma / k) for k = 1, 2, ... until the first 0; the
    index K of that 0 is odd with probability exp(-gamma).
    Cost: at most e expected draws.
    """
    k = 1
    while bernoulli(gamma / k, rng) == 1:
        k += 1
    return k % 2


def bernoulli_exp_neg(gamma: Rational, rng: random.Random) -> int:
    """Return 1 with probability exactly exp(-gamma). Algorithm 1 of CKS.

    Precondition: gamma >= 0 is rational. Cost: O(1) expected draws, since
    the loop stops at the first Bernoulli(exp(-1)) draw that is 0.
    """
    g = Fraction(gamma)
    if g < 0:
        raise ValueError("gamma must be non-negative")
    if g <= 1:
        return _bernoulli_exp_neg_unit(g, rng)
    whole = math.floor(g)
    for _ in range(whole):
        if _bernoulli_exp_neg_unit(Fraction(1), rng) == 0:
            return 0
    return _bernoulli_exp_neg_unit(g - whole, rng)


def discrete_laplace(t: int, rng: random.Random) -> int:
    """Return Y with P[Y = y] proportional to exp(-|y| / t). Algorithm 2 of CKS with s = 1.

    Precondition: t >= 1 is an integer. Cost: O(1) expected draws.
    """
    if t < 1:
        raise ValueError("t must be a positive integer")
    while True:
        u = rng.randrange(t)
        if bernoulli_exp_neg(Fraction(u, t), rng) == 0:
            continue
        v = 0
        while bernoulli_exp_neg(1, rng) == 1:
            v += 1
        magnitude = u + t * v  # geometric with ratio exp(-1/t)
        negative = bernoulli(Fraction(1, 2), rng)
        if negative == 1 and magnitude == 0:
            continue  # so that 0 is not counted twice
        return -magnitude if negative else magnitude


def laplace_scale_for(sigma2: Rational) -> int:
    """t = floor(sigma) + 1, the least integer t with t^2 > sigma^2. Cost: O(1)."""
    s = _as_positive_fraction(sigma2)
    t = math.isqrt(math.floor(s))
    while t * t <= s:
        t += 1
    return t


def acceptance_exponent(y: int, sigma2: Rational, t: int) -> Fraction:
    """gamma = (|y| - sigma^2 / t)^2 / (2 sigma^2), the exponent of line L4."""
    s = _as_positive_fraction(sigma2)
    d = abs(y) - s / t
    return d * d / (2 * s)


def discrete_gaussian_mechanism(value: int, sigma2: Rational, rng: random.Random) -> int:
    """Release value + Y with Y from the discrete Gaussian N_Z(0, sigma2).

    value is the true answer f(x) of an integer query. If f has sensitivity
    Delta, the release is (Delta^2 / (2 sigma2))-zCDP.
    Precondition: sigma2 > 0 rational. Cost: O(1) expected rounds of the
    loop (each round accepts with probability above 0.29).
    """
    s = _as_positive_fraction(sigma2)
    t = laplace_scale_for(s)  # @line L1
    while True:  # @line L2
        y = discrete_laplace(t, rng)  # @line L3
        gamma = acceptance_exponent(y, s, t)  # @line L4
        c = bernoulli_exp_neg(gamma, rng)  # @line L5
        if c == 1:  # @line L6
            return value + y


def discrete_gaussian(sigma2: Rational, rng: random.Random) -> int:
    """One sample of N_Z(0, sigma2). Same precondition and cost as the mechanism."""
    return discrete_gaussian_mechanism(0, sigma2, rng)


def discrete_gaussian_delta(epsilon: float, sigma2: Rational, sensitivity: int = 1) -> float:
    """The tight delta of the mechanism at epsilon, by Theorem 7 of CKS.

    delta = P[Y > epsilon sigma^2 / Delta - Delta / 2]
            - e^epsilon P[Y > epsilon sigma^2 / Delta + Delta / 2],
    with Y ~ N_Z(0, sigma^2). This is accounting, so it uses floats; the sums
    stop at |y| = 40 sigma + epsilon sigma^2 / Delta + Delta + 10, past which
    the terms are below exp(-800).
    Precondition: epsilon >= 0, sigma2 > 0, sensitivity >= 1.
    Cost: O(sigma + epsilon sigma^2) float operations.
    """
    s = float(_as_positive_fraction(sigma2))
    if epsilon < 0 or sensitivity < 1:
        raise ValueError("need epsilon >= 0 and sensitivity >= 1")
    shift = epsilon * s / sensitivity
    bound = int(40 * math.sqrt(s) + shift + sensitivity + 10)
    weights = [math.exp(-(y * y) / (2 * s)) for y in range(-bound, bound + 1)]
    total = math.fsum(weights)

    def tail(a: float) -> float:
        return math.fsum(w for y, w in zip(range(-bound, bound + 1), weights) if y > a) / total

    delta = tail(shift - sensitivity / 2) - math.exp(epsilon) * tail(shift + sensitivity / 2)
    return max(0.0, delta)
test_discrete_gaussian_mechanism.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-gaussian-mechanism/. The authors are listed in prov/70PG4J.jsonl.

import math
import random
from collections import Counter
from fractions import Fraction

import pytest

from discrete_gaussian_mechanism import (
    acceptance_exponent,
    bernoulli,
    bernoulli_exp_neg,
    discrete_gaussian,
    discrete_gaussian_delta,
    discrete_gaussian_mechanism,
    discrete_laplace,
    laplace_scale_for,
)

BETA = 1e-6  # failure probability for each Hoeffding or DKW margin


def margin(n):
    return math.sqrt(math.log(2 / BETA) / (2 * n))


def gauss_pmf(sigma2, lo, hi):
    """The discrete Gaussian pmf on [lo, hi], normalized over a wide range."""
    s = float(sigma2)
    wide = int(60 * math.sqrt(s)) + 60
    total = math.fsum(math.exp(-(y * y) / (2 * s)) for y in range(-wide, wide + 1))
    return {y: math.exp(-(y * y) / (2 * s)) / total for y in range(lo, hi + 1)}


def hockey_stick(epsilon, sigma2, sensitivity):
    """sum_y (p(y) - e^epsilon p(y - Delta))_+ by brute force over a wide range."""
    s = float(sigma2)
    wide = int(60 * math.sqrt(s) + epsilon * s + 2 * sensitivity) + 60
    w = {y: math.exp(-(y * y) / (2 * s)) for y in range(-wide - sensitivity, wide + 1)}
    total = math.fsum(w[y] for y in range(-wide, wide + 1))
    terms = (w[y] - math.exp(epsilon) * w[y - sensitivity] for y in range(-wide, wide + 1))
    return math.fsum(max(0.0, d) for d in terms) / total


def test_worked_example():
    # sigma^2 = 4: t = floor(2) + 1 = 3, and Y = 2 is kept with probability exp(-1/18).
    assert laplace_scale_for(4) == 3
    assert acceptance_exponent(2, 4, 3) == Fraction(1, 18)
    assert acceptance_exponent(0, 4, 3) == Fraction(2, 9)
    assert acceptance_exponent(-5, 4, 3) == Fraction(121, 72)
    assert discrete_gaussian_delta(1.0, 4) == pytest.approx(0.0072488, abs=1e-7)


def test_scale_edges():
    assert laplace_scale_for(1) == 2
    assert laplace_scale_for(Fraction(9, 4)) == 2
    assert laplace_scale_for(Fraction(1, 4)) == 1
    assert laplace_scale_for(Fraction(99, 100)) == 1
    assert laplace_scale_for(10**12) == 10**6 + 1


def test_bad_input():
    rng = random.Random(1)
    with pytest.raises(TypeError):
        discrete_gaussian(4.0, rng)
    with pytest.raises(ValueError):
        discrete_gaussian(0, rng)
    with pytest.raises(ValueError):
        bernoulli_exp_neg(Fraction(-1, 2), rng)
    with pytest.raises(ValueError):
        discrete_laplace(0, rng)
    with pytest.raises(ValueError):
        bernoulli(Fraction(3, 2), rng)


def test_bernoulli_edges():
    rng = random.Random(2)
    assert all(bernoulli(Fraction(0), rng) == 0 for _ in range(100))
    assert all(bernoulli(Fraction(1), rng) == 1 for _ in range(100))
    assert all(bernoulli_exp_neg(0, rng) == 1 for _ in range(100))


def test_bernoulli_exp_neg_frequencies():
    rng = random.Random(3)
    n = 2500
    for gamma in [Fraction(1, 3), Fraction(1), Fraction(5, 2), Fraction(7)]:
        hits = sum(bernoulli_exp_neg(gamma, rng) for _ in range(n))
        assert abs(hits / n - math.exp(-float(gamma))) <= margin(n)


def test_discrete_laplace_frequencies():
    rng = random.Random(4)
    n = 4000
    t = 2
    counts = Counter(discrete_laplace(t, rng) for _ in range(n))
    r = math.exp(-1 / t)
    for y in range(-6, 7):
        want = (1 - r) / (1 + r) * r ** abs(y)
        assert abs(counts[y] / n - want) <= margin(n)


@pytest.mark.parametrize("sigma2,seed", [(4, 5), (Fraction(1, 3), 6), (Fraction(50, 7), 7)])
def test_discrete_gaussian_against_exact_pmf(sigma2, seed):
    rng = random.Random(seed)
    n = 2000
    samples = [discrete_gaussian(sigma2, rng) for _ in range(n)]
    counts = Counter(samples)
    width = int(6 * math.sqrt(float(sigma2))) + 2
    pmf = gauss_pmf(sigma2, -width, width)
    cdf_got = cdf_want = 0.0
    for y in range(-width, width + 1):
        assert abs(counts[y] / n - pmf[y]) <= margin(n)
        cdf_got += counts[y] / n
        cdf_want += pmf[y]
        assert abs(cdf_got - cdf_want) <= margin(n)  # the DKW inequality
    # Variance at most sigma^2 (Canonne, Kamath and Steinke, Corollary 17), up to sampling error.
    var = sum(y * y for y in samples) / n
    assert var <= float(sigma2) * (1 + 0.2) + 0.05


def test_mechanism_adds_the_noise():
    for seed in range(20):
        a = discrete_gaussian_mechanism(10, Fraction(5, 2), random.Random(seed))
        b = discrete_gaussian(Fraction(5, 2), random.Random(seed))
        assert a == 10 + b


def test_delta_decreases_and_matches_known_values():
    values = [discrete_gaussian_delta(e / 4, 4) for e in range(0, 17)]
    assert all(x >= y for x, y in zip(values, values[1:]))
    assert discrete_gaussian_delta(0.5, 4) == pytest.approx(0.0540072, abs=1e-7)
    assert discrete_gaussian_delta(2.0, 4) == pytest.approx(1.07409e-05, rel=1e-4)
    # More noise gives a smaller delta.
    assert discrete_gaussian_delta(1.0, 16) < discrete_gaussian_delta(1.0, 4)


def test_random_delta_against_hockey_stick():
    rng = random.Random(2020)
    for _ in range(500):
        sigma2 = Fraction(rng.randint(1, 240), rng.randint(4, 8))
        epsilon = rng.uniform(0.0, 3.0)
        sensitivity = rng.randint(1, 3)
        got = discrete_gaussian_delta(epsilon, sigma2, sensitivity)
        assert got == pytest.approx(hockey_stick(epsilon, sigma2, sensitivity), rel=1e-7, abs=1e-12)


def test_random_rejection_identity_exact():
    # Line L4 must make Laplace weight times acceptance proportional to the Gaussian weight:
    # -|y|/t - gamma(y) = -y^2/(2 sigma^2) - sigma^2/(2 t^2), exactly.
    rng = random.Random(70)
    for _ in range(500):
        sigma2 = Fraction(rng.randint(1, 500), rng.randint(1, 9))
        t = laplace_scale_for(sigma2)
        assert (t - 1) ** 2 <= sigma2 < t * t
        y = rng.randint(-60, 60)
        lhs = -Fraction(abs(y), t) - acceptance_exponent(y, sigma2, t)
        rhs = -Fraction(y * y) / (2 * sigma2) - sigma2 / (2 * t * t)
        assert lhs == rhs

History

The discrete Gaussian has long been used in lattice-based cryptography, where it is the noise of many schemes and of trapdoor sampling. In differential privacy, Mironov (2012) showed that float implementations of the Laplace mechanism can leak through the low-order bits of their outputs, and proposed the snapping mechanism. Canonne, Kamath and Steinke (NeurIPS 2020) analyzed the discrete Gaussian as a privacy mechanism, showed that it matches the continuous Gaussian under zCDP, gave its exact (ε,δ)(\varepsilon, \delta) curve, and gave the exact sampler of this page. The US Census Bureau used discrete Gaussian noise with zCDP accounting in the disclosure avoidance system of the 2020 Census.

References

  1. Clement L. Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, arXiv 2004.00010, Definition 1 (discrete Gaussian), Theorem 4 (zCDP), Proposition 5 and Lemma 6 (Renyi divergence), Theorem 7 (tight (epsilon, delta)), Corollary 17 (variance), Section 5 (Algorithms 1, 2 and 3, Propositions 33 and 34, Theorem 32)
  2. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, the weakness of floating point implementations of noise and the snapping mechanism as a fix
  3. Mark Bun and Thomas Steinke, Concentrated differential privacy: simplifications, extensions, and lower bounds, TCC 2016-B, LNCS 9985, pages 635 to 658, Definition 1.1 (zCDP) and Proposition 1.3 (conversion to approximate DP)

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.expected
  • 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