Algorithm Search⌘K

Algorithmadvanced

Moments accountant

Also called privacy accountant for DP-SGD, RDP accountant.

Tracks the log moments of the privacy loss of each subsampled Gaussian step, adds them over the steps, and turns the sum into an (epsilon, delta) bound by a tail bound.

Time
O(m^2) worst
Space
O(m) extra
Where
m = the largest moment order that is tried
Properties
deterministicnot randomized
Origin
Martin Abadi, Andy Chu, Ian Goodfellow, H. Brendan McMahan, Ilya Mironov, Kunal Talwar, Li Zhang, 2016

The moments accountant computes the privacy cost of training with DP-SGD, where each step picks a random batch of records, clips their gradients, adds them, and adds Gaussian noise. Abadi and coauthors introduced it in 2016. Instead of a pair (ε,δ)(\varepsilon, \delta) per step, it tracks the log of the moment generating function of the privacy loss random variable at a few orders λ\lambda. These log moments add up exactly under composition, and a tail bound at the end turns the sum into one (ε,δ)(\varepsilon, \delta) guarantee. For a step with sampling rate q=0.01q = 0.01 and noise multiplier σ=4\sigma = 4, ten thousand steps cost about ε=1.26\varepsilon = 1.26 at δ=10−5\delta = 10^{-5}, while the advanced composition theorem on the same steps gives about 9.349.34. The log moment of order λ\lambda is λ\lambda times the Renyi divergence of order λ+1\lambda + 1, so the accountant is Renyi DP accounting at integer orders. This page gives the version with the exact finite sum of Mironov, Talwar and Zhang.

In plain words

Training a private model takes thousands of small noisy steps, and each step leaks a little about each person. Adding the worst-case leak of each step gives a total that is far too large to be useful.

The accountant keeps a better record. For each step it notes a few summary numbers that describe how the leak is spread out, not only its worst case. These numbers just add from step to step. At the end, one short calculation turns the totals into the usual privacy guarantee. Because the step uses a random batch, most people are not in it, and the numbers for one step are very small.

The problem

One step of the subsampled Gaussian mechanism, under add/remove neighbors:

  • keep each record independently with probability qq (Poisson sampling);
  • for each kept record, compute a vector and clip it to ℓ2\ell_2 norm at most 1;
  • release the sum of the clipped vectors plus N(0,σ2I)N(0, \sigma^2 I).

The vectors of a step may depend on the outputs of earlier steps. Input: the rate q∈[0,1]q \in [0, 1], the noise multiplier σ>0\sigma > 0, the number of steps TT, a target δ∈(0,1)\delta \in (0, 1), and the largest order mm to try. Output: an ε\varepsilon such that the TT steps together are (ε,δ)(\varepsilon, \delta)-DP, as small as the method allows, and the order λ\lambda that gives it.

For one step, let μ0=N(0,σ2)\mu_0 = N(0, \sigma^2) and μ=(1−q)μ0+qN(1,σ2)\mu = (1 - q)\mu_0 + q N(1, \sigma^2). The log moment of order λ\lambda that the accountant uses is

α(λ)=ln⁡Ez∼μ[(μ(z)μ0(z))λ]=ln⁡Aλ+1,Aa=∑k=0a(ak)(1−q)a−kqke(k2−k)/(2σ2).\alpha(\lambda) = \ln E_{z \sim \mu}\left[\left(\frac{\mu(z)}{\mu_0(z)}\right)^{\lambda}\right] = \ln A_{\lambda + 1}, \qquad A_a = \sum_{k=0}^{a}\binom{a}{k}(1-q)^{a-k}q^k e^{(k^2 - k)/(2\sigma^2)}.

The algorithm

  1. MOMENTS-ACCOUNTANT(q, sigma, T, delta, m)
  2. 1for lambda <- 1 to m do
  3. 2a <- lambda + 1
  4. 3t_k <- ln C(a, k) + (a - k) ln(1 - q) + k ln q + (k^2 - k)/(2 sigma^2) for k = 0..a
  5. 4alpha <- LOG-SUM-EXP(t_0, ..., t_a) ▷ alpha = ln A_a
  6. 5eps_lambda <- (T alpha + ln(1/delta)) / lambda
  7. 6keep the smallest eps_lambda and its lambda
  8. 7return the smallest eps_lambda and its lambda

Line L1 tries each integer order. Lines L2 and L3 write the a+1a + 1 terms of the binomial sum AaA_a as logs; a term with q=0q = 0 or q=1q = 1 that is 0 is left out. Line L4 adds the terms with the log-sum-exp trick: subtract the largest tkt_k, add the exponentials, take the log, and add the largest back. This is needed, because for small σ\sigma and large kk the term e(k2−k)/(2σ2)e^{(k^2 - k)/(2\sigma^2)} overflows a float. Line L5 applies the tail bound to the sum TαT\alpha of the log moments of TT steps. Lines L6 and L7 return the best order.

The same sum gives δ\delta for a fixed ε\varepsilon: δ=min⁡λeTα(λ)−λε\delta = \min_\lambda e^{T\alpha(\lambda) - \lambda\varepsilon}. The code has both directions.

The accountant does only arithmetic on public parameters; it does not touch data or draw noise. The training that it accounts for must draw its noise from a cryptographic source of randomness with an exact sampler, because float noise from a seeded generator leaks through its low-order bits (Mironov 2012; Canonne, Kamath and Steinke 2020). The discrete Gaussian mechanism page shows an exact sampler.

Example

Take q=0.1q = 0.1, σ=1\sigma = 1, T=10T = 10, δ=10−5\delta = 10^{-5} and m=8m = 8, so ln⁡(1/δ)=11.5129\ln(1/\delta) = 11.5129. For λ=1\lambda = 1, the order is a=2a = 2 and A2=1+q2(e1/σ2−1)=1.017183A_2 = 1 + q^2(e^{1/\sigma^2} - 1) = 1.017183, so α(1)=0.017037\alpha(1) = 0.017037.

λ\lambda aa (L2) α(λ)\alpha(\lambda) (L4) Tα(λ)T\alpha(\lambda) ελ\varepsilon_\lambda (L5) best so far (L6)
1 2 0.017037 0.170369 11.6833 11.6833 at 1
2 3 0.063425 0.634246 6.0736 6.0736 at 2
3 4 0.176018 1.760178 4.4244 4.4244 at 3
4 5 0.519510 5.195097 4.1770 4.1770 at 4
5 6 1.855472 18.554718 6.0135 4.1770 at 4
6 7 5.068282 50.682817 10.3660 4.1770 at 4
7 8 9.648530 96.485299 15.4283 4.1770 at 4
8 9 15.304462 153.044625 20.5697 4.1770 at 4

Line L7 returns ε=4.177\varepsilon = 4.177 at λ=4\lambda = 4. Small orders pay too much for ln⁡(1/δ)/λ\ln(1/\delta)/\lambda; large orders pay too much for Tα(λ)/λT\alpha(\lambda)/\lambda, which grows fast once the top terms of the sum, with their factor e(k2−k)/(2σ2)e^{(k^2 - k)/(2\sigma^2)}, beat the small factor qkq^k.

A second check, the setting of Abadi et al.: q=0.01q = 0.01, σ=4\sigma = 4, T=10000T = 10000, δ=10−5\delta = 10^{-5} and m=32m = 32 give ε=1.2586\varepsilon = 1.2586 at λ=19\lambda = 19. The paper reports about 1.261.26.

Correctness

Theorem. Let ε∗\varepsilon^* be the output of MOMENTS-ACCOUNTANT(q,σ,T,δ,m)(q, \sigma, T, \delta, m). Then TT adaptively composed steps of the subsampled Gaussian mechanism, with Poisson rate qq, clipping norm 1 and noise N(0,σ2I)N(0, \sigma^2 I), are (ε∗,δ)(\varepsilon^*, \delta)-DP under add/remove neighbors.

The proof in proofs/correctness.md has four steps. First, lines L2 to L4 compute ln⁡Aλ+1\ln A_{\lambda + 1} exactly in the real RAM, by the binomial theorem and the identity Eμ0[(μ1/μ0)k]=e(k2−k)/(2σ2)E_{\mu_0}[(\mu_1/\mu_0)^k] = e^{(k^2 - k)/(2\sigma^2)} for μ1=N(1,σ2)\mu_1 = N(1, \sigma^2). Second, for one step and each pair of neighbors, the log moment of order λ\lambda of the privacy loss is at most ln⁡Aλ+1\ln A_{\lambda + 1}: for the neighbor with the extra record this follows by joint convexity and a reduction to one dimension, and for the other order it is a result of Mironov, Talwar and Zhang that we cite. Third, log moments add over adaptive steps, by conditioning on the earlier outputs. Fourth, Markov's inequality on eλZe^{\lambda Z} gives Pr⁡[Z>ελ]≤δ\Pr[Z > \varepsilon_\lambda] \le \delta, and a tail bound of this form implies (ελ,δ)(\varepsilon_\lambda, \delta)-DP. Each ελ\varepsilon_\lambda is valid, so their minimum is valid.

Proof: The moments accountant gives a valid (epsilon, delta) bound for the subsampled Gaussianfull

We work in the real RAM. One step of the mechanism, with the outputs of the earlier steps fixed, is as follows. Each record of the dataset is kept independently with probability qq; this gives the batch BB. Each record ii has a vector gi∈Rdg_i \in \mathbb R^d with ∥gi∥2≤1\lVert g_i \rVert_2 \le 1, which may depend on the earlier outputs. The step releases sB+N(0,σ2Id)s_B + N(0, \sigma^2 I_d), where sB=∑i∈Bgis_B = \sum_{i \in B} g_i. Neighbors are add/remove: x′=x∪{r}x' = x \cup \{r\}.

For distributions P,QP, Q with positive densities p,qp, q and λ>0\lambda > 0, write

cλ(P∥Q)=ln⁡∫pλ+1q−λ=ln⁡EY∼P[eλℓ(Y)],ℓ=ln⁡pq.c_\lambda(P\|Q) = \ln \int p^{\lambda + 1}q^{-\lambda} = \ln E_{Y \sim P}\left[e^{\lambda \ell(Y)}\right], \qquad \ell = \ln\frac{p}{q}.

Let φc\varphi_c be the density of N(c,σ2)N(c, \sigma^2) on R\mathbb R, and for a=λ+1a = \lambda + 1 and c≥0c \ge 0 let

Aa(c)=∑k=0a(ak)(1−q)a−kqke(k2−k)c2/(2σ2).A_a(c) = \sum_{k=0}^{a}\binom{a}{k}(1-q)^{a-k}q^k e^{(k^2 - k)c^2/(2\sigma^2)}.

So Aa=Aa(1)A_a = A_a(1) is the sum of the page.

Lemma 1 (Gaussian moments). For every integer k≥0k \ge 0 and c≥0c \ge 0, ∫φ0(φc/φ0)k=e(k2−k)c2/(2σ2)\int \varphi_0 (\varphi_c/\varphi_0)^k = e^{(k^2 - k)c^2/(2\sigma^2)}. Hence ∫((1−q)φ0+qφc)aφ01−a=Aa(c)\int ((1-q)\varphi_0 + q\varphi_c)^a\varphi_0^{1-a} = A_a(c).

Proof. φc(z)/φ0(z)=exp⁡((2cz−c2)/(2σ2))\varphi_c(z)/\varphi_0(z) = \exp((2cz - c^2)/(2\sigma^2)). For Z∼N(0,σ2)Z \sim N(0, \sigma^2), E[etZ]=et2σ2/2E[e^{tZ}] = e^{t^2\sigma^2/2}. With t=kc/σ2t = kc/\sigma^2,

E[(φc/φ0)k(Z)]=e−kc2/(2σ2)ek2c2/(2σ2).E\left[(\varphi_c/\varphi_0)^k(Z)\right] = e^{-kc^2/(2\sigma^2)}e^{k^2c^2/(2\sigma^2)}.

For the second claim write the integrand as φ0⋅(1−q+qR)a\varphi_0 \cdot (1 - q + qR)^a with R=φc/φ0R = \varphi_c/\varphi_0, expand by the binomial theorem, and apply the first claim to each term. □\square

Lemma 2 (lines L2 to L4). For each λ\lambda, the value α\alpha of line L4 equals ln⁡Aλ+1\ln A_{\lambda + 1}.

Proof. Line L2 sets a=λ+1a = \lambda + 1. Each term of AaA_a with a non-zero coefficient is positive, and line L3 computes its log tkt_k; the terms that are 0 (the cases q=0q = 0, k>0k > 0 and q=1q = 1, k<ak < a) are left out and do not change the sum. At least one term remains. With M=max⁡ktkM = \max_k t_k, line L4 returns M+ln⁡∑ketk−M=ln⁡∑ketk=ln⁡AaM + \ln\sum_k e^{t_k - M} = \ln\sum_k e^{t_k} = \ln A_a. □\square

Lemma 3 (one step, larger dataset first). Fix the earlier outputs. Let PP and P′P' be the laws of the step on xx and on x′=x∪{r}x' = x \cup \{r\}. Then cλ(P′∥P)≤ln⁡Aλ+1c_\lambda(P'\|P) \le \ln A_{\lambda + 1} for every integer λ≥1\lambda \ge 1.

Proof. Let a=λ+1a = \lambda + 1, and let pBp_B be the density of N(sB,σ2I)N(s_B, \sigma^2 I). A Poisson sample of x′x' is BB, or B∪{r}B \cup \{r\} with probability qq, independently of BB. So

p=EB[pB],p′=EB[pB′],pB′=(1−q)pB+q pB(⋅−gr).p = E_B[p_B], \qquad p' = E_B[p'_B], \qquad p'_B = (1 - q)p_B + q\,p_{B}(\cdot - g_r).

The map (u,v)↦uav1−a=v(u/v)a(u, v) \mapsto u^a v^{1-a} = v(u/v)^a on (0,∞)2(0, \infty)^2 is the perspective of the convex function u↦uau \mapsto u^a, so it is jointly convex. BB takes finitely many values, so Jensen's inequality at each point yy gives p′(y)ap(y)1−a≤EB[pB′(y)apB(y)1−a]p'(y)^a p(y)^{1-a} \le E_B[p'_B(y)^a p_B(y)^{1-a}]. Integrate over yy and swap the integral and the finite average:

∫p′ap1−a≤EB∫(pB′)apB1−a.\int p'^a p^{1-a} \le E_B \int (p'_B)^a p_B^{1-a}.

Fix BB. Translate by sBs_B and rotate so that gr=c e1g_r = c\,e_1 with c=∥gr∥2≤1c = \lVert g_r \rVert_2 \le 1. Both densities are products of the same factor in coordinates 2,…,d2, \ldots, d, which integrates to 1, and of (1−q)φ0+qφc(1-q)\varphi_0 + q\varphi_c and φ0\varphi_0 in coordinate 1. By Lemma 1 the inner integral is Aa(c)A_a(c). Every exponent (k2−k)c2/(2σ2)(k^2 - k)c^2/(2\sigma^2) is non-negative and grows with cc, so Aa(c)≤Aa(1)=AaA_a(c) \le A_a(1) = A_a. Hence ∫p′ap1−a≤Aa\int p'^a p^{1-a} \le A_a, and cλ(P′∥P)=ln⁡∫p′ap1−a≤ln⁡Aac_\lambda(P'\|P) = \ln\int p'^a p^{1-a} \le \ln A_a. □\square

Lemma 4 (one step, smaller dataset first). With the notation of Lemma 3, cλ(P∥P′)≤ln⁡Aλ+1c_\lambda(P\|P') \le \ln A_{\lambda + 1} for every integer λ≥1\lambda \ge 1.

Proof. The joint convexity step of Lemma 3, with the roles of the two arguments swapped, reduces the claim to Ba(c)≤Aa(1)B_a(c) \le A_a(1), where Ba(c)=∫φ0a((1−q)φ0+qφc)1−aB_a(c) = \int \varphi_0^a((1-q)\varphi_0 + q\varphi_c)^{1-a} and c≤1c \le 1. If c=0c = 0, then Ba(0)=1≤Aa(1)B_a(0) = 1 \le A_a(1). For c>0c > 0, the pair with shift cc and noise σ\sigma is the pair with shift 1 and noise σ/c\sigma/c after a scaling of the axis, and scaling does not change these integrals. Mironov, Talwar and Zhang (arXiv 1908.10530, Section 3.1 with Theorem 4) prove Ba≤AaB_a \le A_a for shift 1 and every noise level. So Ba(c)≤Aa(c)≤Aa(1)B_a(c) \le A_a(c) \le A_a(1) by the monotonicity in Lemma 3. This is the one step that we cite and do not prove here. □\square

Lemma 5 (adaptive composition). Let Y=(Y1,…,YT)Y = (Y_1, \ldots, Y_T) be the outputs of TT steps on a dataset with law PP, and on its neighbor with law QQ. If, for each tt and each fixed prefix y<ty_{<t}, the conditional laws satisfy cλ(Pt(⋅∣y<t)∥Qt(⋅∣y<t))≤αc_\lambda(P_t(\cdot \mid y_{<t})\|Q_t(\cdot \mid y_{<t})) \le \alpha, then cλ(P∥Q)≤Tαc_\lambda(P\|Q) \le T\alpha.

Proof. The privacy loss of the whole output is ℓ(y)=∑tℓt(yt∣y<t)\ell(y) = \sum_t \ell_t(y_t \mid y_{<t}), the sum of the conditional privacy losses, because the densities factor as products of the conditional densities. Then

EP[eλℓ(Y)]=EP[eλ∑t<Tℓt EP[eλℓT∣Y<T]]≤eαEP[eλ∑t<Tℓt],E_P\left[e^{\lambda\ell(Y)}\right] = E_P\left[e^{\lambda\sum_{t < T}\ell_t}\,E_P\left[e^{\lambda\ell_T} \mid Y_{<T}\right]\right] \le e^{\alpha}E_P\left[e^{\lambda\sum_{t < T}\ell_t}\right],

and induction on TT gives eTαe^{T\alpha}. □\square

Lemma 6 (tail bound to DP). Let L=ℓ(Y)L = \ell(Y) with Y∼PY \sim P. If Pr⁡[L>ε]≤δ\Pr[L > \varepsilon] \le \delta, then P(S)≤eεQ(S)+δP(S) \le e^{\varepsilon}Q(S) + \delta for every event SS.

Proof. On the set {ℓ≤ε}\{\ell \le \varepsilon\} we have p≤eεqp \le e^{\varepsilon}q. So P(S)=P(S∩{ℓ≤ε})+P(S∩{ℓ>ε})≤eεQ(S)+δP(S) = P(S \cap \{\ell \le \varepsilon\}) + P(S \cap \{\ell > \varepsilon\}) \le e^{\varepsilon}Q(S) + \delta. □\square

Theorem. The output ε∗\varepsilon^* of MOMENTS-ACCOUNTANT(q,σ,T,δ,m)(q, \sigma, T, \delta, m) makes the TT composed steps (ε∗,δ)(\varepsilon^*, \delta)-DP under add/remove neighbors.

Proof. Fix neighbors and either order of the pair, and fix λ∈{1,…,m}\lambda \in \{1, \ldots, m\}. Let α=ln⁡Aλ+1\alpha = \ln A_{\lambda + 1}, the value of line L4 by Lemma 2. Lemmas 3 and 4 bound the conditional log moment of each step by α\alpha in both orders and for every prefix, so Lemma 5 gives E[eλL]≤eTαE[e^{\lambda L}] \le e^{T\alpha} for the privacy loss LL of the TT outputs. With ελ=(Tα+ln⁡(1/δ))/λ\varepsilon_\lambda = (T\alpha + \ln(1/\delta))/\lambda of line L5, Markov's inequality gives

Pr⁡[L>ελ]=Pr⁡[eλL>eλελ]≤eTα−λελ=e−ln⁡(1/δ)=δ.\Pr[L > \varepsilon_\lambda] = \Pr\left[e^{\lambda L} > e^{\lambda\varepsilon_\lambda}\right] \le e^{T\alpha - \lambda\varepsilon_\lambda} = e^{-\ln(1/\delta)} = \delta.

By Lemma 6, the composition is (ελ,δ)(\varepsilon_\lambda, \delta)-DP for this ordered pair, and so for all of them. Lines L6 and L7 return the smallest ελ\varepsilon_\lambda over λ≤m\lambda \le m, which is one of these valid values. The loop of line L1 runs mm times, and the inner work is O(λ)O(\lambda), so the procedure stops. ■\blacksquare

Complexity

In the real RAM, order λ\lambda costs O(λ)O(\lambda) operations at lines L3 and L4, so the whole run costs ∑λ≤mO(λ)=O(m2)\sum_{\lambda \le m} O(\lambda) = O(m^2) time and O(m)O(m) extra space for the terms of one order. The cost does not depend on TT, because composition is one multiplication by TT. Abadi et al. used λ≤32\lambda \le 32, so mm is small in practice. A float version needs the log-sum-exp form of line L4, or the terms overflow.

Properties

  • Exact for its pair. For integer orders, α(λ)\alpha(\lambda) is the exact log moment of the one-dimensional pair, not an approximation. The asymptotic form in the paper of Abadi et al., q2λ(λ+1)/((1−q)σ2)+O(q3λ3/σ3)q^2\lambda(\lambda + 1)/((1 - q)\sigma^2) + O(q^3\lambda^3/\sigma^3), holds only under conditions on qq, σ\sigma and λ\lambda, and has a hidden term; the finite sum has neither problem.
  • Additive. The state of the accountant during training is one vector of mm numbers, ∑stepsαstep(λ)\sum_{\text{steps}}\alpha_{\text{step}}(\lambda). Steps with different qq or σ\sigma simply add their own vectors.
  • Pure arithmetic. It reads no data and has no randomness.
  • Monotone. ε∗\varepsilon^* grows with TT and qq, and shrinks as σ\sigma or δ\delta grows.

Variants and improvements

  • Fractional orders. Mironov, Talwar and Zhang give a series for real orders α>1\alpha > 1. A finer grid of orders gives a slightly smaller ε\varepsilon.
  • Better conversions. The step from Renyi divergence to (ε,δ)(\varepsilon, \delta) in line L5 loses a little. Later conversions shave this loss.
  • Numerical accounting. Numerical privacy accounting composes the full privacy loss distribution with the FFT, and gives an ε\varepsilon within a stated error of the exact value, which is smaller than the moments bound.
  • GDP accounting. The central limit theorem of Gaussian differential privacy gives a simple approximation for many steps, but it is not an upper bound in general.
  • Other sampling schemes. Sampling a fixed batch size without replacement under replace neighbors has its own bound, which is not AaA_a.

When to use it

Use the moments accountant, or an RDP accountant built the same way, for long runs of subsampled Gaussian steps, as in DP-SGD and federated learning with Gaussian noise. It is simple, fast, and always an upper bound. Use numerical accounting when the last few percent of ε\varepsilon matter, and the advanced composition theorem only for steps that have nothing but an (ε,δ)(\varepsilon, \delta) guarantee.

Pitfalls

  • Wrong sampling scheme at line L3. The sum AaA_a is for Poisson sampling with add/remove neighbors. Many training loops shuffle the data and take fixed-size batches; the bound for that scheme is different, and reporting the Poisson number for it is an error.
  • Overflow at line L4. Adding etke^{t_k} directly overflows for small σ\sigma and large λ\lambda. Use log-sum-exp, as in the pseudocode.
  • Too few orders at line L1. If the best order is mm itself, the minimum may lie beyond mm; raise mm and run again.
  • Clipping not enforced. The bound assumes that each record changes the sum by at most 1 in ℓ2\ell_2 norm. If the clip norm is CC, the noise must be N(0,σ2C2I)N(0, \sigma^2C^2 I), and σ\sigma in the accountant is the ratio.
  • Only one order of the pair. Abadi et al. take the maximum of the two orders of the privacy loss. The formula here uses only the order with the extra record, which is correct because Mironov, Talwar and Zhang proved that it dominates. A homemade variant for another mechanism must check both orders.

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.

moments_accountant.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moments-accountant/. The authors are listed in prov/BBS4G5.jsonl.
"""The moments accountant of Abadi et al. (2016) for the subsampled Gaussian.

One step of DP-SGD keeps each record with probability q (Poisson sampling),
adds the clipped gradients (l2 norm at most 1), and adds N(0, sigma^2) noise
to each coordinate. Under add/remove neighbors, the log moment of order lam
of the privacy loss of one step is at most

    alpha(lam) = ln A_{lam+1},
    A_a = sum_{k=0}^{a} C(a, k) (1-q)^(a-k) q^k exp((k^2 - k) / (2 sigma^2)),

for integer lam >= 1 (Mironov, Talwar and Zhang 2019). Log moments add over
T steps, and the tail bound gives (epsilon, delta)-DP with

    epsilon = min over lam of (T alpha(lam) + ln(1/delta)) / lam.

The accountant only does arithmetic on the parameters. A deployment of the
mechanism that it accounts for needs a cryptographic source of randomness and
exact sampling of the noise, because float noise leaks through its low-order
bits (Mironov 2012; Canonne, Kamath and Steinke 2020).
"""

from __future__ import annotations

import math
from typing import List, Tuple


def _check(q: float, sigma: float) -> None:
    if not 0.0 <= q <= 1.0:
        raise ValueError("q must be in [0, 1]")
    if not sigma > 0.0:
        raise ValueError("sigma must be positive")


def log_moment(q: float, sigma: float, lam: int) -> float:
    """alpha(lam) = ln A_{lam+1} for one subsampled Gaussian step.

    Precondition: 0 <= q <= 1, sigma > 0, lam >= 1 an integer.
    Cost: O(lam) arithmetic operations in the real RAM.
    """
    _check(q, sigma)
    if lam < 1:
        raise ValueError("lam must be a positive integer")
    a = lam + 1  # @line L2
    terms: List[float] = []
    for k in range(a + 1):  # @line L3
        if (q == 0.0 and k > 0) or (q == 1.0 and k < a):
            continue  # this term is 0; its log is minus infinity
        t = math.log(math.comb(a, k)) + (k * k - k) / (2.0 * sigma * sigma)
        if k < a:
            t += (a - k) * math.log1p(-q)
        if k > 0:
            t += k * math.log(q)
        terms.append(t)
    m = max(terms)  # @line L4
    return m + math.log(sum(math.exp(t - m) for t in terms))


def moments_accountant(
    q: float, sigma: float, steps: int, delta: float, max_order: int = 32
) -> Tuple[float, int]:
    """The epsilon of `steps` subsampled Gaussian steps at the given delta.

    Returns (epsilon, lam) where lam is the order that gives the minimum.
    Precondition: 0 <= q <= 1, sigma > 0, steps >= 1, 0 < delta < 1,
    max_order >= 1. Cost: O(m^2) arithmetic operations for m = max_order,
    and O(m) extra space.
    """
    _check(q, sigma)
    if steps < 1 or max_order < 1 or not 0.0 < delta < 1.0:
        raise ValueError("need steps >= 1, max_order >= 1 and 0 < delta < 1")
    best_eps = math.inf
    best_lam = 0
    for lam in range(1, max_order + 1):  # @line L1
        alpha = log_moment(q, sigma, lam)  # lines L2 to L4
        eps_lam = (steps * alpha + math.log(1.0 / delta)) / lam  # @line L5
        if eps_lam < best_eps:  # @line L6
            best_eps, best_lam = eps_lam, lam
    return best_eps, best_lam  # @line L7


def delta_for_epsilon(
    q: float, sigma: float, steps: int, epsilon: float, max_order: int = 32
) -> float:
    """The delta that the tail bound gives for a target epsilon.

    delta = min over lam of exp(T alpha(lam) - lam epsilon), capped at 1.
    Precondition: as for moments_accountant, and epsilon >= 0.
    Cost: O(m^2) arithmetic operations for m = max_order.
    """
    _check(q, sigma)
    if steps < 1 or max_order < 1 or epsilon < 0:
        raise ValueError("need steps >= 1, max_order >= 1 and epsilon >= 0")
    best = 0.0  # log of the best delta so far; delta <= 1 always holds
    for lam in range(1, max_order + 1):
        best = min(best, steps * log_moment(q, sigma, lam) - lam * epsilon)
    return math.exp(best)
test_moments_accountant.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moments-accountant/. The authors are listed in prov/BBS4G5.jsonl.

import math
import random
from fractions import Fraction

import pytest

from moments_accountant import delta_for_epsilon, log_moment, moments_accountant


def exact_moment(q, b, a):
    """A_a as an exact Fraction when exp(1 / (2 sigma^2)) = b is rational.

    Then exp((k^2 - k) / (2 sigma^2)) = b^(k^2 - k), and the binomial sum is
    rational. This oracle never uses logs or the code under test.
    """
    total = Fraction(0)
    for k in range(a + 1):
        total += math.comb(a, k) * (1 - q) ** (a - k) * q**k * b ** (k * k - k)
    return total


def log_fraction(x):
    return math.log(x.numerator) - math.log(x.denominator)


def sigma_for(b):
    """The sigma with exp(1 / (2 sigma^2)) = b, for b > 1."""
    return 1.0 / math.sqrt(2.0 * math.log(b))


def gauss_log_pdf(z, mean, sigma):
    return -((z - mean) ** 2) / (2 * sigma * sigma) - math.log(sigma * math.sqrt(2 * math.pi))


def integral_moments(q, sigma, lam, n=2000):
    """E1 = E_mu0[(mu0/mu)^lam] and E2 = E_mu[(mu/mu0)^lam] by Simpson's rule.

    mu0 = N(0, sigma^2) and mu = (1-q) N(0, sigma^2) + q N(1, sigma^2). This
    oracle integrates the densities and does not use the binomial formula.
    """
    lo = -12.0 * sigma - 1.0
    hi = lam + 1 + 12.0 * sigma + 1.0
    h = (hi - lo) / n
    e1 = e2 = 0.0
    for i in range(n + 1):
        z = lo + i * h
        l0 = gauss_log_pdf(z, 0.0, sigma)
        l1 = gauss_log_pdf(z, 1.0, sigma)
        top = max(l0, l1)
        lm = top + math.log((1 - q) * math.exp(l0 - top) + q * math.exp(l1 - top))
        w = 1 if i in (0, n) else (4 if i % 2 else 2)
        e1 += w * math.exp((lam + 1) * l0 - lam * lm)
        e2 += w * math.exp((lam + 1) * lm - lam * l0)
    return e1 * h / 3, e2 * h / 3


def test_worked_example():
    expected = [0.017037, 0.063425, 0.176018, 0.519510]
    for lam, want in enumerate(expected, start=1):
        assert abs(log_moment(0.1, 1.0, lam) - want) < 1e-6
    eps, lam = moments_accountant(0.1, 1.0, 10, 1e-5, max_order=8)
    assert lam == 4
    assert abs(eps - 4.1770) < 1e-4


def test_abadi_example():
    # q = 0.01, sigma = 4, delta = 1e-5, 10000 steps: Abadi et al. report about 1.26.
    eps, lam = moments_accountant(0.01, 4.0, 10000, 1e-5)
    assert lam == 19
    assert abs(eps - 1.2586) < 1e-3


def test_no_sampling_is_gaussian_rdp():
    # q = 1 is the plain Gaussian mechanism: alpha(lam) = lam (lam + 1) / (2 sigma^2).
    for lam in range(1, 20):
        assert log_moment(1.0, 2.0, lam) == pytest.approx(lam * (lam + 1) / 8, rel=1e-12)


def test_empty_sample_costs_nothing():
    for lam in range(1, 10):
        assert log_moment(0.0, 1.0, lam) == 0.0
    eps, lam = moments_accountant(0.0, 1.0, 100, 1e-5, max_order=16)
    assert lam == 16
    assert eps == pytest.approx(math.log(1e5) / 16)


def test_second_moment_closed_form():
    # A_2 = 1 + q^2 (e^(1/sigma^2) - 1), exactly, when exp(1/(2 sigma^2)) = 2.
    q = Fraction(3, 10)
    a2 = 1 + q * q * (Fraction(4) - 1)
    assert a2 == exact_moment(q, Fraction(2), 2)
    assert log_moment(0.3, sigma_for(2), 1) == pytest.approx(log_fraction(a2), rel=1e-12)


def test_small_sigma_does_not_overflow():
    value = log_moment(0.5, 0.3, 32)
    assert math.isfinite(value)
    # The sum is at least its last term, q^33 exp((33^2 - 33) / (2 sigma^2)).
    assert value >= 33 * math.log(0.5) + (33 * 33 - 33) / (2 * 0.09) - 1e-6


def test_bad_input():
    for args in [(-0.1, 1.0, 1), (1.1, 1.0, 1), (0.5, 0.0, 1), (0.5, 1.0, 0)]:
        with pytest.raises(ValueError):
            log_moment(*args)
    with pytest.raises(ValueError):
        moments_accountant(0.1, 1.0, 0, 1e-5)
    with pytest.raises(ValueError):
        moments_accountant(0.1, 1.0, 10, 1.0)


def test_monotone():
    base, _ = moments_accountant(0.02, 1.5, 200, 1e-6)
    more_steps, _ = moments_accountant(0.02, 1.5, 400, 1e-6)
    more_noise, _ = moments_accountant(0.02, 3.0, 200, 1e-6)
    larger_delta, _ = moments_accountant(0.02, 1.5, 200, 1e-3)
    larger_rate, _ = moments_accountant(0.05, 1.5, 200, 1e-6)
    assert more_steps > base
    assert more_noise < base
    assert larger_delta < base
    assert larger_rate > base


def test_delta_for_epsilon_inverts():
    eps, _ = moments_accountant(0.01, 1.1, 1000, 1e-5)
    assert delta_for_epsilon(0.01, 1.1, 1000, eps) <= 1e-5 * (1 + 1e-9)
    assert delta_for_epsilon(0.01, 1.1, 1000, eps * 0.9) > 1e-5
    assert delta_for_epsilon(0.5, 0.5, 100, 0.0) == 1.0


def test_against_numerical_integration():
    rng = random.Random(20160)
    for _ in range(30):
        q = rng.uniform(0.001, 1.0)
        sigma = rng.uniform(0.8, 4.0)
        lam = rng.randint(1, 6)
        e1, e2 = integral_moments(q, sigma, lam)
        assert math.log(e2) == pytest.approx(log_moment(q, sigma, lam), abs=1e-6)
        # The add direction dominates the remove direction (Mironov, Talwar and Zhang).
        assert e1 <= e2 * (1 + 1e-9)


def test_random_against_exact_fractions():
    rng = random.Random(1908)
    for _ in range(500):
        q = Fraction(rng.randint(0, 64), 64)
        b = Fraction(rng.randint(66, 256), 64)
        sigma = sigma_for(b)
        max_order = rng.randint(1, 8)
        steps = rng.randint(1, 50)
        delta = Fraction(1, rng.randint(2, 10**6))
        logs = [log_fraction(exact_moment(q, b, lam + 1)) for lam in range(1, max_order + 1)]
        lam = rng.randint(1, max_order)
        assert log_moment(float(q), sigma, lam) == pytest.approx(logs[lam - 1], rel=1e-9, abs=1e-12)
        want = min(
            (steps * logs[i] - log_fraction(delta)) / (i + 1) for i in range(max_order)
        )
        got, _ = moments_accountant(float(q), sigma, steps, float(delta), max_order)
        assert got == pytest.approx(want, rel=1e-9)

History

Abadi, Chu, Goodfellow, McMahan, Mironov, Talwar and Zhang introduced the moments accountant in 2016 to train neural networks with differential privacy. They bounded the log moments for small qq and computed them by numerical integration, and their example of ε≈1.26\varepsilon \approx 1.26 against 9.349.34 for strong composition showed how much the method saves. Mironov's Renyi differential privacy (2017) gave the general framework, in which the log moment of order λ\lambda is λDλ+1\lambda D_{\lambda + 1}. Mironov, Talwar and Zhang (2019) derived the exact binomial sum for integer orders, a series for fractional orders, and the proof that one order dominates the other. RDP accountants of this form are in the main open source DP-SGD libraries.

References

  1. Martin Abadi, Andy Chu, Ian Goodfellow, H. Brendan McMahan, Ilya Mironov, Kunal Talwar and Li Zhang, Deep learning with differential privacy, ACM CCS 2016, pages 308 to 318, Section 3.1 (the differentially private SGD algorithm and its privacy example), Section 3.2 (the moments accountant, Theorem 1, the log moment alpha(lambda) and Theorem 2 on composability and the tail bound)
  2. Ilya Mironov, Kunal Talwar and Li Zhang, Renyi differential privacy of the sampled Gaussian mechanism, arXiv 1908.10530, 2019, Definition 3 (sampled Gaussian mechanism with add/remove neighbors), Section 3.1 (the expression A_alpha for integer alpha and the proof that it dominates B_alpha), Theorem 4 (reduction to one dimension) and Section 3.3 (numerically stable computation)
  3. Ilya Mironov, Renyi differential privacy, IEEE 30th Computer Security Foundations Symposium (CSF 2017), pages 263 to 275, Proposition 1 (composition) and Proposition 3 (conversion to (epsilon, delta)-DP)

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