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
- Model
- Real RAM
- Properties
- deterministicnot randomized
- Evidence
- Proof sketchCode in 1 languages
- 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 per step, it tracks the log of the moment generating function of the privacy loss random variable at a few orders . These log moments add up exactly under composition, and a tail bound at the end turns the sum into one guarantee. For a step with sampling rate and noise multiplier , ten thousand steps cost about at , while the advanced composition theorem on the same steps gives about . The log moment of order is times the Renyi divergence of order , 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 (Poisson sampling);
- for each kept record, compute a vector and clip it to norm at most 1;
- release the sum of the clipped vectors plus .
The vectors of a step may depend on the outputs of earlier steps. Input: the rate , the noise multiplier , the number of steps , a target , and the largest order to try. Output: an such that the steps together are -DP, as small as the method allows, and the order that gives it.
For one step, let and . The log moment of order that the accountant uses is
The algorithm
MOMENTS-ACCOUNTANT(q, sigma, T, delta, m)- 1
for lambda <- 1 to m do - 2
a <- lambda + 1 - 3
t_k <- ln C(a, k) + (a - k) ln(1 - q) + k ln q + (k^2 - k)/(2 sigma^2) for k = 0..a - 4
alpha <- LOG-SUM-EXP(t_0, ..., t_a) ▷ alpha = ln A_a - 5
eps_lambda <- (T alpha + ln(1/delta)) / lambda - 6
keep the smallest eps_lambda and its lambda - 7
return the smallest eps_lambda and its lambda
Line L1 tries each integer order. Lines L2 and L3 write the terms of the binomial sum as logs; a term with or that is 0 is left out. Line L4 adds the terms with the log-sum-exp trick: subtract the largest , add the exponentials, take the log, and add the largest back. This is needed, because for small and large the term overflows a float. Line L5 applies the tail bound to the sum of the log moments of steps. Lines L6 and L7 return the best order.
The same sum gives for a fixed : . 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 , , , and , so . For , the order is and , so .
| (L2) | (L4) | (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 at . Small orders pay too much for ; large orders pay too much for , which grows fast once the top terms of the sum, with their factor , beat the small factor .
A second check, the setting of Abadi et al.: , , , and give at . The paper reports about .
Correctness
Theorem. Let be the output of MOMENTS-ACCOUNTANT. Then adaptively composed steps of the subsampled Gaussian mechanism, with Poisson rate , clipping norm 1 and noise , are -DP under add/remove neighbors.
The proof in proofs/correctness.md has four steps. First, lines L2 to L4 compute exactly in the real RAM, by the binomial theorem and the identity for . Second, for one step and each pair of neighbors, the log moment of order of the privacy loss is at most : 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 gives , and a tail bound of this form implies -DP. Each 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 ; this gives the batch . Each record has a vector with , which may depend on the earlier outputs. The step releases , where . Neighbors are add/remove: .
For distributions with positive densities and , write
Let be the density of on , and for and let
So is the sum of the page.
Lemma 1 (Gaussian moments). For every integer and , . Hence .
Proof. . For , . With ,
For the second claim write the integrand as with , expand by the binomial theorem, and apply the first claim to each term.
Lemma 2 (lines L2 to L4). For each , the value of line L4 equals .
Proof. Line L2 sets . Each term of with a non-zero coefficient is positive, and line L3 computes its log ; the terms that are 0 (the cases , and , ) are left out and do not change the sum. At least one term remains. With , line L4 returns .
Lemma 3 (one step, larger dataset first). Fix the earlier outputs. Let and be the laws of the step on and on . Then for every integer .
Proof. Let , and let be the density of . A Poisson sample of is , or with probability , independently of . So
The map on is the perspective of the convex function , so it is jointly convex. takes finitely many values, so Jensen's inequality at each point gives . Integrate over and swap the integral and the finite average:
Fix . Translate by and rotate so that with . Both densities are products of the same factor in coordinates , which integrates to 1, and of and in coordinate 1. By Lemma 1 the inner integral is . Every exponent is non-negative and grows with , so . Hence , and .
Lemma 4 (one step, smaller dataset first). With the notation of Lemma 3, for every integer .
Proof. The joint convexity step of Lemma 3, with the roles of the two arguments swapped, reduces the claim to , where and . If , then . For , the pair with shift and noise is the pair with shift 1 and noise 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 for shift 1 and every noise level. So by the monotonicity in Lemma 3. This is the one step that we cite and do not prove here.
Lemma 5 (adaptive composition). Let be the outputs of steps on a dataset with law , and on its neighbor with law . If, for each and each fixed prefix , the conditional laws satisfy , then .
Proof. The privacy loss of the whole output is , the sum of the conditional privacy losses, because the densities factor as products of the conditional densities. Then
and induction on gives .
Lemma 6 (tail bound to DP). Let with . If , then for every event .
Proof. On the set we have . So .
Theorem. The output of MOMENTS-ACCOUNTANT makes the composed steps -DP under add/remove neighbors.
Proof. Fix neighbors and either order of the pair, and fix . Let , the value of line L4 by Lemma 2. Lemmas 3 and 4 bound the conditional log moment of each step by in both orders and for every prefix, so Lemma 5 gives for the privacy loss of the outputs. With of line L5, Markov's inequality gives
By Lemma 6, the composition is -DP for this ordered pair, and so for all of them. Lines L6 and L7 return the smallest over , which is one of these valid values. The loop of line L1 runs times, and the inner work is , so the procedure stops.
Complexity
In the real RAM, order costs operations at lines L3 and L4, so the whole run costs time and extra space for the terms of one order. The cost does not depend on , because composition is one multiplication by . Abadi et al. used , so 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, is the exact log moment of the one-dimensional pair, not an approximation. The asymptotic form in the paper of Abadi et al., , holds only under conditions on , and , and has a hidden term; the finite sum has neither problem.
- Additive. The state of the accountant during training is one vector of numbers, . Steps with different or simply add their own vectors.
- Pure arithmetic. It reads no data and has no randomness.
- Monotone. grows with and , and shrinks as or grows.
Variants and improvements
- Fractional orders. Mironov, Talwar and Zhang give a series for real orders . A finer grid of orders gives a slightly smaller .
- Better conversions. The step from Renyi divergence to 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 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 .
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 matter, and the advanced composition theorem only for steps that have nothing but an guarantee.
Pitfalls
- Wrong sampling scheme at line L3. The sum 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 directly overflows for small and large . Use log-sum-exp, as in the pseudocode.
- Too few orders at line L1. If the best order is itself, the minimum may lie beyond ; raise and run again.
- Clipping not enforced. The bound assumes that each record changes the sum by at most 1 in norm. If the clip norm is , the noise must be , and 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.
# 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 and computed them by numerical integration, and their example of against 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 is . 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BBS4G5 Edit this page History Report an error Markdown