Algorithm Search⌘K

Algorithmresearch

Numerical privacy loss distribution accounting

Also called PRV accountant, privacy loss distribution accountant, PLD accountant, FFT accountant.

Composes mechanisms by convolving discretized privacy loss distributions with the FFT, which gives near-exact epsilon for given delta.

Time
O(k n log(k n)) worst
Space
O(k n) extra
Where
k = the number of composed steps; n = the number of grid points of one privacy loss distribution
Properties
deterministicnot randomized
Origin
Sebastian Meiser, Esfandiar Mohammadi, Antti Koskela, Joonas Jalko, Antti Honkela, Sivakanth Gopi, Yin Tat Lee, Lukas Wutschitz, 2018

Numerical privacy accounting computes the privacy guarantee of many composed mechanisms almost exactly. The tight δ\delta of a mechanism at a given ε\varepsilon is a function of the distribution of its privacy loss random variable, the PLD. When mechanisms with independent noise are composed, their privacy losses add, so the PLD of the composition is the convolution of their PLDs. The accountant rounds each PLD to a grid of step hh, convolves the grids with the FFT, and reads off δ(ε)\delta(\varepsilon). If every loss is rounded up, the result is an upper bound on the true δ\delta; if every loss is rounded down, it is a lower bound. A finer grid closes the gap. For ten Gaussian steps that together are 11-GDP, a grid of step h=0.002h = 0.002 puts the true δ(1)=0.126937\delta(1) = 0.126937 between 0.1251290.125129 and 0.1287610.128761. The method is due to Meiser and Mohammadi (2018), Koskela, Jalko and Honkela (2020), and Gopi, Lee and Wutschitz (2021), who call their version the PRV accountant.

In plain words

Each private step leaks a random amount about a person. Some outcomes leak a lot and most leak little. The full pattern of the leak is a list: how likely each size of leak is. When we run many steps, the leaks add up, and the list for the total can be computed from the lists of the steps.

The accountant writes each list on a fine ruler, and moves each entry to the next mark up, so that it never claims less leak than there is. It then combines the lists with a fast method for adding up all the ways the steps can combine. From the final list it reads the usual privacy numbers. A second run that moves each entry down gives a number that is too small. The true answer is between the two.

The problem

A PLD on a grid of step h>0h > 0 is a list of masses ω0,…,ωn−1≥0\omega_0, \ldots, \omega_{n-1} \ge 0 at the losses ℓj=(l+j)h\ell_j = (l + j)h for an integer offset ll, and a mass ω∞≥0\omega_\infty \ge 0 at +∞+\infty. For a pair of output distributions (P,Q)(P, Q) of a mechanism on two neighbors, the exact PLD is the law of L=ln⁡(P(o)/Q(o))L = \ln(P(o)/Q(o)) for o∼Po \sim P, and

δ(ε)=sup⁡S(P(S)−eεQ(S))=E[(1−eε−L)+],\delta(\varepsilon) = \sup_S\left(P(S) - e^{\varepsilon}Q(S)\right) = E\left[\left(1 - e^{\varepsilon - L}\right)_+\right],

where the term is 1 when L=+∞L = +\infty. Input: a grid PLD ω\omega, a number of steps k≥1k \ge 1, and ε≥0\varepsilon \ge 0. Output: δk(ε)\delta_k(\varepsilon) for the sum of kk independent copies of the loss. For the inverse problem, a target δ\delta is given and the output is the least ε\varepsilon with δk(ε)≤δ\delta_k(\varepsilon) \le \delta, which bisection finds because δk\delta_k does not increase with ε\varepsilon.

Two discretizations of a continuous PLD with distribution function FF:

  • pessimistic: the mass of each cell ((i−1)h,ih]((i-1)h, ih] goes to ihih; the mass below the grid goes to its lowest point, and the mass above it goes to +∞+\infty;
  • optimistic: the mass of each cell ((i−1)h,ih]((i-1)h, ih] goes to (i−1)h(i-1)h, and the mass outside the grid is dropped.

The algorithm

  1. NUMERICAL-ACCOUNTANT(omega, k, epsilon)
  2. 1N <- the least power of 2 with N >= k(n - 1) + 1
  3. 2W <- FFT(omega_0, ..., omega_{n-1}, 0, ..., 0) ▷ zero padded to length N
  4. 3W_s <- (W_s)^k for s = 0..N-1
  5. 4omega' <- the first k(n - 1) + 1 entries of INVERSE-FFT(W)
  6. 5omega'_inf <- 1 - (1 - omega_inf)^k
  7. 6delta <- omega'_inf + sum over j with loss (kl + j)h > epsilon of omega'_j (1 - e^(epsilon - (kl + j)h))
  8. 7return delta

Line L1 picks a transform length that holds the whole kk-fold convolution, which has k(n−1)+1k(n-1)+1 entries, so that the cyclic convolution of the FFT does not wrap around. Line L2 takes the discrete Fourier transform of the zero-padded masses. By the convolution theorem, the transform of a kk-fold convolution is the kk-th power of the transform, so line L3 raises each entry to the power kk and line L4 transforms back. The offset of the result is klkl, because the losses add. Line L5 gives the mass at +∞+\infty: the sum is infinite when at least one step is infinite. Line L6 evaluates the formula for δ\delta on the composed grid, and line L7 returns it.

To compose different mechanisms on the same grid, multiply their transforms at line L3 instead of taking a power. To find ε\varepsilon for a target δ\delta, compose once and run bisection on ε\varepsilon with line L6 alone.

The accountant does only arithmetic on public parameters; it reads no data and draws no noise. The mechanisms that it accounts for must draw their 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 randomized response with ε0=1\varepsilon_0 = 1 on the grid h=1h = 1: the loss is +1+1 with probability p=e/(1+e)=0.731059p = e/(1+e) = 0.731059 and −1-1 otherwise, so l=−1l = -1, n=3n = 3 and ω=(0.268941,0,0.731059)\omega = (0.268941, 0, 0.731059). Compose k=3k = 3 steps.

step state
L1 k(n−1)+1=7k(n-1)+1 = 7, so N=8N = 8
L2 to L4 ω′=(0.019452,0,0.158631,0,0.431205,0,0.390712)\omega' = (0.019452, 0, 0.158631, 0, 0.431205, 0, 0.390712) at losses −3,…,3-3, \ldots, 3; offset kl=−3kl = -3
L5 ω∞′=0\omega'_\infty = 0
L6, ε=0\varepsilon = 0 0.431205(1−e−1)+0.390712(1−e−3)=0.6438330.431205(1 - e^{-1}) + 0.390712(1 - e^{-3}) = 0.643833
L6, ε=1\varepsilon = 1 0.390712(1−e−2)=0.3378350.390712(1 - e^{-2}) = 0.337835
L6, ε=2\varepsilon = 2 0.390712(1−e−1)=0.2469770.390712(1 - e^{-1}) = 0.246977
L6, ε=3\varepsilon = 3 00

The composed masses are the binomial law of the number of +1+1 losses, as they must be. Randomized response is the worst case among ε0\varepsilon_0-DP mechanisms, so these numbers are also the tight values of the optimal composition theorem for three 11-DP steps.

A second example uses a continuous PLD. Ten Gaussian steps, each with μi=1/10\mu_i = 1/\sqrt{10}, compose to 11-GDP, whose exact δ(1)\delta(1) is Φ(−1/2)−e Φ(−3/2)=0.126937\Phi(-1/2) - e\,\Phi(-3/2) = 0.126937. The pessimistic and optimistic grids give:

grid step hh grid points nn optimistic δ(1)\delta(1) pessimistic δ(1)\delta(1)
0.01 635 0.118074 0.136234
0.005 1267 0.122451 0.131531
0.002 3165 0.125129 0.128761

The gap shrinks in proportion to hh. On the 4-fold composition of μ=0.5\mu = 0.5 with h=0.01h = 0.01, bisection gives ε=4.397\varepsilon = 4.397 at δ=10−5\delta = 10^{-5} from the pessimistic grid and 4.3574.357 from the optimistic grid; the exact value is 4.3774.377.

Correctness

Theorem. Let (P,Q)(P, Q) be a pair of distributions with PLD LL, and let δk\delta_k be the δ\delta curve of (P⊗k,Q⊗k)(P^{\otimes k}, Q^{\otimes k}). In the real RAM, NUMERICAL-ACCOUNTANT on a grid PLD ω\omega returns E[(1−eε−S)+]E[(1 - e^{\varepsilon - S})_+] for SS the sum of kk independent draws from ω\omega. If ω\omega is the pessimistic discretization of LL, the result is at least δk(ε)\delta_k(\varepsilon); if ω\omega is the optimistic one, it is at most δk(ε)\delta_k(\varepsilon).

The proof in proofs/correctness.md has four steps. First, δ(ε)=E[(1−eε−L)+]\delta(\varepsilon) = E[(1 - e^{\varepsilon - L})_+], the hockey-stick divergence written as an expectation under PP. Second, the PLD of a product pair is the law of the sum of independent PLDs, so δk\delta_k comes from the kk-fold convolution. Third, lines L1 to L5 compute that convolution exactly, by the convolution theorem and because NN is large enough that the cyclic convolution equals the linear one. Fourth, the function s↦(1−eε−s)+s \mapsto (1 - e^{\varepsilon - s})_+ does not decrease, so rounding every loss up, or moving mass to +∞+\infty, can only increase the result, and rounding down, or dropping mass, can only decrease it. When (P,Q)(P, Q) is a dominating pair for each step of an adaptive composition, as for the Gaussian mechanism, the same bounds hold for the adaptive composition.

Proof: The numerical accountant computes the composed delta, and the two grids bracket itfull

We work in the real RAM, where arithmetic on reals and exe^x are exact. Write gε(s)=(1−eε−s)+g_\varepsilon(s) = (1 - e^{\varepsilon - s})_+ for s∈Rs \in \mathbb R and gε(+∞)=1g_\varepsilon(+\infty) = 1. For each ε\varepsilon, gεg_\varepsilon takes values in [0,1][0, 1] and does not decrease on R∪{+∞}\mathbb R \cup \{+\infty\}.

Let PP and QQ be distributions on a countable set OO (the argument for densities is the same with integrals in place of sums). The privacy loss of oo with P(o)>0P(o) > 0 is L(o)=ln⁡(P(o)/Q(o))L(o) = \ln(P(o)/Q(o)), which is +∞+\infty when Q(o)=0Q(o) = 0. The PLD of (P,Q)(P, Q) is the law of L(o)L(o) for o∼Po \sim P, a probability measure on R∪{+∞}\mathbb R \cup \{+\infty\}. For ε≥0\varepsilon \ge 0 let δP,Q(ε)=sup⁡S⊆O(P(S)−eεQ(S))\delta_{P,Q}(\varepsilon) = \sup_{S \subseteq O}(P(S) - e^{\varepsilon}Q(S)).

Lemma 1 (delta as an expectation). δP,Q(ε)=Eo∼P[gε(L(o))]\delta_{P,Q}(\varepsilon) = E_{o \sim P}[g_\varepsilon(L(o))].

Proof. For each SS, P(S)−eεQ(S)=∑o∈S(P(o)−eεQ(o))P(S) - e^{\varepsilon}Q(S) = \sum_{o \in S}(P(o) - e^{\varepsilon}Q(o)), and this is largest for S∗={o:P(o)>eεQ(o)}S^* = \{o : P(o) > e^{\varepsilon}Q(o)\}, where it equals ∑o(P(o)−eεQ(o))+\sum_o (P(o) - e^{\varepsilon}Q(o))_+. A point with P(o)=0P(o) = 0 adds nothing. For P(o)>0P(o) > 0, (P(o)−eεQ(o))+=P(o)(1−eεQ(o)/P(o))+=P(o) gε(L(o))(P(o) - e^{\varepsilon}Q(o))_+ = P(o)(1 - e^{\varepsilon}Q(o)/P(o))_+ = P(o)\,g_\varepsilon(L(o)), also when Q(o)=0Q(o) = 0, where both sides are P(o)P(o). Summing gives the claim. □\square

Lemma 2 (composition adds losses). Let (Pi,Qi)(P_i, Q_i) for i=1,…,ki = 1, \ldots, k be pairs with PLDs λ1,…,λk\lambda_1, \ldots, \lambda_k. The PLD of (P1×⋯×Pk,Q1×⋯×Qk)(P_1 \times \cdots \times P_k, Q_1 \times \cdots \times Q_k) is the law of L1+⋯+LkL_1 + \cdots + L_k with independent Li∼λiL_i \sim \lambda_i, where a sum with an infinite term is +∞+\infty.

Proof. For o=(o1,…,ok)o = (o_1, \ldots, o_k) with ∏iPi(oi)>0\prod_i P_i(o_i) > 0,

ln⁡∏iPi(oi)∏iQi(oi)=∑iln⁡Pi(oi)Qi(oi),\ln\frac{\prod_i P_i(o_i)}{\prod_i Q_i(o_i)} = \sum_i \ln\frac{P_i(o_i)}{Q_i(o_i)},

and both sides are +∞+\infty exactly when some Qi(oi)=0Q_i(o_i) = 0. Under the product law o1,…,oko_1, \ldots, o_k are independent with oi∼Pio_i \sim P_i, so the terms are independent with laws λi\lambda_i. □\square

So for kk copies of one pair with PLD λ\lambda, Lemmas 1 and 2 give δk(ε)=E[gε(L1+⋯+Lk)]\delta_k(\varepsilon) = E[g_\varepsilon(L_1 + \cdots + L_k)] with LiL_i independent draws from λ\lambda.

Lemma 3 (lines L1 to L5 compute the k-fold convolution). Let ω\omega be a grid PLD with finite masses ω0,…,ωn−1\omega_0, \ldots, \omega_{n-1} at (l+j)h(l + j)h and mass ω∞\omega_\infty at +∞+\infty, and let SS be the sum of kk independent draws from ω\omega. Then lines L1 to L5 return the law of SS: mass ωj′\omega'_j at (kl+j)h(kl + j)h for 0≤j≤k(n−1)0 \le j \le k(n-1), and ω∞′\omega'_\infty at +∞+\infty.

Proof. The finite part. Let c=ω∗kc = \omega^{*k} be the kk-fold linear convolution of the vector (ω0,…,ωn−1)(\omega_0, \ldots, \omega_{n-1}). Its entry cjc_j is the sum of ωj1⋯ωjk\omega_{j_1}\cdots\omega_{j_k} over all tuples with j1+⋯+jk=jj_1 + \cdots + j_k = j, which is the probability that all kk draws are finite and S=(kl+j)hS = (kl + j)h, because ∑i(l+ji)h=(kl+j)h\sum_i (l + j_i)h = (kl + j)h. The entries with j>k(n−1)j > k(n-1) are zero. Let aa be ω\omega padded with zeros to length NN, and let ⊛\circledast be cyclic convolution modulo NN. By the convolution theorem for the discrete Fourier transform, the transform of a⊛ka^{\circledast k} is the pointwise kk-th power of the transform of aa, so lines L2 to L4 return a⊛ka^{\circledast k}. An entry of a⊛ka^{\circledast k} at index rr is the sum of cjc_j over j≡r(modN)j \equiv r \pmod N. Every nonzero cjc_j has 0≤j≤k(n−1)<N0 \le j \le k(n-1) < N by line L1, so each residue class holds at most one such jj, and a⊛ka^{\circledast k} equals cc padded with zeros. Line L4 keeps the first k(n−1)+1k(n-1)+1 entries, which are cc. The offset is klkl.

The infinite part. S=+∞S = +\infty exactly when at least one draw is +∞+\infty, which has probability 1−(1−ω∞)k1 - (1 - \omega_\infty)^k by independence. This is line L5. □\square

Line L6 computes ω∞′+∑jωj′ gε((kl+j)h)\omega'_\infty + \sum_j \omega'_j\,g_\varepsilon((kl + j)h), where the terms with (kl+j)h≤ε(kl + j)h \le \varepsilon are zero. By Lemma 3 this is E[gε(S)]E[g_\varepsilon(S)], and line L7 returns it.

Lemma 4 (monotone coupling). Let L1,…,LkL_1, \ldots, L_k and L1′,…,Lk′L'_1, \ldots, L'_k be random variables on R∪{+∞}\mathbb R \cup \{+\infty\}, each family independent, with a coupling such that Li≤Li′L_i \le L'_i for each ii. Then E[gε(∑iLi)]≤E[gε(∑iLi′)]E[g_\varepsilon(\sum_i L_i)] \le E[g_\varepsilon(\sum_i L'_i)].

Proof. Under the coupling, ∑iLi≤∑iLi′\sum_i L_i \le \sum_i L'_i pointwise, with the rule that a sum with an infinite term is +∞+\infty. Since gεg_\varepsilon does not decrease, the inequality holds pointwise, and so for expectations. To couple kk pairs with independence across ii, couple each pair (Li,Li′)(L_i, L'_i) on its own and take the product of the kk couplings. □\square

Lemma 5 (dropping mass). Let ν\nu be a measure on R∪{+∞}\mathbb R \cup \{+\infty\} with total mass at most 1, and let ν≤λ\nu \le \lambda setwise, where λ\lambda is a probability measure. Define Eν(k)=∫gε(s1+⋯+sk) dν(s1)⋯dν(sk)E_\nu^{(k)} = \int g_\varepsilon(s_1 + \cdots + s_k)\,d\nu(s_1)\cdots d\nu(s_k). Then Eν(k)≤Eλ(k)E_\nu^{(k)} \le E_\lambda^{(k)}.

Proof. The integrand is non-negative, and ν⊗k≤λ⊗k\nu^{\otimes k} \le \lambda^{\otimes k} setwise, because λ−ν\lambda - \nu is a non-negative measure and the product of the two expands into ν⊗k\nu^{\otimes k} plus non-negative cross terms. □\square

Lines L1 to L6 apply unchanged to a sub-probability grid: Lemma 3 holds with "law" replaced by the measure ν∗k\nu^{*k}, since its proof only uses the multinomial expansion. With ω∞=0\omega_\infty = 0, line L5 gives 0.

Theorem. Let λ\lambda be the PLD of (P,Q)(P, Q) and δk\delta_k the δ\delta curve of (P⊗k,Q⊗k)(P^{\otimes k}, Q^{\otimes k}). Let ω↑\omega^\uparrow and ω↓\omega^\downarrow be the pessimistic and optimistic discretizations of λ\lambda on a grid of step hh with cells indexed by ilo≤i≤ihii_{\mathrm{lo}} \le i \le i_{\mathrm{hi}}. Then for every ε≥0\varepsilon \ge 0,

NUMERICAL-ACCOUNTANT(ω↓,k,ε)≤δk(ε)≤NUMERICAL-ACCOUNTANT(ω↑,k,ε).\text{NUMERICAL-ACCOUNTANT}(\omega^\downarrow, k, \varepsilon) \le \delta_k(\varepsilon) \le \text{NUMERICAL-ACCOUNTANT}(\omega^\uparrow, k, \varepsilon).

Proof. By Lemmas 1 and 2, δk(ε)=E[gε(L1+⋯+Lk)]\delta_k(\varepsilon) = E[g_\varepsilon(L_1 + \cdots + L_k)] with LiL_i independent draws from λ\lambda. By Lemma 3 and line L6, the accountant on a grid returns the same expression with draws from the grid PLD.

Upper bound. Define the map uu on R∪{+∞}\mathbb R \cup \{+\infty\} by u(s)=ilohu(s) = i_{\mathrm{lo}}h for s≤(ilo−1)hs \le (i_{\mathrm{lo}} - 1)h, u(s)=ihu(s) = ih for s∈((i−1)h,ih]s \in ((i-1)h, ih] with ilo≤i≤ihii_{\mathrm{lo}} \le i \le i_{\mathrm{hi}}, and u(s)=+∞u(s) = +\infty for s>ihihs > i_{\mathrm{hi}}h, including s=+∞s = +\infty. Then u(s)≥su(s) \ge s for every ss, and u(L)u(L) for L∼λL \sim \lambda has law ω↑\omega^\uparrow by its definition. Couple Li′=u(Li)L'_i = u(L_i). Lemma 4 gives δk(ε)≤E[gε(∑iu(Li))]\delta_k(\varepsilon) \le E[g_\varepsilon(\sum_i u(L_i))], which is the accountant on ω↑\omega^\uparrow.

Lower bound. Let A=((ilo−1)h,ihih]A = ((i_{\mathrm{lo}} - 1)h, i_{\mathrm{hi}}h] and let ν\nu be λ\lambda restricted to AA, so ν≤λ\nu \le \lambda. By Lemma 5, Eν(k)≤Eλ(k)=δk(ε)E_\nu^{(k)} \le E_\lambda^{(k)} = \delta_k(\varepsilon). Define d(s)=(i−1)hd(s) = (i-1)h for s∈((i−1)h,ih]s \in ((i-1)h, ih], so d(s)≤sd(s) \le s on AA, and the image of ν\nu under dd is ω↓\omega^\downarrow. The coupling argument of Lemma 4 applies to the finite measure ν\nu after normalizing it, with the same factor ν(A)k\nu(A)^k on both sides, and gives E[gε(∑id(Li))]≤Eν(k)E[g_\varepsilon(\sum_i d(L_i))] \le E_\nu^{(k)} under ν\nu. The left side is the accountant on ω↓\omega^\downarrow. If ν(A)=0\nu(A) = 0, the accountant returns 0 and the bound is trivial.

Both bounds hold for every ε≥0\varepsilon \ge 0. Since the curves do not increase in ε\varepsilon, bisection on the pessimistic curve returns an ε\varepsilon whose true δk\delta_k is at most the target.

The theorem is about independent copies of one pair. For the Gaussian mechanism with μ=Δ/σ\mu = \Delta/\sigma, the pair (N(μ,1),N(0,1))(N(\mu, 1), N(0, 1)) is the worst case over neighbors, and the composition theorem of Gaussian differential privacy (Dong, Roth and Su) says that kk adaptive μ\mu-GDP steps are kμ\sqrt k\mu-GDP, which is the curve of kk independent copies of that pair. So for the Gaussian mechanism the same bracket holds for adaptive composition. ■\blacksquare

Complexity

The composed grid has k(n−1)+1k(n-1)+1 points, so N<2knN < 2kn. In the real RAM, each FFT costs O(Nlog⁡N)O(N \log N), the powers at line L3 cost O(Nlog⁡k)O(N \log k), and line L6 costs O(N)O(N). The total is O(knlog⁡(kn))O(kn\log(kn)) time and O(kn)O(kn) extra space. Each bisection step for ε\varepsilon costs O(kn)O(kn).

The grid step sets the accuracy. Rounding moves each loss by less than hh, so the sum of kk losses moves by less than khkh, and the two bounds bracket δ\delta in an ε\varepsilon window of width khkh. Gopi, Lee and Wutschitz show that a much coarser grid suffices, because the rounding errors of independent steps partly cancel when the rounding is done in expectation, and they give a running time of O~(k)\tilde O(\sqrt k) for a fixed target accuracy.

Properties

  • Two-sided. The pessimistic and optimistic grids give a certified bracket on δ\delta, so the user can see how far the reported value is from the exact one.
  • Tight in the limit. As h→0h \to 0 and the grid range grows, both bounds tend to the exact δk(ε)\delta_k(\varepsilon), unlike the bounds of the moments accountant or the advanced composition theorem, which stay above it.
  • Any mechanism with a known PLD. The method needs only the PLD of each step, which is known for the Laplace, Gaussian and randomized response mechanisms and can be computed numerically for the subsampled Gaussian.
  • Pure arithmetic. It reads no data and has no randomness.

Variants and improvements

  • Privacy buckets. Meiser and Mohammadi put the loss into buckets with geometric boundaries and convolve the buckets directly, with upper and lower bounds.
  • FFT accountant. Koskela, Jalko and Honkela truncate the losses to an interval [−L,L][-L, L], let the FFT wrap around, and bound the error of the truncation and of the wrap. Their version handles the subsampled Gaussian of DP-SGD.
  • PRV accountant. Gopi, Lee and Wutschitz round each loss so that its mean is kept, and truncate the domain using a tail bound on the composed loss. This gives a grid that grows like k\sqrt k rather than kk, with explicit error bounds on ε\varepsilon.
  • Characteristic functions. Later work composes the Fourier transforms of the continuous PLDs directly and inverts only once at the end.
  • Heterogeneous steps. Steps with different noise multiply their own transforms at line L3; the grid step must be the same for all.

When to use it

Use numerical accounting when the exact ε\varepsilon matters, as in a public release or a long training run where the last ten or twenty percent of the budget decides the noise level. It applies whenever the PLD of each step is known. Use the moments accountant for a fast bound during development, and the closed form of Gaussian differential privacy when every step is a Gaussian mechanism without subsampling.

Pitfalls

  • Wrap-around at line L1. If NN is smaller than the length of the composed grid, the cyclic convolution of the FFT adds the top of the distribution to the bottom, and δ\delta comes out too small. Choose NN as in line L1, or bound the wrapped mass.
  • Wrong rounding direction. The upper bound needs every loss rounded up and the top tail moved to +∞+\infty, not dropped. Rounding to the nearest grid point at line L2 gives neither bound.
  • Float error at lines L2 to L4. The FFT in floats has an absolute error near the machine precision times the total mass, and some masses come out slightly negative. A δ\delta of 10−1010^{-10} is then below the noise floor; the bracket from the two grids does not account for this error.
  • Forgetting the mass at infinity at line L5. A mechanism with ω∞>0\omega_\infty > 0, such as one with a nonzero δ\delta of its own, adds at least 1−(1−ω∞)k1 - (1-\omega_\infty)^k to the final δ\delta.
  • A pair that does not dominate. The result is a guarantee only if the PLD comes from a pair that is the worst case over all neighbors, in both orders. For subsampled mechanisms the two orders give different PLDs, and both must be checked.
  • Floating-point noise in the mechanism. The accounting assumes exact noise. Noise from a float sampler or a non-cryptographic generator is not covered by the bound.

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.

numerical_privacy_accounting.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/numerical-privacy-accounting/. The authors are listed in prov/XTW2ZE.jsonl.
"""Numerical privacy loss distribution (PLD) accounting with the FFT.

A PLD on a grid of step h is a list of masses: mass[j] sits at the loss
(lo + j) * h, and inf_mass sits at +infinity. Composing k mechanisms with
independent noise convolves their PLDs, which the FFT does in
O(N log N) for N about k times the grid size. The tight delta at epsilon is

    delta(epsilon) = inf_mass + sum_j mass[j] * max(0, 1 - e^(epsilon - loss_j)),

and epsilon for a target delta comes from bisection. Rounding each loss up
to the grid (pessimistic) gives an upper bound on delta; rounding down
(optimistic) gives a lower bound, so the two bracket the exact value.

The code is accounting only, in floats, in the real RAM model. The mechanisms
that it accounts for need a cryptographic source of randomness and exact
sampling of their noise in a deployment (Mironov 2012; Canonne, Kamath and
Steinke 2020).
"""

from __future__ import annotations

import cmath
import math
from dataclasses import dataclass
from statistics import NormalDist
from typing import List, Sequence, Tuple


@dataclass(frozen=True)
class Pld:
    """A privacy loss distribution on the grid (lo + j) * step."""

    lo: int
    masses: Tuple[float, ...]
    step: float
    inf_mass: float = 0.0

    def loss(self, j: int) -> float:
        return (self.lo + j) * self.step


def fft(a: Sequence[complex], invert: bool = False) -> List[complex]:
    """Iterative radix-2 FFT. Precondition: len(a) is a power of 2.

    With invert=True it computes the inverse transform, including the 1/N.
    Cost: O(N log N) arithmetic operations, O(N) space.
    """
    n = len(a)
    if n & (n - 1):
        raise ValueError("the length must be a power of 2")
    out = list(a)
    j = 0
    for i in range(1, n):  # bit-reversal permutation
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            out[i], out[j] = out[j], out[i]
    length = 2
    sign = 1.0 if invert else -1.0
    while length <= n:
        w_len = cmath.exp(sign * 2j * math.pi / length)
        half = length // 2
        for start in range(0, n, length):
            w = 1.0 + 0j
            for k in range(half):
                u = out[start + k]
                v = out[start + k + half] * w
                out[start + k] = u + v
                out[start + k + half] = u - v
                w *= w_len
        length <<= 1
    if invert:
        out = [x / n for x in out]
    return out


def compose(pld: Pld, k: int) -> Pld:
    """The PLD of k independent copies of the mechanism with PLD pld.

    Precondition: k >= 1. Cost: O(N log N) with N < 2 k n for n grid points.
    """
    if k < 1:
        raise ValueError("k must be at least 1")
    n = len(pld.masses)
    size = 1
    while size < k * (n - 1) + 1:  # @line L1
        size <<= 1
    spectrum = fft([complex(m) for m in pld.masses] + [0j] * (size - n))  # @line L2
    powered = [z**k for z in spectrum]  # @line L3
    values = fft(powered, invert=True)  # @line L4
    masses = tuple(max(0.0, z.real) for z in values[: k * (n - 1) + 1])
    inf_k = 1.0 - (1.0 - pld.inf_mass) ** k  # @line L5
    return Pld(k * pld.lo, masses, pld.step, inf_k)


def delta_for_epsilon(pld: Pld, epsilon: float) -> float:
    """The delta of the PLD at epsilon. Cost: O(n) for n grid points."""
    total = pld.inf_mass  # @line L6
    for j, m in enumerate(pld.masses):
        loss = pld.loss(j)
        if m > 0.0 and loss > epsilon:
            total += m * -math.expm1(epsilon - loss)
    return min(1.0, total)


def numerical_accountant(pld: Pld, k: int, epsilon: float) -> float:
    """delta(epsilon) for the k-fold composition of pld (lines L1 to L7).

    Precondition: k >= 1, epsilon >= 0. Cost: O(k n log(k n)) for n grid points.
    """
    composed = compose(pld, k)  # lines L1 to L5
    return delta_for_epsilon(composed, epsilon)  # @line L7


def epsilon_for_delta(pld: Pld, delta: float, tol: float = 1e-9) -> float:
    """The least epsilon >= 0 with delta_for_epsilon(pld, epsilon) <= delta, up to tol.

    It returns an epsilon with delta(epsilon) <= delta, found by bisection.
    Precondition: delta > pld.inf_mass. Cost: O(n log(L / tol)) for loss range L.
    """
    if delta <= pld.inf_mass:
        raise ValueError("delta must exceed the mass at infinity")
    lo = 0.0
    if delta_for_epsilon(pld, lo) <= delta:
        return lo
    hi = max(pld.loss(len(pld.masses) - 1), 0.0) + 1.0  # delta(hi) = inf_mass < delta
    while hi - lo > tol:
        mid = (lo + hi) / 2
        if delta_for_epsilon(pld, mid) <= delta:
            hi = mid
        else:
            lo = mid
    return hi


def gaussian_pld(mu: float, step: float, pessimistic: bool = True, width: float = 10.0) -> Pld:
    """The discretized PLD of the Gaussian mechanism with mu = sensitivity / sigma.

    The exact PLD is N(mu^2 / 2, mu^2). Each grid cell ((i-1) h, i h] goes to
    i h (pessimistic) or to (i-1) h (optimistic). Pessimistic: the mass below
    the grid goes to the lowest grid point and the mass above it goes to
    +infinity. Optimistic: both tails are dropped. So the pessimistic PLD
    gives an upper bound on delta and the optimistic PLD a lower bound.
    Precondition: mu > 0, step > 0. Cost: O(n) with n = 2 width mu / step.
    """
    if mu <= 0 or step <= 0:
        raise ValueError("mu and step must be positive")
    law = NormalDist(mu * mu / 2, mu)
    i_lo = math.floor((law.mean - width * mu) / step)
    i_hi = math.ceil((law.mean + width * mu) / step)
    cdf = [law.cdf(i * step) for i in range(i_lo - 1, i_hi + 1)]
    cells = [max(0.0, cdf[j + 1] - cdf[j]) for j in range(len(cdf) - 1)]
    if pessimistic:
        cells[0] += cdf[0]  # the mass below (i_lo - 1) h, rounded up to i_lo h
        return Pld(i_lo, tuple(cells), step, 1.0 - cdf[-1])
    return Pld(i_lo - 1, tuple(cells), step, 0.0)


def randomized_response_pld(m: int, step: float) -> Pld:
    """The PLD of randomized response with epsilon_0 = m * step, on the grid of step.

    The loss is +epsilon_0 with probability e^eps0 / (1 + e^eps0) and
    -epsilon_0 otherwise; both are grid points, so there is no rounding.
    Precondition: m >= 1, step > 0. Cost: O(m).
    """
    if m < 1 or step <= 0:
        raise ValueError("need m >= 1 and step > 0")
    p = 1.0 / (1.0 + math.exp(-m * step))
    masses = [0.0] * (2 * m + 1)
    masses[0] = 1.0 - p
    masses[-1] = p
    return Pld(-m, tuple(masses), step, 0.0)
test_numerical_privacy_accounting.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/numerical-privacy-accounting/. The authors are listed in prov/XTW2ZE.jsonl.

import cmath
import itertools
import math
import random
from fractions import Fraction
from math import comb
from statistics import NormalDist

import pytest

from numerical_privacy_accounting import (
    Pld,
    compose,
    delta_for_epsilon,
    epsilon_for_delta,
    fft,
    gaussian_pld,
    numerical_accountant,
    randomized_response_pld,
)


def gaussian_delta(epsilon, mu):
    """The exact delta of mu-GDP (the Gaussian mechanism), in closed form."""
    phi = NormalDist().cdf
    return phi(-epsilon / mu + mu / 2) - math.exp(epsilon) * phi(-epsilon / mu - mu / 2)


def brute_delta(pld, k, epsilon):
    """An independent oracle: sum over all k-tuples of grid points, no FFT."""
    finite = 1.0 - pld.inf_mass
    total = 1.0 - finite**k
    for idx in itertools.product(range(len(pld.masses)), repeat=k):
        weight = math.prod(pld.masses[j] for j in idx)
        loss = sum(pld.loss(j) for j in idx)
        if weight > 0 and loss > epsilon:
            total += weight * (1 - math.exp(epsilon - loss))
    return min(1.0, total)


def rr_delta_exact(b, k, i):
    """Exact delta of k-fold randomized response with e^eps0 = b, at epsilon = i * eps0.

    The loss is (2j - k) eps0 when j of the k answers have loss +eps0, so
    e^(epsilon - loss) = b^(i - 2j + k), a rational number.
    """
    b = Fraction(b)
    total = Fraction(0)
    for j in range(k + 1):
        ratio = b ** (i - 2 * j + k)
        if ratio < 1:
            total += comb(k, j) * b**j / (1 + b) ** k * (1 - ratio)
    return total


def test_worked_example():
    # Randomized response with eps0 = 1, k = 2 steps, epsilon = 0.
    pld = randomized_response_pld(1, 1.0)
    p = math.e / (1 + math.e)
    composed = compose(pld, 2)
    assert composed.lo == -2
    assert composed.masses[0] == pytest.approx((1 - p) ** 2)
    assert composed.masses[2] == pytest.approx(2 * p * (1 - p))
    assert composed.masses[4] == pytest.approx(p * p)
    want = p * p * (1 - math.exp(-2))
    assert numerical_accountant(pld, 2, 0.0) == pytest.approx(want, abs=1e-12)
    assert want == pytest.approx(0.462117, abs=1e-6)


def test_gaussian_brackets_the_exact_value():
    # 10 Gaussian steps with mu_i = 1 / sqrt(10) compose to exactly 1-GDP.
    k, mu = 10, 1 / math.sqrt(10)
    upper = numerical_accountant(gaussian_pld(mu, 2e-3, pessimistic=True), k, 1.0)
    lower = numerical_accountant(gaussian_pld(mu, 2e-3, pessimistic=False), k, 1.0)
    exact = gaussian_delta(1.0, 1.0)
    assert exact == pytest.approx(0.126937, abs=1e-6)
    assert lower <= exact <= upper
    assert upper - lower < 5e-3


def test_randomized_response_exact_fraction():
    for b_num, k in [(3, 5), (2, 8), (5, 3)]:
        eps0 = math.log(b_num)
        pld = randomized_response_pld(1, eps0)
        for i in range(0, k + 1):
            got = numerical_accountant(pld, k, i * eps0)
            assert got == pytest.approx(float(rr_delta_exact(b_num, k, i)), abs=1e-12)


def test_edges_and_bad_input():
    pld = randomized_response_pld(2, 0.25)
    same = compose(pld, 1)
    assert same.lo == pld.lo
    assert all(abs(a - b) < 1e-15 for a, b in zip(same.masses, pld.masses))
    # Far above the largest loss, only the mass at infinity is left.
    inf_pld = Pld(0, (0.5, 0.25), 1.0, 0.25)
    assert delta_for_epsilon(inf_pld, 100.0) == pytest.approx(0.25)
    assert compose(inf_pld, 3).inf_mass == pytest.approx(1 - 0.75**3)
    # epsilon = 0 for a point mass at loss 0: the two outputs are the same.
    assert numerical_accountant(Pld(0, (1.0,), 0.5), 4, 0.0) == 0.0
    with pytest.raises(ValueError):
        compose(pld, 0)
    with pytest.raises(ValueError):
        fft([1, 2, 3])
    with pytest.raises(ValueError):
        gaussian_pld(0.0, 0.01)
    with pytest.raises(ValueError):
        randomized_response_pld(0, 0.1)
    with pytest.raises(ValueError):
        epsilon_for_delta(inf_pld, 0.2)


def test_fft_against_naive_dft():
    rng = random.Random(11)
    for size in [1, 2, 4, 8, 32]:
        a = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(size)]
        naive = [sum(a[t] * cmath.exp(-2j * math.pi * s * t / size) for t in range(size)) for s in range(size)]
        got = fft(a)
        assert all(abs(x - y) < 1e-9 for x, y in zip(got, naive))
        back = fft(got, invert=True)
        assert all(abs(x - y) < 1e-12 for x, y in zip(back, a))


def test_monotone_in_epsilon_and_steps():
    pld = gaussian_pld(0.5, 0.02)
    composed = compose(pld, 4)
    deltas = [delta_for_epsilon(composed, e / 4) for e in range(13)]
    assert all(x >= y for x, y in zip(deltas, deltas[1:]))
    by_k = [numerical_accountant(pld, k, 1.0) for k in range(1, 6)]
    assert all(x <= y for x, y in zip(by_k, by_k[1:]))


def test_epsilon_for_delta_inverts():
    pld = compose(gaussian_pld(0.5, 0.01), 4)  # close to 1-GDP
    eps = epsilon_for_delta(pld, 1e-5)
    assert delta_for_epsilon(pld, eps) <= 1e-5
    assert delta_for_epsilon(pld, eps - 1e-6) > 1e-5
    # The exact 1-GDP value is 4.3772; the pessimistic grid stays above it.
    assert 4.3772 < eps < 4.42
    assert epsilon_for_delta(pld, 0.9) == 0.0


def test_pessimistic_dominates_single_step():
    for mu in [0.3, 1.0, 2.0]:
        up = gaussian_pld(mu, 0.01)
        down = gaussian_pld(mu, 0.01, pessimistic=False)
        for e in [0.0, 0.5, 1.0, 2.0]:
            exact = gaussian_delta(e, mu)
            assert delta_for_epsilon(down, e) <= exact + 1e-12
            assert exact <= delta_for_epsilon(up, e) + 1e-12


def test_random_against_brute_force():
    rng = random.Random(2106)
    for _ in range(500):
        n = rng.randint(1, 5)
        k = rng.randint(1, 4)
        raw = [rng.random() for _ in range(n)]
        inf_mass = rng.choice([0.0, 0.0, rng.uniform(0.0, 0.1)])
        scale = (1 - inf_mass) / sum(raw)
        pld = Pld(rng.randint(-4, 2), tuple(r * scale for r in raw), rng.choice([0.1, 0.25, 0.5]), inf_mass)
        epsilon = rng.uniform(0.0, 2.0)
        got = numerical_accountant(pld, k, epsilon)
        assert got == pytest.approx(brute_delta(pld, k, epsilon), rel=1e-9, abs=1e-12)

History

Before 2018, composition was done with closed-form bounds such as the advanced composition theorem, with Renyi accounting, or, for pure DP steps, with the exact but costly formula of the optimal composition theorem. Meiser and Mohammadi (CCS 2018) showed that the loss distribution itself can be composed numerically, with provable upper and lower bounds, and found that the bounds of the moments accountant were loose. Koskela, Jalko and Honkela (AISTATS 2020) wrote the exact δ\delta as an integral, evaluated the convolutions with the FFT, and gave error bounds; they applied it to DP-SGD. Gopi, Lee and Wutschitz (NeurIPS 2021) introduced privacy random variables, the PRV accountant, and error bounds that need far fewer grid points, which made the method much faster for long compositions. PLD and PRV accountants are now in the main open source differential privacy libraries.

References

  1. Sebastian Meiser and Esfandiar Mohammadi, Tight on budget? Tight bounds for r-fold approximate differential privacy, ACM CCS 2018, doi 10.1145/3243734.3243765, privacy buckets: provable upper and lower bounds on the delta of r-fold composition
  2. Antti Koskela, Joonas Jalko and Antti Honkela, Computing tight differential privacy guarantees using FFT, AISTATS 2020, the integral formula for exact (epsilon, delta), its discretization, the FFT evaluation of the convolutions, and the error bounds
  3. Sivakanth Gopi, Yin Tat Lee and Lukas Wutschitz, Numerical composition of differential privacy, NeurIPS 2021, privacy loss random variables, the PRV accountant and its error bounds, and the running time for k-fold composition

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