Module contents
Lesson 31 of 39Advanced 110 min

Composition, advanced mechanisms and privacy accounting

Training a network composes thousands of mechanisms, making privacy accounting essential. This lesson covers Gaussian and exponential mechanisms, advanced composition, Rényi privacy and amplification by subsampling, and builds RDP and numerical privacy-loss accountants for comparison with library implementations.

After this lesson you can

  • Calibrate the Gaussian mechanism with classical and analytic bounds, and identify when the classical bound does not apply.
  • Prove that the exponential mechanism is ε-DP and apply it to private selection.
  • State and sketch a proof of advanced composition and compare it with basic composition.
  • Compose using RDP, convert to (ε, δ), and calculate the effect of amplification by subsampling.
  • Implement an RDP accountant and a numerical privacy-loss distribution accountant, and compare them with Opacus.

Before you start

Counting all releases

Training can release a model that depends on thousands of random steps. Each step consumes part of a budget, and accounting must reflect the mechanism actually executed: adjacency, clipping, noise, batch selection and number of steps. A valid bound can be conservative; a bound for another mechanism does not guarantee the observed training.

The Gaussian mechanism adds normal noise calibrated to sensitivity L2L_2. A sufficient classical bound, for 0<ε<10<\varepsilon<1 and 0<δ<10<\delta<1, uses σ>Δ22log⁡(1.25/δ)/ε\sigma>\Delta_2\sqrt{2\log(1.25/\delta)}/\varepsilon under the standard statement. The boundary ε=1\varepsilon=1 is not covered by that strict formulation. Balle and Wang develop analytic calibration using the normal distribution without that approximation; a formula must not be substituted outside its assumptions.

For two Gaussians with displacement norm Δ2\Delta_2 and standard deviation σ\sigma, the analytic privacy curve is

δ(ε)=Φ ⁣(Δ22σ−εσΔ2)−eεΦ ⁣(−Δ22σ−εσΔ2).\delta(\varepsilon)=\Phi\!\left(\frac{\Delta_2}{2\sigma}-\frac{\varepsilon\sigma}{\Delta_2}\right)-e^\varepsilon\Phi\!\left(-\frac{\Delta_2}{2\sigma}-\frac{\varepsilon\sigma}{\Delta_2}\right).

Here Φ\Phi is the standard normal CDF. To calibrate, find the smallest σ\sigma whose value does not exceed the target δ\delta, using a numerically stable implementation. The classical bound is sufficient and usually conservative; comparing results does not turn an approximate calculation with numerical cancellation into a certificate. Sensitivity depends on adjacency and the specific operation released.

Choosing a private output

The exponential mechanism assigns each candidate rr probability proportional to exp⁡(εu(D,r)/(2Δu))\exp(\varepsilon u(D,r)/(2\Delta u)), with uniform utility sensitivity Δu\Delta u and a fixed candidate set. As ε\varepsilon increases, the distribution favors high utilities, although any random selection may choose another option.

To prove privacy, each unnormalized weight changes by at most a factor eε/2e^{\varepsilon/2} between neighboring databases, as does the sum of weights. Combining both factors bounds the probability ratio of any candidate by eεe^\varepsilon; summing over any set of candidates preserves the bound. Sensitivity must hold for all candidates and neighboring databases, not just the observed sample. Expected utility decreases when enough randomness is added, so privacy and utility must be evaluated together.

Report noisy max adds noise to each score and reveals only the winning index; releasing all noisy scores as well requires different accounting. The sparse vector technique compares adaptive queries with a noisy threshold and can limit the number of positive responses, but its variants require accounting for all outputs and their assumptions. Reusing the threshold or changing what is released without revisiting the analysis can break the guarantee; calling any query sequence “sparse vector” is not enough.

InteractiveChoosing with the exponential mechanism
Utility 0
0.4 %
Utility 1
0.7 %
Utility 2
1.2 %
Utility 3
2.0 %
Utility 4
3.3 %
Utility 5
5.4 %
Utility 6
8.8 %
Utility 7
14.6 %
Utility 8
24.0 %
Utility 9
39.6 %
1.0
Expected utility7.53
Probability of the maximum39.6 %
Ten synthetic utilities and declared sensitivity 1. The bars are calculated probabilities, not a survey of private data.

Composition and Rényi

The advanced composition of kk (ε,δ)(\varepsilon,\delta)-DP mechanisms guarantees, for δ′>0\delta'>0, parameters

εtot=2klog⁡(1/δ′) ε+kε(eε−1),δtot=kδ+δ′.\varepsilon_{\mathrm{tot}}=\sqrt{2k\log(1/\delta')}\,\varepsilon+k\varepsilon(e^\varepsilon-1),\qquad \delta_{\mathrm{tot}}=k\delta+\delta'.

This is a general bound, not necessarily tight. Basic composition gives (kε,kδ)(k\varepsilon,k\delta); comparing only ε\varepsilon without acknowledging the additional δ′\delta' would be incomplete. The proof controls the sum of privacy losses using concentration; it requires conditional guarantees at each adaptive step.

In the pure case, conditional losses are bounded and their conditional expectation has a bound in terms of ε\varepsilon. Subtracting those expectations leaves a sum of martingale differences; a concentration inequality controls the probability that it exceeds the term proportional to klog⁡(1/δ′)\sqrt{k\log(1/\delta')}. The sum of expectations supplies the remaining linear term. The approximate extension adds the cost of exceptional events kδk\delta; the full argument must address those events, not assume that losses of an (ε,δ)(\varepsilon,\delta) mechanism are always bounded.

InteractiveFour ways to compose privacy
Floating-point grid for a Gaussian mechanism with Poisson sampling and add/remove adjacency. Basic composition uses δ/2. Advanced composition reserves an extra δ/2. RDP uses standard conversion at integer orders 2 to 24.
Steps: 10, 50, 100, and 200. Vertical axis: log₁₀(1 + ε). Blue is basic, orange is advanced, green is RDP, and amber is FFT. Advanced composition can give a looser bound than basic composition. Both give bounds on the true privacy cost.
FFT rounds the privacy-loss distribution into 16,384 bins over [−30,30] and uses circular convolution in both directions. The grid values are approximations without rigorous controls for tails, aliasing, or rounding.
Basic, 100 steps104.495
Advanced, 100 steps244.239
RDP, 100 steps2.884
Approximate FFT, 100 steps2.119
Grid precalculated from the formulas described and the laboratory numerical convolution; FFT is an approximation without a certified guarantee.

Rényi differential privacy bounds the Rényi divergence of order α>1\alpha>1 between outputs on neighboring databases. For a Gaussian with sensitivity Δ2\Delta_2 and standard deviation σ\sigma, one-step RDP is bounded by αΔ22/(2σ2)\alpha\Delta_2^2/(2\sigma^2); equality is achieved for a displacement of norm Δ2\Delta_2. Per-step bounds add at fixed order, even under adaptive composition with uniform guarantees. The divergence is defined by

Dα(P∥Q)=1α−1log⁡EX∼Q[(dPdQ(X))α].D_\alpha(P\Vert Q)=\frac{1}{\alpha-1}\log\mathbb E_{X\sim Q}\left[\left(\frac{dP}{dQ}(X)\right)^\alpha\right].

The guarantee must hold for every ordered pair of neighboring databases; swapping PP and QQ does not generally leave the divergence unchanged. If a step mechanism depends on previous outputs, the moment bound must hold conditionally for every possible history. Iterated expectations multiply the moment factors, and logarithms turn that product into a sum. This gives additive composition at a fixed order.

To convert the guarantee to approximate differential privacy, one may use

ε(δ)≤min⁡α>1[εRDP(α)+log⁡(1/δ)α−1].\varepsilon(\delta)\le\min_{\alpha>1}\left[\varepsilon_{\mathrm{RDP}}(\alpha)+\frac{\log(1/\delta)}{\alpha-1}\right].

Minimizing over a finite grid still gives a valid bound, although it may be looser than the continuous minimum. Mironov develops this accounting; improved conversions and numerical accountants may produce different bounds.

InteractiveFrom the Rényi profile to (ε, δ)
Compose the RDP of Gaussian mechanisms with sensitivity 1, then add ln(1/δ)/(α−1). Blue marks Poisson sampling and orange marks no sampling.
Horizontal axis: integer α from 2 to 24. Vertical axis: log₁₀(1 + ε bound). The point marks the minimum across these orders.
0.05
1.3
5
100
Best integer order8
Subsampled ε bound2.884
ε bound without sampling70.685
Bounds calculated for sensitivity one and integer orders; the blue line uses the Poisson Gaussian mixture expression, while the orange line does not subsample.

An improved conversion used in Opacus also evaluates εRDP(α)−(log⁡δ+log⁡α)/(α−1)+log⁡((α−1)/α)\varepsilon_{\mathrm{RDP}}(\alpha)-(\log\delta+\log\alpha)/(\alpha-1)+\log((\alpha-1)/\alpha) and minimizes over available orders. The result may be lower-bounded at zero. The formula comes from a hypothesis-testing interpretation of RDP under its assumptions; see Balle and colleagues. Changing the formula and grid simultaneously prevents attributing the difference to either factor alone.

Amplification by subsampling depends on the design: including each record independently with probability qq differs from shuffling and traversing a partition by epochs. The formulas of Mironov and colleagues for the subsampled Gaussian specify the mechanism and its analysis. Do not apply a Poisson accountant to another loader based on superficial similarity.

With n=100n=100, batches of 10 and ten steps, one shuffled epoch uses each record exactly once. In contrast, with ten independent Poisson inclusions of probability 0.1, a record may not appear, appear once or repeat: those probabilities follow a binomial distribution. Under Poisson sampling each batch size is random too. Shuffled and Poisson loaders with the same average size do not have the same joint law, and using the wrong accountant can yield a number without a proven guarantee for the mechanism executed.

For a pure ε\varepsilon-DP base mechanism applied to Poisson subsampling with add/remove adjacency, an amplified privacy bound is log⁡(1+q(eε−1))\log(1+q(e^\varepsilon-1)). When ε\varepsilon is small, eε−1≈εe^\varepsilon-1\approx\varepsilon and the bound approaches qεq\varepsilon; for large values that approximation can substantially underestimate it. The equality does not describe every mechanism or sampling scheme: see the assumptions in Balle and colleagues.

InteractiveSampling for protection
Bound ε′ = ln(1 + q(e^ε − 1)) for Poisson inclusion and add/remove adjacency. The subsampled Gaussian RDP uses a separate formula.
Horizontal axis: q from 0 to 1. Vertical axis: ε′ from 0 to 4. Curves are for ε = 0.5, 1, 2, and 4. The dashed line marks the selected q.
0.20
1.0
Amplified ε0.295
qε approximation0.200
Theoretical pure bound for Poisson sampling and add/remove adjacency; the curves do not represent measured training results.

Accounting must report parameters, adjacency, method, steps, sampling and assumptions. The privacy-loss distribution and its numerical composition offer another route, with discretization errors requiring control. An δ\delta should be chosen in relation to the population and use case; an ε\varepsilon figure without context does not explain risk on its own.

As a common guideline, choose δ\delta considerably smaller than 1/n1/n for a population of nn protected units, although that guideline does not itself make a number acceptable. The unit can be a record or a person with several records; changing it changes sensitivity and the guarantee. The report must also include whether validation metrics or checkpoints were released and accounted for, the actual number of steps and which hyperparameter selection accessed private data.

In a basic comparison in the figure, the analytic Gaussian bound is calibrated to a fraction of the δ\delta budget, amplified with Poisson sampling and composed step by step. Advanced composition uses the same per-step mechanism and reserves half of δ\delta for the concentration term. An advanced bound can exceed the basic one; the smaller of two valid bounds for the same final budget may be chosen. The numerical curve approximates the loss distribution and its sum through circular convolution: it does not rigorously control tails, rounding or aliasing, so it does not certify privacy. The graph uses a logarithmic log⁡10(1+ε)\log_{10}(1+\varepsilon) scale to show very different values.

Moment accounting accumulates bounds on the logarithm of the loss moment; RDP organizes equivalent bounds by Rényi order and zCDP imposes a form linear in the order. GDP describes a Gaussian comparison curve; not every mechanism becomes exactly GDP by calling it that. PRV accountants use loss distributions and numerical algorithms with explicit tolerances. Gopi and colleagues analyze numerical composition with error control; our educational FFT does not implement that guarantee. A library accountant’s figure depends on its orders, tolerances and assumptions as well as the mechanism parameters.

Laboratory: Gaussian RDP without subsampling

This deliberately limited accountant composes Gaussians with equal sensitivity and noise, without sampling or accounting for floating-point errors. It is useful for checking the closed-form formula, not for certifying subsampled DP-SGD training.

[ ]Compose and convert an RDP gridBrowser
import numpy as np
steps, sensitivity, sigma, delta = 100, 1., 4., 1e-5
orders = np.arange(2, 65, dtype=float)
rdp = steps * orders * sensitivity**2 / (2*sigma**2)
eps = rdp + np.log(1/delta)/(orders-1)
i = np.argmin(eps)
print('mejor orden de la rejilla', int(orders[i]), 'cota epsilon', round(float(eps[i]), 6))
assert np.all(rdp[1:] > rdp[:-1])
from scipy.special import ndtr
from scipy.optimize import brentq
epsilon=.5;delta=1e-5
classic=np.sqrt(2*np.log(1.25/delta))/epsilon
def gaussian_delta(s):return ndtr(1/(2*s)-epsilon*s)-np.exp(epsilon)*ndtr(-1/(2*s)-epsilon*s)
analytic=brentq(lambda s:gaussian_delta(s)-delta,.01,100)
print('σ clásico umbral y σ analítico',classic,analytic)
[ ]Check the two sampling lawsBrowser
import numpy as np
rng=np.random.default_rng(31);trials=10000;steps=10;q=.1
poisson=rng.binomial(steps,q,size=trials)
# En una época barajada, cada uno de los 100 índices entra una vez.
order=np.argsort(rng.random((trials,100)),axis=1).reshape(trials,10,10)
shuffled=(order==0).sum(axis=(1,2))
print('Poisson: cero, una, al menos dos',[(poisson==0).mean(),(poisson==1).mean(),(poisson>=2).mean()])
print('barajado: cero, una, al menos dos',[(shuffled==0).mean(),(shuffled==1).mean(),(shuffled>=2).mean()])
print('Poisson teórico: cero y al menos dos',(1-q)**steps,1-(1-q)**steps-steps*q*(1-q)**(steps-1))

Integrate the mixture and compose its loss using FFT

To add or remove a record with normalized contribution of magnitude one, compare Q=N(0,σ2)Q=\mathcal N(0,\sigma^2) and P=(1−q)Q+qN(1,σ2)P=(1-q)Q+q\mathcal N(1,\sigma^2). The ratio is P(x)/Q(x)=1−q+qexp⁡(x/σ2−1/(2σ2))P(x)/Q(x)=1-q+q\exp(x/\sigma^2-1/(2\sigma^2)). The integral of the moment of that ratio gives RDP in the P∥QP\Vert Q direction; for the Poisson Gaussian mechanism and that adjacency, the cited analysis justifies using this expression in the calculation. The integral is truncated to a wide interval and checked against the binomial expansion at integer orders. Agreement is a numerical check, not a general error proof.

For FFT, group the loss L=log⁡(P/Q)L=\log(P/Q) into intervals, calculate their masses using normal CDFs, and convolve the masses of identical independent steps of the described pair. Both directions must be examined: under PP use LL, under QQ use −L-L. For a loss distribution, δ(ε)=E[(1−eε−L)+]\delta(\varepsilon)=\mathbb E[(1-e^{\varepsilon-L})_+]. Find the root of the larger of the two curves. Rounding to centers, circular convolution and truncated tails mean this estimate is not a certified bound. Comparing two grids does not prove a maximum error or independently validate a different adaptive procedure.

[ ]Integrated RDP and FFT lossBrowser
import numpy as np
from scipy.integrate import quad
from scipy.special import ndtr, logsumexp, gammaln
from scipy.optimize import brentq

def rdp_quad(a,q,s):
 def f(z):
  lr=np.logaddexp(np.log1p(-q),np.log(q)+z/s-.5/s**2)
  return np.exp(-z*z/2-.5*np.log(2*np.pi)+a*lr)
 points=sorted(set([-12.,0.,max(0.,a/s-8),a/s,a/s+12]))
 integral=sum(quad(f,x,y,epsabs=1e-11,epsrel=1e-10,limit=300)[0] for x,y in zip(points[:-1],points[1:]))
 return np.log(integral)/(a-1)
def rdp_integer(a,q,s):
 j=np.arange(a+1)
 terms=gammaln(a+1)-gammaln(j+1)-gammaln(a-j+1)+j*np.log(q)+(a-j)*np.log1p(-q)+j*(j-1)/(2*s*s)
 return logsumexp(terms)/(a-1)
def fft_epsilon(q,s,k,delta,n=32768,L=30):
 h=2*L/n;ell=(np.arange(n)-n//2)*h
 def inv(y):
  v=np.expm1(y)+q;out=np.full_like(y,-np.inf);m=v>0
  out[m]=s*s*(np.log(v[m]/q)+.5/s**2);return out
 lo,hi=inv(ell-h/2),inv(ell+h/2)
 Q=ndtr(hi/s)-ndtr(lo/s);P=(1-q)*Q+q*(ndtr((hi-1)/s)-ndtr((lo-1)/s))
 distributions=[]
 for mass in (P,np.roll(Q[::-1],1)):
  mass=np.maximum(mass,0);mass/=mass.sum()
  conv=np.fft.fftshift(np.fft.ifft(np.fft.fft(np.fft.ifftshift(mass))**k).real)
  conv=np.maximum(conv,0);conv/=conv.sum();distributions.append(conv)
 def profile(e):return max(np.sum(m*np.maximum(-np.expm1(np.minimum(e-ell,0)),0)) for m in distributions)
 return brentq(lambda e:profile(e)-delta,0,L-1)
def gauss_delta(e,s):return ndtr(1/(2*s)-e*s)-np.exp(e)*ndtr(-1/(2*s)-e*s)

q,s,k,delta=.05,1.3,100,1e-5
orders=np.arange(2,25);integral=np.array([rdp_quad(int(a),q,s) for a in orders]);closed=np.array([rdp_integer(int(a),q,s) for a in orders])
print('máxima discrepancia integral y suma',np.max(np.abs(integral-closed)))
bound=np.min(k*integral+np.log(1/delta)/(orders-1))
e0=brentq(lambda e:gauss_delta(e,s)-delta/(2*k*q),0,30)
sampled=np.log1p(q*np.expm1(e0));basic=k*sampled
advanced=np.sqrt(2*k*np.log(2/delta))*sampled+k*sampled*np.expm1(sampled)
print('básica, avanzada, RDP estándar',basic,advanced,bound)
print('FFT 32768 y 65536 intervalos',fft_epsilon(q,s,k,delta),fft_epsilon(q,s,k,delta,65536))
# Control sin submuestreo: la suma de diez pérdidas gaussianas tiene fórmula cerrada.
mu=np.sqrt(10)/s
analytic=brentq(lambda e:ndtr(mu/2-e/mu)-np.exp(e)*ndtr(-mu/2-e/mu)-delta,0,30)
print('control q=1: analítica y FFT',analytic,fft_epsilon(1.,s,10,delta,65536))

For q=0,05q=0,05, σ=1,3\sigma=1,3, 100 steps and δ=10−5\delta=10^{-5}, this run obtains standard RDP with integer orders of approximately 2.884 and FFT estimates of 2.11924 and 2.11918. The figure uses 16384 intervals and its grid parameters; it can be reproduced by repeating the calculation for each combination shown. Basic and advanced composition bound a per-step mechanism obtained from a Gaussian bound and amplification, so they can be much larger than the joint analysis.

Compare with Opacus locally

Install opacus and its dependencies in an appropriate environment. Two configurations are compared with its RDP and PRV accountants; the first matches the previous example. Opacus uses its own orders and conversions, and the PRV accountant adds its numerical tolerance: it is unsurprising that its results differ from an FFT without error control. Accounting refers to Poisson sampling; if the loader shuffles and partitions data, these figures do not certify that procedure.

[ ]Compare with OpacusLocal GPU
import opacus
from opacus.accountants import RDPAccountant, PRVAccountant
for q,s,k,delta in [(.05,1.3,100,1e-5),(.02,1.6,200,1e-6)]:
 r,p=RDPAccountant(),PRVAccountant()
 for _ in range(k):
  r.step(noise_multiplier=s,sample_rate=q);p.step(noise_multiplier=s,sample_rate=q)
 print('opacus',opacus.__version__,'q,σ,pasos,δ',q,s,k,delta,'RDP',r.get_epsilon(delta),'PRV',p.get_epsilon(delta))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Prove the ε-DP bound for the exponential mechanism with fixed candidates.
0
The utility of each candidate changes in absolute value by at most Δu between neighboring databases.

Step 1 of 2. By how much can each unnormalized weight change at most?

Proof
Prove: Explain why RDP bounds add under adaptive composition.
0
For every possible previous output, the next mechanism satisfies the same order-α RDP bound.

Step 1 of 2. What is controlled conditionally?

Numeric
For Δ₂=1, ε=0.5 and δ=10⁻⁵, calculate the threshold of the classical bound σ=√(2 ln(1.25/δ))/ε.
Numeric
For k=100, ε=0.1, δ=0 and δ′=10⁻⁵, calculate ε for the stated advanced composition bound.
Code
Implement rdp_to_dp(rdp_eps, orders, delta): return a pair containing the standard and improved bounds, each minimized over the grid and lower-bounded at zero. Reject orders ≤1 and δ outside (0,1).
def rdp_to_dp(rdp_eps, orders, delta):
  pass
Shift+Enter to run
Key idea
Valid accounting follows the actual mechanism and its assumptions; a figure without adjacency, sampling and δ does not describe the full guarantee.