Module contents
Lesson 32 of 39Core 115 min

DP-SGD: training networks with differential privacy and auditing them

Apply the preceding ideas to training. Implement DP-SGD from scratch with Poisson sampling, per-example clipping, noise addition, and privacy accounting. Study how its hyperparameters interact and techniques for narrowing the gap with non-private training, including private LLM fine-tuning with LoRA. Close the loop with the attacks from lesson 29 by empirically auditing a trained model's ε using canaries.

After this lesson you can

  • Implement DP-SGD with vectorized per-example gradients, per-example clipping, noise, and a privacy accountant.
  • Show that each step is a subsampled Gaussian mechanism and calculate the training ε.
  • Tune C, σ, batch size, and epochs to maximize utility at a fixed ε.
  • Fine-tune a small LLM with LoRA and measure canary memorization as a function of ε.
  • Audit an implementation to obtain a lower bound on ε with confidence intervals.

Before you start

From the gradient to a private mechanism

DP-SGD adapts training to limit each privacy unit’s contribution. At each step, it calculates individual gradients gi\vb g_i, clips each example’s gradient at CC, sums them, and adds Gaussian noise. Privacy accounting must match the sampling scheme and all operations that access the data. Abadi and collaborators present private training with composition accounting.

Per-example clipping applies gˉi=gimin⁡(1,C/∥g∥i)\bar{\vb g}_i=\vb g_i\min(1,C/\norm{\vb g}_i), with zero output for a zero gradient. Clipping after averaging does not limit an individual’s influence in the same way. Under add/remove adjacency, if the other gradients are unchanged, the clipped sum has sensitivity at most CC; under replacement adjacency, at most 2C2C.

InteractiveClip three gradients
123
Dashed line: original gradient. Thick line: clipped. The gray circle marks C; the line of the text color shows the original mean and magenta the clipped mean. The magenta circle has radius σC/3, a coordinate scale, and does not show a random sample nor the entire noise region. Three examples and fixed denominator.
1.0
1.0
Difference between means0.616
Noise standard deviation per coordinate0.333
The vectors are synthetic. The indicated noise is a theoretical standard deviation, not a sample nor a privacy budget.

With Poisson sampling, each record is included independently with probability qq. Add noise N(0,σ2C2I)\mathcal N(0,\sigma^2C^2I) to the sum; dividing by the public expected batch size qNqN is post-processing. The batch can be empty, so the mechanism must define that case too. The overall guarantee requires accounting for the actual subsampled mechanism, updates, and adjacency relation; the previous lesson’s Gaussian accountant without subsampling does not automatically give the appropriate bound for this case.

Utility and design

The utility of private training depends on CC, σ\sigma, batch size, architecture, and number of steps. A small CC clips more gradients and can bias their direction; a large value increases the absolute noise when σ\sigma is fixed. There is no universal frontier. Public-data pretraining and fine-tuning a subset of parameters can help, but tuning hyperparameters using private data and selecting models also require accounting. The guide by Ponomareva and collaborators details these decisions.

InteractivePrivacy and utility in a synthetic MLP
An MLP built from scratch on artificial data: 600 training examples, 2000 test examples, and 1200 simulated public pretraining examples. Same seed used, 100 steps, q=0.1 and δ=10⁻⁵.
Horizontal: ε from 0 to 16. Vertical amplified: accuracy from 0.8 to 0.9. Blue without pretraining and orange with it; the differences are less than one percentage point. The accounting uses RDP of integer orders and Poisson sampling.
Reproducible NumPy noise for teaching: this is neither a cryptographic generator nor an implementation for releasing sensitive data.
ε standard bound6.415
Accuracy without pretraining86.7 %
Accuracy with pretraining86.4 %
Clipped fraction with/without pretraining25.3 % / 23.2 %
Six reproducible training runs on artificial data with one seed. Simulated public pretraining does not improve this run; the comparison is not a universal frontier.
InteractiveNoise calculator
Binary search for σ in [0.2, 50], shown with six decimals rounded up. It is a floating point calculation, not a numerical certification. The noise added to the sum has standard deviation σC per coordinate; dividing by the public expected batch size gives σC/(qN). The curve depends on the number of steps actually performed and the accounting method.
10000
500
3
5.0
5
q and steps0.050 · 60
Approximate σ0.905107
Noise standard deviation on mean, C=10.001810
Approximate search for Poisson sampling and add/remove adjacency using an integer-order RDP accountant; other queries are not included.

Batch normalization in training mode mixes statistics across examples: changing one example can change others’ gradients and invalidate the per-example sensitivity argument. Layers that do not mix examples, such as appropriately designed group or layer normalization, are common alternatives. Gradient accumulation must preserve per-example clipping, add noise, and perform accounting for the actual logical batch.

To calculate per-example gradients, vmap applies the derivative to each input without first summing the losses. The clipping norm must cover all trainable parameters for the unit together; clipping each tensor separately at CC does not imply a global norm bound of CC. For sequences, if the protected unit is a document, sum its token losses before computing its gradient. Ghost clipping techniques calculate norms without materializing every per-example gradient, then perform a second pass with appropriate weights; Li and collaborators present a technique for linear layers. A memory optimization is insufficient if it changes the clipping result.

Increasing the expected batch size reduces the noise standard deviation σC/(qN)\sigma C/(qN) on the mean for fixed σ\sigma, but also changes qq and the number of steps per epoch: the full privacy budget must be recalculated. More epochs can improve the fit and consume more budget. If you generate several transformations of the same image, those views still belong to the same unit; for a per-person or per-record guarantee, combine their contributions before the corresponding clipping. Public pretraining can provide good features, but its utility depends on the task and on whether those data are truly independent of the protected database.

An empirical privacy audit can seek evidence that an implementation contradicts its advertised guarantee. With exact population FPR and TPR and δ=0\delta=0, the DP inequality implies ε≥log⁡(TPR/FPR)\varepsilon\ge\log(\mathrm{TPR}/\mathrm{FPR}) when both are positive. With finite data, use appropriate confidence bounds and control threshold selection; a weak attack that finds no leakage does not prove privacy. Steinke and collaborators develop a specialized audit using a single training run.

InteractiveA lower bound of ε
Counts constructed with observed TPR 20% and observed FPR 1%. The reference ε=ln(20)≈2.996 is the exact value of a hypothetical binary mechanism with those rates and δ=0, not a guarantee of training.
A combination of a one-sided lower bound for TPR and an upper bound for FPR from Clopper-Pearson at 97.5% each: by the union bound, joint coverage at least 95% under independent binomial tests and a pre-specified threshold.
The ε bound takes the maximum of zero, ln(TPR lower/FPR upper) and ln((1-FPR upper)/(1-TPR lower)). More trials narrow these intervals in this table; a weak attack does not prove privacy.
TP and FP200/1000 · 10/1000
TPR lower bound17.6 %
FPR upper bound1.8 %
ε confidence lower bound2.261
Hypothetical counts with a pre-fixed threshold; the one-sided Clopper-Pearson limits have joint coverage at least 95 % under the indicated hypotheses.

Laboratory: a synthetic update

This cell calculates per-example logistic regression gradients, clips them, adds noise to the sum, and divides by a fixed expected batch size. The dataset is artificial and the seed makes the run reproducible. The code illustrates one step; it does not include a Poisson-sampling accountant and is neither a production implementation nor a training guarantee.

[ ]A step with per-example clippingBrowser
import numpy as np
rng = np.random.default_rng(32)
N, q, C, sigma = 128, .25, 1., 1.1
X = rng.normal(size=(N,2)); y = (X[:,0]+X[:,1]>0).astype(float)
w = np.zeros(2)
selected = rng.random(N) < q
x, target = X[selected], y[selected]
p = 1/(1+np.exp(-(x@w)))
grad = (p-target)[:,None]*x
norm = np.linalg.norm(grad,axis=1,keepdims=True)
clipped = grad*np.minimum(1, C/np.maximum(norm,1e-12))
noisy_sum = clipped.sum(axis=0)+rng.normal(0,sigma*C,size=2)
private_step = noisy_sum/(q*N)
print('lote observado',len(x),'lote esperado',q*N)
print('norma máxima recortada',round(float(np.linalg.norm(clipped,axis=1).max(initial=0)),6))
print('gradiente ruidoso',np.round(private_step,4))

Train a regression and an MLP with an RDP accountant

The following experiment generates artificial data and uses 600 training examples, 2000 test examples, and 1200 simulated public pretraining examples. It manually calculates per-example gradients for an MLP and a logistic regression, clips them, samples each example independently, and divides by the fixed expected batch size. It calculates ε for 100 steps using the previous lesson’s integer-order formula. NumPy noise with a fixed seed is reproducible and non-cryptographic: ε describes the ideal random mechanism, and this cell does not protect real sensitive data.

The figure uses exactly these six MLP runs. For this seed and the values shown, pretraining does not improve test accuracy over the model without pretraining; do not extrapolate this result to other tasks. The comparison uses a single seed, and the ε values are bounds rather than measurements of leakage.

[ ]DP-SGD for regression and MLPBrowser
import json,numpy as np
from scipy.special import expit,gammaln,logsumexp
rng=np.random.default_rng(32);d,h=6,8
def generate(n):
 x=rng.normal(size=(n,d));true=x[:,0]-.7*x[:,1]+.4*x[:,2]+rng.normal(0,.5,n)
 return x,(true>0).astype(float)
X,y=generate(600);Xv,yv=generate(2000);Xp,yp=generate(1200)
size=d*h+h+h+1
def initialise():
 r=np.random.default_rng(329);return np.r_[r.normal(0,.1,d*h),np.zeros(h),r.normal(0,.1,h),0.]
def unpack(theta):
 return theta[:d*h].reshape(d,h),theta[d*h:d*h+h],theta[d*h+h:d*h+2*h],theta[-1]
def gradients(theta,x,y):
 W,b,v,c=unpack(theta);H=np.tanh(x@W+b);z=H@v+c;dz=expit(z)-y
 dh=dz[:,None]*v*(1-H*H);return np.concatenate([(x[:,:,None]*dh[:,None,:]).reshape(len(x),d*h),dh,H*dz[:,None],dz[:,None]],axis=1)
def accuracy(theta,x,y):
 W,b,v,c=unpack(theta);return float(np.mean((np.tanh(x@W+b)@v+c>=0)==y))
def fit_public(theta):
 for _ in range(120):theta-=.4*gradients(theta,Xp,yp).mean(axis=0)
 return theta
def rdp(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 epsilon(q,s,k,delta):return min(k*rdp(a,q,s)+np.log(1/delta)/(a-1) for a in range(2,25))
def train(sigma,pretrained,steps=100):
 theta=initialise();
 if pretrained:theta=fit_public(theta)
 gen=np.random.default_rng(320);q=.1;C=1.;batch=q*len(X);clipped_count=0;selected_count=0
 for _ in range(steps):
  mask=gen.random(len(X))<q;g=gradients(theta,X[mask],y[mask]);norm=np.linalg.norm(g,axis=1,keepdims=True)
  clipped_count+=int((norm>C).sum());selected_count+=len(g)
  clipped=g*np.minimum(1,C/np.maximum(norm,1e-12));noise=gen.normal(0,sigma*C,size=size)
  theta-=.4*(clipped.sum(axis=0)+noise)/batch
 return dict(sigma=sigma,pretrained=pretrained,steps=steps,q=q,delta=1e-5,eps=epsilon(q,sigma,steps,1e-5),accuracy=accuracy(theta,Xv,yv),clipped=clipped_count/selected_count)
rows=[train(s,p) for p in (False,True) for s in (.8,1.2,2.)]
for x in rows:print(x)
def logistic(sigma):
 gen=np.random.default_rng(321);w=np.zeros(d+1);x=np.column_stack([np.ones(len(X)),X]);xv=np.column_stack([np.ones(len(Xv)),Xv]);q=.1;C=1.
 for _ in range(100):
  select=gen.random(len(X))<q;g=(expit(x[select]@w)-y[select])[:,None]*x[select];norm=np.linalg.norm(g,axis=1,keepdims=True)
  clipped=g*np.minimum(1,C/np.maximum(norm,1e-12));w-=.4*(clipped.sum(axis=0)+gen.normal(0,sigma*C,d+1))/(q*len(X))
 return dict(sigma=sigma,epsilon=epsilon(q,sigma,100,1e-5),accuracy=float(np.mean((xv@w>=0)==yv)))
print('logística',logistic(1.2))

Compare membership attacks on your own models

This control trains a target regression model and 32 shadows for each configuration, with per-example clipping and noise 0 or 1.2. Each network sees 300 of the 600 synthetic examples and uses Poisson sampling at each step. The offline attack standardizes the target score using shadows that exclude the example, calibrates the threshold on half the scores, and evaluates it on the other half. In the measured run, the noise-free model produced 1 false positive and 1 true positive among 150 examples of each condition; with noise 1.2, the counts were 0 and 0. An attack with no findings does not prove privacy. With a fixed seed, the noise only illustrates the mechanism and is not securely generated.

[ ]Shadows for two own trainingsBrowser
import numpy as np
from scipy.special import expit
rng=np.random.default_rng(322);n=600;d=6;S=32
raw=rng.normal(size=(n,d));labels=(raw[:,0]-.7*raw[:,1]+.4*raw[:,2]+rng.normal(0,.5,n)>0).astype(float)
X=np.column_stack([np.ones(n),raw]);membership=np.stack([rng.permutation(n)<n//2 for _ in range(S+1)])
assert np.all(membership.sum(1)==n//2)
def fit(noise):
 gen=np.random.default_rng(323);w=np.zeros((S+1,d+1));q=.1;C=1.;expected=q*(n//2)
 for _ in range(100):
  sample=(gen.random((S+1,n))<q)&membership
  error=expit([email protected])-labels;norm=np.abs(error)*np.linalg.norm(X,axis=1)[None,:]
  factor=sample*error*np.minimum(1,C/np.maximum(norm,1e-12))
  w-=.4*((factor@X)+gen.normal(0,noise*C,w.shape))/expected
 logits=([email protected])*(2*labels-1);target=logits[0];sh=logits[1:];inside=membership[1:];target_members=membership[0]
 count=(~inside).sum(0);mean=np.where(~inside,sh,0).sum(0)/count
 sd=np.maximum(np.sqrt(np.where(~inside,(sh-mean)**2,0).sum(0)/np.maximum(count-1,1)),.05)
 score=(target-mean)/sd
 split=np.random.default_rng(324);cal=np.zeros(n,dtype=bool)
 for group in (False,True):
  idx=split.permutation(np.flatnonzero(target_members==group));cal[idx[:len(idx)//2]]=True
 test=~cal;out=score[cal&~target_members];threshold=np.sort(out)[-max(1,int(.01*len(out)))]
 return dict(noise=noise,threshold=float(threshold),fp=int(np.sum((score>=threshold)&test&~target_members)),tn=int(np.sum(test&~target_members)),tp=int(np.sum((score>=threshold)&test&target_members)),members=int(np.sum(test&target_members)))
print('32 sombras, puntuación offline, test separado')
for s in (0.,1.2):print(fit(s))

Two implementations on public CIFAR-10

This cell uses the first 512 training images and 1000 test images from CIFAR-10. It trains a small CNN for eight expected steps with Poisson sampling, first with Opacus and then with per-example gradients via torch.func.vmap. Both use q=0.125, C=1, σ=1.2, and the Opacus RDP accountant for δ=10⁻⁵. In the RTX 3060 run, Opacus reported ε≈2.667 and accuracy 10.5%, and the from-scratch implementation reported ε≈2.667 and accuracy 16.1%. These are short runs with different sampling and noise realizations, with no claim of quality or numerical equivalence between trajectories.

Install PyTorch, torchvision, and Opacus. If CIFAR-10 is absent from CIFAR_DIR or ./cifar_data, torchvision downloads it from its configured source. secure_mode=False and fixed seeds make the experiment reproducible; do not use this cell as a production guarantee or with sensitive data. Adjacency is record-level and does not cover people with multiple records without additional analysis.

[ ]CIFAR-10 with Opacus and torch.funcLocal GPU
import os,torch,numpy as np
from torch import nn
from torch.utils.data import DataLoader,Subset,TensorDataset
from torch.func import functional_call,grad,vmap
from torchvision.datasets import CIFAR10
from torchvision.transforms import ToTensor
from opacus import PrivacyEngine
from opacus.accountants import RDPAccountant
torch.set_num_threads(1);torch.manual_seed(32);device='cuda' if torch.cuda.is_available() else 'cpu'
root=os.environ.get('CIFAR_DIR','./cifar_data')
download=not os.path.isdir(os.path.join(root,'cifar-10-batches-py'))
train=CIFAR10(root,train=True,download=download,transform=ToTensor());test=CIFAR10(root,train=False,download=False,transform=ToTensor())
X=torch.stack([train[i][0] for i in range(512)]).to(device);Y=torch.tensor([train[i][1] for i in range(512)],device=device)
Xv=torch.stack([test[i][0] for i in range(1000)]).to(device);Yv=torch.tensor([test[i][1] for i in range(1000)],device=device)
def make():return nn.Sequential(nn.Conv2d(3,8,3,padding=1),nn.ReLU(),nn.AvgPool2d(4),nn.Flatten(),nn.Linear(8*8*8,10)).to(device)
def eval_model(model):
 model.eval()
 with torch.no_grad():return float((model(Xv).argmax(1)==Yv).float().mean())
torch.manual_seed(32);model=make();loader=DataLoader(TensorDataset(X,Y),batch_size=64,shuffle=True)
opt=torch.optim.SGD(model.parameters(),lr=.2);engine=PrivacyEngine(accountant='rdp',secure_mode=False)
model,opt,loader=engine.make_private(module=model,optimizer=opt,data_loader=loader,noise_multiplier=1.2,max_grad_norm=1.)
for xx,yy in loader:
 opt.zero_grad();loss=nn.functional.cross_entropy(model(xx),yy);loss.backward();opt.step()
print('Opacus','pasos',len(loader),'epsilon',engine.get_epsilon(delta=1e-5),'exactitud',eval_model(model),flush=True)

torch.manual_seed(32);model=make();params=dict(model.named_parameters());buffers=dict(model.named_buffers())
def sample_loss(params,buffers,x,y):return nn.functional.cross_entropy(functional_call(model,(params,buffers),(x.unsqueeze(0),)),y.unsqueeze(0))
per_example=vmap(grad(sample_loss),in_dims=(None,None,0,0));q=.125;C=1.;sigma=1.2;accountant=RDPAccountant()
for step in range(8):
 select=torch.rand(len(X),device=device)<q;xx=X[select];yy=Y[select]
 if len(xx):
  gs=per_example(params,buffers,xx,yy);norm=torch.sqrt(sum(g.reshape(len(xx),-1).pow(2).sum(1) for g in gs.values()))
  scale=(C/norm.clamp_min(1e-12)).clamp(max=1)
 else:gs=None
 with torch.no_grad():
  for name,p in params.items():
   summed=(gs[name]*scale.reshape((-1,)+(1,)*p.ndim)).sum(0) if gs is not None else torch.zeros_like(p)
   p-=.2*(summed+torch.randn_like(p)*sigma*C)/(q*len(X))
 accountant.step(noise_multiplier=sigma,sample_rate=q)
print('torch.func','pasos',8,'epsilon',accountant.get_epsilon(delta=1e-5),'exactitud',eval_model(model),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Private GPT-2 fine-tuning with LoRA and a fictitious canary

The following experiment uses GPT-2 small at a pinned revision and freezes its weights. It adds a rank-two LoRA adapter to the last block’s attention projection: only 6144 parameters are updated. The corpus contains twelve artificial examples from the previous lesson and four copies of the fictitious canary FAKE_TOKEN_DELTA=demo_193. It evaluates the 1000 three-digit suffixes using the full sequence probability. The duplication creates four records; the accountant gives a per-record bound, not a guarantee for removing all four copies as one person’s contribution.

In the eight-step local run, the canary had rank 82 and exposure 3.608 bits both before fine-tuning and after noise-free fine-tuning. With σ=1.2, the Opacus RDP accountant gives ε≈4.608 and the observed rank is 80 (3.644 bits); with σ=2, ε≈2.076 and rank 81 (3.626 bits), both with δ=10⁻⁵. These small variations do not demonstrate a monotonic relationship or reproduce the conclusions of a large-scale study. The comparisons depend on this prefix, these candidates, and a single seed. A public seed and torch.randn are not a cryptographic source: the figures analyze the ideal mechanism, not a guarantee for sensitive data.

Install PyTorch, Transformers, and Opacus; the first execution may download the weights. The calculation evaluates thousands of continuations and may take several minutes. The selection of canaries and hyperparameters are public in this example; if they depended on private data, that selection would need to be accounted for.

[ ]LoRA private and exposure of a private canaryLocal GPU
import os, math, numpy as np, torch
from torch import nn
from transformers import AutoTokenizer,AutoModelForCausalLM
from opacus.accountants import RDPAccountant
torch.set_num_threads(1);torch.manual_seed(32)
model_id='openai-community/gpt2';revision='607a30d783dfa663caf39e06633721c8d4cfcd7e'
tok=AutoTokenizer.from_pretrained(model_id,revision=revision);tok.pad_token=tok.eos_token
model=AutoModelForCausalLM.from_pretrained(model_id,revision=revision).eval()
device='cuda' if torch.cuda.is_available() else 'cpu';model.to(device)
for p in model.parameters():p.requires_grad_(False)
class LoRA(nn.Module):
 def __init__(self,base):
  super().__init__();self.base=base;self.A=nn.Parameter(torch.randn(768,2,device=device)*.02);self.B=nn.Parameter(torch.zeros(2,2304,device=device))
 def forward(self,x):return self.base(x)+([email protected]@self.B)
model.transformer.h[-1].attn.c_attn=LoRA(model.transformer.h[-1].attn.c_attn)
adapter=model.transformer.h[-1].attn.c_attn;params=[adapter.A,adapter.B];initial=[p.detach().clone() for p in params]
canary='FAKE_TOKEN_DELTA=demo_193';records=[f'# example {i:03d}\nVALUE_{i%10}={i%37:02d}\n' for i in range(12)]+[(canary+'\n')]*4
encoded=[tok(x,return_tensors='pt').to(device) for x in records];q=.25;C=1.;steps=8
def exposure():
 prefix='FAKE_TOKEN_DELTA=demo_';scores=[]
 for start in range(0,1000,25):
  samples=[prefix+f'{i:03d}\n' for i in range(start,min(start+25,1000))]
  batch=tok(samples,return_tensors='pt',padding=True).to(device)
  with torch.no_grad():
   z=model(**batch,use_cache=False).logits[:,:-1].log_softmax(-1)
   logp=z.gather(-1,batch.input_ids[:,1:,None]).squeeze(-1)*batch.attention_mask[:,1:]
   scores.extend(logp.sum(1).cpu().tolist())
 rank=1+sum(x>scores[193] for x in scores)
 return rank,math.log2(1000)-math.log2(rank)
print('device',device,'trainable',sum(p.numel() for p in params),'base rank/exposure',exposure(),flush=True)
for sigma in (0.,1.2,2.):
 for p,v in zip(params,initial):p.data.copy_(v)
 torch.manual_seed(32);gen=np.random.default_rng(32);acc=RDPAccountant()
 for step in range(steps):
  indices=np.flatnonzero(gen.random(len(records))<q);totals=[torch.zeros_like(p) for p in params]
  for i in indices:
   model.zero_grad(set_to_none=True);batch=encoded[int(i)];loss=model(**batch,labels=batch.input_ids,use_cache=False).loss;loss.backward()
   norm=torch.sqrt(sum(p.grad.detach().pow(2).sum() for p in params));scale=min(1.,C/(float(norm)+1e-12))
   for total,p in zip(totals,params):total.add_(p.grad.detach(),alpha=scale)
  with torch.no_grad():
   for p,total in zip(params,totals):p-=.1*(total+torch.randn_like(p)*sigma*C)/(q*len(records))
  if sigma:acc.step(noise_multiplier=sigma,sample_rate=q)
 print('sigma',sigma,'steps',steps,'epsilon',acc.get_epsilon(delta=1e-5) if sigma else 'sin garantía','rank/exposure',exposure(),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Audit a single execution

This test reproduces the scheme of Steinke and collaborators: 80 artificial vector canaries are included or excluded independently with probability 1/2, a single logistic regression is trained, and all canaries are scored. Before inspecting their memberships, the protocol fixes 20 positive and 20 negative predictions, abstaining on the rest. The paper’s test allows dependence between predictions from the same training run and adds a correction for δ. Inclusion, ranking, and the prediction rule are part of the protocol.

In the run with seed 326, 40 canaries were included and 14 of the 40 predictions were correct. The p-value for ε=0 is approximately 0.981 and the 95% lower bound is zero for δ=10⁻⁵. The previous cell’s standard RDP accountant, with q=0.1, σ=1.2, and 100 steps, gives the ideal upper bound of 6.415 per record. A zero lower bound does not prove that training is private: it describes this audit’s limited power. The code uses pseudorandom numbers with a public seed and synthetic data, not a secure noise source.

[ ]A synthetic canary auditBrowser
import numpy as np
from scipy.special import expit
from scipy.stats import binom
rng=np.random.default_rng(326);d=6;m=80;fixed=200;q=.1;C=1.;sigma=1.2;steps=100;delta=1e-5
def make(n):
 x=rng.normal(size=(n,d));z=x[:,0]-.7*x[:,1]+.4*x[:,2]+rng.normal(0,.5,n)
 return np.column_stack([np.ones(n),x]),(z>0).astype(float)
Xbase,ybase=make(fixed);Xcan,ycan=make(m);included=rng.random(m)<.5
X=np.r_[Xbase,Xcan[included]];y=np.r_[ybase,ycan[included]];w=np.zeros(d+1);expected=q*(fixed+m/2)
for _ in range(steps):
 select=rng.random(len(X))<q;g=(expit(X[select]@w)-y[select])[:,None]*X[select]
 norm=np.linalg.norm(g,axis=1,keepdims=True);clipped=g*np.minimum(1,C/np.maximum(norm,1e-12))
 w-=.4*(clipped.sum(0)+rng.normal(0,sigma*C,size=d+1))/expected
scores=(Xcan@w)*(2*ycan-1);order=np.argsort(scores);guesses=np.zeros(m,dtype=int)
guesses[order[:20]]=-1;guesses[order[-20:]]=1;truth=np.where(included,1,-1)
correct=int(np.sum((guesses==truth)&(guesses!=0)));r=int(np.sum(guesses!=0))
def p_bound(e,m=m,r=r,v=correct,delta=delta):
 p=expit(e);tail=binom.sf(v-1,r,p)
 if v==0:return 1.
 probs=binom.pmf(v-np.arange(1,v+1),r,p)
 correction=np.max(np.cumsum(probs)/np.arange(1,v+1))
 return min(1.,float(tail+2*m*delta*correction))
if p_bound(0)>=.05:lower=0.
else:
 lo,hi=0.,1.
 while p_bound(hi)<.05:hi*=2
 for _ in range(40):
  mid=(lo+hi)/2
  if p_bound(mid)<.05:lo=mid
  else:hi=mid
 lower=lo
print('canarios',m,'incluidos',int(included.sum()),'respuestas',r,'aciertos',correct)
print('p nulo epsilon=0',p_bound(0),'cota inferior 95%',lower,'delta',delta)
print('control publicado m=r=100, aciertos=75, ε=ln 3, δ=0',p_bound(np.log(3),100,100,75,0))

Construct a hypothetical audit bound

The following calculation reproduces the figure using hypothetical counts. Fix the threshold in advance, obtain one-sided bounds for both rates, and apply the DP inequality in both directions. This is neither an audit of actual training nor the specialized single-run method; those guarantees require their own experimental designs.

[ ]Confidence bounds for a hypothetical testBrowser
import numpy as np
from scipy.stats import beta
for n in (100,1000,10000,100000):
 tp=n//5;fp=n//100;tl=beta.ppf(.025,tp,n-tp+1);fu=beta.ppf(.975,fp+1,n-fp)
 lower=max(0.,np.log(tl/fu),np.log((1-fu)/(1-tl)))
 print('n',n,'TPR inferior',tl,'FPR superior',fu,'ε inferior',lower)

Exercises

Proof
Prove: Bound the sensitivity of the sum of clipped gradients.
0
Two databases differ by the addition or removal of one example, and the other examples' gradients do not change.

Step 1 of 2. What difference is there between the sums?

Numeric
For σ=1,1, C=1 and expected public batch 1024, what is the noise coordinate standard deviation on the mean gradient?
Numeric
With δ=0 and exact population rates FPR=0.01 and TPR=0.2, calculate the lower bound on ε using natural logarithms.
Quiz
Why does batch normalization during training require special care in DP-SGD?
Code
Implement clip_and_noise(grads, C, sigma, expected_batch, rng): grads is B×d, clip each row, add Gaussian noise of standard deviation σC to the sum and divide by the public expected batch. It must accept B=0.
def clip_and_noise(grads, C, sigma, expected_batch, rng):
  pass
Shift+Enter to run
Key idea
DP-SGD requires per-example clipping, noise, sampling, and consistent accounting; a single illustrative step or a finding-free audit do not certify complete training.