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 . A sufficient classical bound, for and , uses under the standard statement. The boundary 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 and standard deviation , the analytic privacy curve is
Here is the standard normal CDF. To calibrate, find the smallest whose value does not exceed the target , 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 probability proportional to , with uniform utility sensitivity and a fixed candidate set. As 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 between neighboring databases, as does the sum of weights. Combining both factors bounds the probability ratio of any candidate by ; 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.
Composition and Rényi
The advanced composition of -DP mechanisms guarantees, for , parameters
This is a general bound, not necessarily tight. Basic composition gives ; comparing only without acknowledging the additional 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 . Subtracting those expectations leaves a sum of martingale differences; a concentration inequality controls the probability that it exceeds the term proportional to . The sum of expectations supplies the remaining linear term. The approximate extension adds the cost of exceptional events ; the full argument must address those events, not assume that losses of an mechanism are always bounded.
Rényi differential privacy bounds the Rényi divergence of order between outputs on neighboring databases. For a Gaussian with sensitivity and standard deviation , one-step RDP is bounded by ; equality is achieved for a displacement of norm . Per-step bounds add at fixed order, even under adaptive composition with uniform guarantees. The divergence is defined by
The guarantee must hold for every ordered pair of neighboring databases; swapping and 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
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.
An improved conversion used in Opacus also evaluates 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 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 , 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 -DP base mechanism applied to Poisson subsampling with add/remove adjacency, an amplified privacy bound is . When is small, and the bound approaches ; 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.
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 should be chosen in relation to the population and use case; an figure without context does not explain risk on its own.
As a common guideline, choose considerably smaller than for a population of 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 budget, amplified with Poisson sampling and composed step by step. Advanced composition uses the same per-step mechanism and reserves half of 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 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.
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)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 and . The ratio is . The integral of the moment of that ratio gives RDP in the 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 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 use , under use . For a loss distribution, . 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.
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 , , 100 steps and , 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.
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))npm run lab and open the connection link.Exercises
Step 1 of 2. By how much can each unnormalized weight change at most?
Step 1 of 2. What is controlled conditionally?
def rdp_to_dp(rdp_eps, orders, delta):
pass