Module contents
Lesson 29 of 39Core 110 min

Privacy attacks: membership inference, data extraction and inversion

Measure how much a model reveals about its training data before learning to protect it. Formulate membership inference as a hypothesis test, progress from threshold attacks to LiRA, and evaluate TPR at very low FPR. Extract synthetic training data from your own language model using canaries, including fictitious API keys relevant to code models, measure memorization, and introduce the reconstruction attacks that motivate differential privacy.

After this lesson you can

  • Formulate membership inference as a hypothesis test and relate its success to the generalization gap.
  • Implement threshold attacks, shadow-model attacks, and LiRA, and evaluate them with ROC curves on a logarithmic FPR axis.
  • Insert canaries in a language model, measure their exposure, and extract them.
  • Distinguish extractability, counterfactual memorization and duplication as sources of leakage.
  • Explain with the reconstruction attack by Dinur and Nissim why noise is needed to protect privacy.

Before you start

What question does a membership audit ask?

Membership inference contrasts two hypotheses: that an example was included in training or that it was not. A score calculated from the model’s response may differ between these cases, but a low loss does not prove that a specific record was a member. A generalization gap can facilitate inference; its absence does not guarantee that no individual example is exposed.

The threat model determines what is observed, how members and non-members are constructed, and what constitutes a success. Carlini and collaborators recommend measuring the true positive rate at very low false positive rates, because the average accuracy can hide a vulnerable tail.

InteractiveInspect the low-FPR tail
Toy scores: 2000 non-members uniformly spaced between 0 and 1; 1900 members with the same pattern and 100 with score 1.01.
Membership is predicted if the score is at least the threshold. Each false positive changes the FPR by 0.05 percentage points.
These rates are exact counts of the toy, not results of an attack on a model nor confidence intervals.
0.999
False positives2 / 2000 · 0.10 %
True positives102 / 2000 · 5.10 %
Handcrafted data illustrate counts and resolution. The figure does not represent a measurement of a real model.

Membership inference evaluation needs enough non-members: with 2000 examples, one false positive equals 0.05 percentage points and two equal 0.1 %. Even observing zero false positives does not prove that the population FPR is zero. Separate calibration and test sets, report uncertainty intervals, ties, and sample size, and consider the membership base rate before interpreting a positive prediction.

InteractiveLosses and ROC curves of trained models
2200 artificial examples, 200 members and 2000 non-members. Blue: histogram of member loss; orange: non-members. The bars are proportions by group; the intervals cover losses of 0 to 3.44. Membership is predicted when the loss does not exceed the threshold.
Empirical ROC: logarithmic FPR horizontally, TPR vertically. Points of FPR zero are drawn at 1/2000 to allow the scale; they do not equate to that FPR. The threshold is chosen in this same sample, so the result is exploratory.
With only two false positives in the region of 0.1%, tail estimates are very uncertain. The absence of observed false positives does not demonstrate a zero population FPR.
0.20
empirical FPR17.1 %
empirical TPR20.0 %
TPR with empirical FPR ≤0.1 %0.0 %
Mean loss: member/non-member0.519 / 0.651
Four training configurations of a NumPy MLP on artificial data; each distribution uses 200 members and 2000 non-members. The region at FPR 0.1% contains only two false positives and has substantial uncertainty.

The four configurations start from the same initialization and synthetic set; they modify steps and L2 penalty. In one execution, 150 steps without regularization produce a mean loss of 0.519 for members and 0.651 for non-members; with L2 equal to 0.05, the means are 0.624 and 0.647. These are results of this experiment, not a universal relationship. 1800 non-members generated by the same procedure are added to observe the tail; the curve and thresholds are calculated on the same examples and do not measure performance on a held-out sample.

Compare with reference models

The LiRA test calibrates an example’s score against reference models trained with or without it, under a defined protocol. The online version compares distributions under both conditions; offline variants use an exclusion reference. Gaussian approximations and transformations must be validated for each example, especially in the tails; an arbitrary loss is not a probability, so do not apply the logit to it without first defining a valid probability.

InteractiveThe likelihood of an example
Logit of the probability assigned to the correct label: blue for models that included the example and orange for those that did not. Each curve fits a Gaussian to the measurements of that example; dashed line: score of the target model.
Example 153: 14 shadows including it and 18 excluding it. The Gaussian fit and its standard deviation floor of 0.05 are approximations. The real membership is shown only for experiment evaluation.
Target logit0.289
Online log-likelihood ratio0.326
True membershipmember
Two examples from the lab's 32 shadow MLPs, selected at the median and maximum ranks of the absolute offline score; approximate Gaussian curves.

The online likelihood ratio compares the fitted density at the target score under inclusion with the fitted density under exclusion. The offline example in the cell uses a standardized one-sided score relative to the exclusion shadows; it does not claim to be identical to all published variants of LiRA. Each estimate uses a few dozen shadows and a standard deviation floor of 0.05 to avoid unstable divisions; these choices particularly affect the tails. The experiment does not support generalization to other models.

In language models, differences in date, source, or style between members and non-members can produce a distributional signal rather than a membership signal. Duan and collaborators demonstrate the importance of this control in pretraining evaluations. A metric based on unlikely tokens, such as Min-K%, must also be evaluated against those controls; no score offers universal evidence of membership.

Memorization and extraction

Training data extraction asks whether a sequence can be recovered from the model’s behavior under a given protocol. Memorization, high probability, and extractability are not synonyms: they depend on the context, candidates, and access. A synthetic canary inserted by the auditors can quantify risk without using real secrets. The exposure proposed by Carlini and collaborators is log⁡2N−log⁡2r\log_2 N-\log_2 r for a space of NN candidates and a canary at rank rr; the rank and reference space must be defined.

Prefix-conditioned extractability asks whether a specific generation rule recovers a training continuation when provided with a context of a given length. Changing the prefix, temperature, or decoding rule changes the question; a likely sequence does not necessarily appear in greedy generation. Exposure compares a canary with candidates from a specified space, while counterfactual memorization compares models trained with and without a piece of data under a training protocol. Carlini and collaborators study relationships between scale, duplication, and memorization; a correlation in one run does not by itself identify the cause of a leak.

An audit can generate candidates in a controlled environment and rank them using a score sensitive to probability and compressibility. The ranking depends on the candidate set; a high score does not establish that a sequence came from training. Behavioral changes caused by repetitive inputs have also been studied in production language models. This lesson neither tests that phenomenon nor queries an external service; its exercises use only controlled fictitious tokens.

Memorization measures include comparing the model with a counterfactual trained without a document. Zhang and collaborators study this difference to distinguish a document’s influence from that of common or repeated text. Deduplication, source review, and access controls reduce risks, but they are not by themselves equivalent to a formal guarantee.

InteractiveExposure of artificial canaries
A GRU trained from scratch, a synthetic corpus, and FAKE_TOKEN labels. Exposure is log₂(1000) - log₂(rank); rank uses the full sequence probability among 1000 possible suffixes.
ALPHA · 1 insertions · rank 651/1000 · exposure 0.62 bits · greedy prefix completion: does not recover the canary
BRAVO · 5 insertions · rank 84/1000 · exposure 3.57 bits · greedy prefix completion: does not recover the canary
CHARLIE · 20 insertions · rank 2/1000 · exposure 8.97 bits · greedy prefix completion: does not recover the canary
DELTA · 80 insertions · rank 1/1000 · exposure 9.97 bits · greedy prefix completion: recovers the canary
Measured lab results at epochs 0, 5, 10, and 20. Rank ties are counted optimistically.
Prefix candidates1000
Epoch20
A run of a character-level GRU trained from scratch on synthetic code; none of the tokens is a real credential.

The run shown in the figure includes four different canaries inserted 1, 5, 20, and 80 times, and compares each suffix with the 1000 possible three-digit numbers under the same prefix. The rank uses the probability of the full sequence; ties are counted optimistically. After 20 epochs, the observed ranks were 651, 84, 2, and 1 respectively. From epoch 10, greedy completion recovered the canary inserted 80 times; the other three were not recovered with that rule. The comparison uses a single seed and confounds canary identity with repetition count: it does not estimate the causal effect of duplicating the same text.

Model inversion and attribute inference seek to recover information associated with inputs or data. Reconstruction attacks show that many aggregate responses can leak a database even if each response seems uninformative. The effect of noise depends on the queries, mechanism, and threat; do not extrapolate a theorem’s noise scale to an arbitrary system. Differential privacy, covered later, offers a formal definition that limits an individual’s effect under its assumptions.

Dinur and Nissim study subset sums of a binary database and a specific model of perturbed responses. Their result links reconstruction to perturbations on the square-root scale in nn under their conditions; it does not say that adding arbitrary noise of that scale protects any system. The following exercise uses only 32 artificial bits and least squares; it does not implement the proof or establish the asymptotic theorem.

InteractiveReconstruct synthetic sums
32 synthetic bits and subset sums; unrestricted least squares followed by thresholding at 0.5. Each cell shows the true bit above and the reconstruction below.
1
1
0
0
1
1
1
1
0
0
1
1
1
1
0
0
1
1
0
0
1
1
0
0
0
0
0
0
0
0
0
0
1
1
0
1
0
0
0
0
0
0
1
1
0
0
1
1
1
1
1
1
0
0
1
1
1
1
1
0
0
0
0
0
The amber boxes are errors. By increasing the noise or the number of queries, the results may vary non-monotonically in a specific realization.
Bits reconstructed correctly93.8 %
A fixed realization with seed 29. The table compares generated bits with least squares estimates; there are no private data.

Lab: rates on synthetic data

The code reproduces the counts of the figure: it does not train nor query a model and does not use human data. Change the threshold and observe that the resolution of the FPR depends on the number of non-members.

[ ]Count true and false positivesBrowser
import numpy as np
negative = (np.arange(2000)+.5)/2000
positive = np.r_[(np.arange(1900)+.5)/1900, np.full(100, 1.01)]
for threshold in (.995, .999, 1.0, 1.02):
    fp = int(np.sum(negative >= threshold)); tp = int(np.sum(positive >= threshold))
    print('umbral', threshold, 'FP', fp, 'FPR', fp/len(negative),
          'TP', tp, 'TPR', tp/len(positive))

Change steps and regularization

The four training configurations used in the figure share initialization, data, and split; their mean losses by membership show the gap in this sample. The cell reproduces the figure’s values with seed 291.

[ ]Train four synthetic MLPsBrowser
import json,numpy as np
from scipy.special import expit
rng=np.random.default_rng(291);n,d,h=400,8,12
X=rng.normal(size=(n,d));truth=(X[:,0]*X[:,1]+.5*X[:,2]-.4*X[:,3]>0).astype(int)
y=np.where(rng.random(n)<.15,1-truth,truth);member=rng.permutation(n)<200
W0=rng.normal(0,.25,(d,h));v0=rng.normal(0,.25,h);rows=[]
Xe=rng.normal(size=(1800,d));te=(Xe[:,0]*Xe[:,1]+.5*Xe[:,2]-.4*Xe[:,3]>0).astype(int)
ye=np.where(rng.random(1800)<.15,1-te,te);Xall=np.r_[X,Xe];yall=np.r_[y,ye];membership=np.r_[member,np.zeros(1800,dtype=bool)]
for reg in (0.,.05):
 W=W0.copy();v=v0.copy();b=np.zeros(h);c=0.
 for step in range(1,151):
  H=np.tanh(X@W+b);z=H@v+c;dz=(expit(z)-y)*member/member.sum()
  dv=H.T@dz+reg*v;dc=dz.sum();dh=dz[:,None]*v*(1-H**2)
  W-=.4*(X.T@dh+reg*W);b-=.4*dh.sum(axis=0);v-=.4*dv;c-=.4*dc
  if step in (20,150):
   z=np.tanh(Xall@W+b)@v+c;loss=np.logaddexp(0,-z*(2*yall-1))
   rows.append(dict(steps=step,regularization=reg,loss=loss.tolist()))
   print('pasos',step,'regularizacion',reg,'perdida miembro/no',float(loss[membership].mean()),float(loss[~membership].mean()))

Toy reconstruction

A binary database, queries, and noise are generated with seed 29; the same realization is reused to compare σ values and query counts. The outputs need not be monotonic within one sample. Averaging over multiple seeds would be necessary to study variability; this cell reproduces the figure’s data exactly.

[ ]Synthetic sums and least squaresBrowser
import json,numpy as np
rng=np.random.default_rng(29);n=32;bits=rng.integers(0,2,n);A=rng.integers(0,2,size=(256,n));noise=rng.normal(size=256)
rows=[]
for m in (32,64,128,256):
 sigmas=np.array([0.,.5,2.,4.,8.]);Y=(A[:m]@bits)[:,None]+noise[:m,None]*sigmas
 estimates=np.linalg.lstsq(A[:m],Y,rcond=None)[0]
 for j,sigma in enumerate(sigmas):
  reconstructed=(estimates[:,j]>=.5).astype(int);accuracy=float(np.mean(reconstructed==bits))
  rows.append(dict(queries=m,sigma=sigma,accuracy=accuracy,reconstructed=reconstructed.tolist()))
  print('consultas',m,'σ',sigma,'acierto',accuracy)

Shadow models and per-example likelihood ratios

Here we train 32 single-hidden-layer shadow MLPs and a target model from scratch in parallel, using random membership masks over the same 400 synthetic examples. NumPy computes each network’s gradients, ROC, and AUC. The score is the logit of the probability assigned to the correct label. Per-example means and standard deviations are estimated from inclusion and exclusion shadows. The ROC over all examples is exploratory. The cell also splits examples into calibration and test halves, stratified by membership, to choose thresholds and count test successes. With only 100 test non-members, tail uncertainty remains large.

In an execution with seed 29, the 200 non-members allow FPR jumps of 0.5 percentage points. At 1% FPR, the TPR is 0.04 for the loss threshold, 0.03 for LiRA online, and 0.025 for the offline variant; AUCs are respectively 0.565, 0.581, and 0.627. These numbers are a small experiment, not a general comparison nor a measurement at 0.1% FPR. In the curve, the zeros are plotted at the resolution 1/N to be able to use a logarithmic scale, without asserting that this is their real FPR.

[ ]Train shadows and calculate LiRABrowser
import json,numpy as np
from scipy.special import expit
import matplotlib.pyplot as plt
rng=np.random.default_rng(29);n,d,hidden,shadows=400,8,12,32
X=rng.normal(size=(n,d));truth=(X[:,0]*X[:,1]+.5*X[:,2]-.4*X[:,3]>0).astype(int)
y=np.where(rng.random(n)<.15,1-truth,truth)
masks=rng.random((shadows+1,n))<.5
W=rng.normal(0,.25,(shadows+1,d,hidden));b=np.zeros((shadows+1,hidden));v=rng.normal(0,.25,(shadows+1,hidden));c=np.zeros(shadows+1)
for _ in range(150):
 H=np.tanh(np.einsum('nd,sdh->snh',X,W)+b[:,None,:]);z=np.einsum('snh,sh->sn',H,v)+c[:,None]
 dz=(expit(z)-y)*masks/masks.sum(axis=1)[:,None]
 dv=np.einsum('sn,snh->sh',dz,H);dc=dz.sum(axis=1)
 dh=dz[:,:,None]*v[:,None,:]*(1-H**2)
 dW=np.einsum('nd,snh->sdh',X,dh);db=dh.sum(axis=1)
 W-=.4*dW;b-=.4*db;v-=.4*dv;c-=.4*dc
H=np.tanh(np.einsum('nd,sdh->snh',X,W)+b[:,None,:]);z=np.einsum('snh,sh->sn',H,v)+c[:,None]
scores=z*(2*y-1);target=scores[0];member=masks[0];sh=scores[1:];inside=masks[1:]
# Puntuación: logit de la probabilidad asignada a la etiqueta correcta.
def stats(data,mask):
 count=mask.sum(axis=0);mean=np.where(mask,data,0).sum(axis=0)/count
 var=np.where(mask,(data-mean)**2,0).sum(axis=0)/np.maximum(count-1,1)
 return mean,np.maximum(np.sqrt(var),.05)
assert inside.sum(axis=0).min()>1 and (~inside).sum(axis=0).min()>1
mu_in,sd_in=stats(sh,inside);mu_out,sd_out=stats(sh,~inside)
online=np.log(sd_out/sd_in)-.5*((target-mu_in)/sd_in)**2+.5*((target-mu_out)/sd_out)**2
offline=(target-mu_out)/sd_out
def roc_curve(member,score):
 order=np.argsort(-score,kind='stable');sorted_score=score[order]
 cuts=np.r_[np.flatnonzero(np.diff(sorted_score)!=0),len(score)-1]
 tp=np.cumsum(member[order])[cuts];fp=np.cumsum(~member[order])[cuts]
 return np.r_[0,fp/(~member).sum()],np.r_[0,tp/member.sum()]
def at_fpr(score,cap=.01):
 fpr,tpr=roc_curve(member,score);valid=np.flatnonzero(fpr<=cap+1e-12);j=valid[np.argmax(tpr[valid])]
 return float(fpr[j]),float(tpr[j]),float(np.trapezoid(tpr,fpr))
for name,s in [('perdida',target),('lira_online',online),('lira_offline',offline)]:print(name,'FPR,TPR,AUC',at_fpr(s),flush=True)
# Umbrales calibrados únicamente en la mitad de cada grupo; evaluación en la otra mitad.
split=np.random.default_rng(290);cal=np.zeros(n,dtype=bool)
for group in (False,True):
 idx=split.permutation(np.flatnonzero(member==group));cal[idx[:len(idx)//2]]=True
test=~cal
for name,s in [('perdida',target),('lira_online',online),('lira_offline',offline)]:
 negatives=np.sort(s[cal&~member]);allowed=max(1,int(.01*len(negatives)));threshold=negatives[-allowed]
 print('test reservado',name,'umbral',float(threshold),'FP',int(np.sum((s>=threshold)&test&~member)),'/',int(np.sum(test&~member)),
       'TP',int(np.sum((s>=threshold)&test&member)),'/',int(np.sum(test&member)))
fpr,tpr=roc_curve(member,online);plt.semilogx(np.maximum(fpr,1/(~member).sum()),tpr,label='LiRA online');plt.xlabel('FPR (escala log; ceros en resolución 1/N)');plt.ylabel('TPR');plt.legend();plt.show()
entries=[]
for j in (np.argsort(np.abs(offline))[n//2],np.argmax(np.abs(offline))):entries.append({'example':int(j),'member':bool(member[j]),'target':float(target[j]),'in':sh[:,j][inside[:,j]].tolist(),'out':sh[:,j][~inside[:,j]].tolist(),'mu_in':float(mu_in[j]),'mu_out':float(mu_out[j]),'sd_in':float(sd_in[j]),'sd_out':float(sd_out[j])})

The next variant uses 32 scikit-learn MLPs, 12 iterations each, independent initializations, and the same synthetic protocol. The networks are deliberately undertrained: a convergence warning does not establish convergence. Results may differ from the vectorized MLP because the optimizer and initialization change. The cell prints the loaded library version and every rate, including negative results.

[ ]Shadow Models with scikit-learnBrowser
import warnings, numpy as np, sklearn
from sklearn.neural_network import MLPClassifier
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings('ignore',category=ConvergenceWarning)
rng=np.random.default_rng(29);n,d,shadows=400,8,32
X=rng.normal(size=(n,d));truth=(X[:,0]*X[:,1]+.5*X[:,2]-.4*X[:,3]>0).astype(int)
y=np.where(rng.random(n)<.15,1-truth,truth);masks=rng.random((shadows+1,n))<.5
logits=[]
for i,mask in enumerate(masks):
 model=MLPClassifier(hidden_layer_sizes=(12,),activation='tanh',solver='sgd',learning_rate_init=.05,batch_size=int(mask.sum()),max_iter=12,random_state=29+i)
 model.fit(X[mask],y[mask]);p=model.predict_proba(X)[np.arange(n),y];p=np.clip(p,1e-7,1-1e-7)
 logits.append(np.log(p/(1-p)))
logits=np.array(logits);target,sh,inside=logits[0],logits[1:],masks[1:];member=masks[0]
def stats(data,mask):
 count=mask.sum(axis=0);mu=np.where(mask,data,0).sum(axis=0)/count
 sd=np.maximum(np.sqrt(np.where(mask,(data-mu)**2,0).sum(axis=0)/np.maximum(count-1,1)),.05)
 return mu,sd
mi,si=stats(sh,inside);mo,so=stats(sh,~inside)
online=np.log(so/si)-.5*((target-mi)/si)**2+.5*((target-mo)/so)**2
offline=(target-mo)/so
def at_fpr(s):
 order=np.argsort(-s,kind='stable');cuts=np.r_[np.flatnonzero(np.diff(s[order])!=0),len(s)-1]
 tp=np.r_[0,np.cumsum(member[order])[cuts]/member.sum()];fp=np.r_[0,np.cumsum(~member[order])[cuts]/(~member).sum()]
 i=np.flatnonzero(fp<=.01+1e-12);j=i[np.argmax(tp[i])];return float(fp[j]),float(tp[j]),float(np.trapezoid(tp,fp))
print('sklearn',sklearn.__version__,'32 sombras, 12 iteraciones por MLP')
for name,s in [('perdida',target),('online',online),('offline',offline)]:print(name,at_fpr(s))

Fictitious canaries in your own GRU

The local cell trains a character model from scratch on programmatically generated examples, with four explicitly fictitious tokens. It evaluates all 1000 continuations of each prefix at epochs 0, 5, 10, and 20; it calculates exposure, greedily generates three characters, and compares Min-K at 20% against four variants that were not inserted. It also ranks the four generated sequences by their log score divided by their zlib-compressed length. That final score is a heuristic over a tiny list, not a reproduction or estimate of extraction at scale. The comparisons diagnose the corpus created here; they are not membership inference tests on external texts.

Install PyTorch in a local environment. Use GPU if available; the result recorded is from an RTX 3060 and the execution on another platform may vary. The four suffixes and their prefixes are synthetic, shown intentionally and do not have any authentication function.

[ ]Train and measure false canariesLocal GPU
import json, math, zlib, random
import numpy as np, torch
from torch import nn

torch.set_num_threads(1);torch.manual_seed(29);rng=np.random.default_rng(29);random.seed(29)
device='cuda' if torch.cuda.is_available() else 'cpu'
vocab='\n #0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
stoi={s:i for i,s in enumerate(vocab)}
def encode(s):return [stoi[c] for c in s]

# Corpus generado, sin credenciales reales. Todos los tokens se anuncian como falsos.
background=[f'# example {i:03d}\nVALUE_{i%10}={i%37:02d}\n' for i in range(400)]
services=['ALPHA','BRAVO','CHARLIE','DELTA']; secrets=['314','527','806','193']; repetitions=[1,5,20,80]
canaries=[f'FAKE_TOKEN_{service}=demo_{secret}\n' for service,secret in zip(services,secrets)]
corpus=background+sum(([c]*count for c,count in zip(canaries,repetitions)),[])
maxlen=max(map(len,corpus));pad=stoi['\n'];enc=np.full((len(corpus),maxlen),pad,dtype=np.int64)
mask=np.zeros((len(corpus),maxlen-1),dtype=np.float32)
for i,line in enumerate(corpus):
 seq=encode(line);enc[i,:len(seq)]=seq;mask[i,:len(seq)-1]=1
X=torch.tensor(enc[:,:-1],device=device);Y=torch.tensor(enc[:,1:],device=device);M=torch.tensor(mask,device=device)
class CharLM(nn.Module):
 def __init__(self):
  super().__init__();self.embed=nn.Embedding(len(vocab),48);self.rnn=nn.GRU(48,64,batch_first=True);self.head=nn.Linear(64,len(vocab))
 def forward(self,x):
  h,_=self.rnn(self.embed(x));return self.head(h)
model=CharLM().to(device);optim=torch.optim.AdamW(model.parameters(),lr=.003)
def score(texts):
 n=max(map(len,texts));x=np.full((len(texts),n),pad,dtype=np.int64);m=np.zeros((len(texts),n-1),np.float32)
 for i,t in enumerate(texts):x[i,:len(t)]=encode(t);m[i,:len(t)-1]=1
 xx=torch.tensor(x[:,:-1],device=device);yy=torch.tensor(x[:,1:],device=device);mm=torch.tensor(m,device=device)
 with torch.no_grad():
  lp=model(xx).log_softmax(-1).gather(-1,yy[:,:,None]).squeeze(-1)
  sums=(lp*mm).sum(1); mins=torch.sort(torch.where(mm.bool(),lp,torch.inf),dim=1).values
  mink=mins[:,:max(1,int((n-1)*.2))].mean(1)
 return sums.cpu().numpy(),mink.cpu().numpy()
def greedy(prefix,count=3):
 result=prefix
 for _ in range(count):
  with torch.no_grad():z=model(torch.tensor([encode(result)],device=device))[0,-1];result+=vocab[int(z.argmax())]
 return result[len(prefix):]
rows=[]
for epoch in range(0,21):
 if epoch:
  indices=torch.randperm(len(corpus),device=device)
  model.train()
  for batch in indices.split(64):
   logits=model(X[batch]);loss=nn.functional.cross_entropy(logits.reshape(-1,len(vocab)),Y[batch].reshape(-1),reduction='none').reshape(len(batch),-1)
   loss=(loss*M[batch]).sum()/M[batch].sum();optim.zero_grad();loss.backward();optim.step()
 if epoch in (0,5,10,20):
  model.eval();entry={'epoch':epoch,'items':[]}
  for service,secret,reps in zip(services,secrets,repetitions):
   prefix=f'FAKE_TOKEN_{service}=demo_';candidates=[prefix+f'{i:03d}\n' for i in range(1000)]
   ranks=[]
   for start in range(0,1000,100):
    lp,_=score(candidates[start:start+100]);ranks.extend(lp.tolist())
   rank=1+sum(v>ranks[int(secret)] for v in ranks);generated=greedy(prefix)
   entry['items'].append(dict(service=service,repetitions=reps,rank=rank,exposure=math.log2(1000)-math.log2(rank),greedy=generated,match=generated==secret))
  rows.append(entry);print('epoch',epoch,entry['items'],flush=True)

model.eval();members=canaries;nonmembers=[f'FAKE_TOKEN_{s}=demo_{int(secret)^1:03d}\n' for s,secret in zip(services,secrets)]
for label,seqs in [('miembro',members),('no-miembro',nonmembers)]:
 lp,mink=score(seqs)
 for text,a,b in zip(seqs,lp,mink):print('mink',label,text.strip(),round(float(a),3),round(float(b),3),flush=True)
generated=[f'FAKE_TOKEN_{s}=demo_{greedy(f"FAKE_TOKEN_{s}=demo_")}\n' for s in services]
lp,_=score(generated);ordering=sorted(zip(generated,lp),key=lambda t:float(t[1])/max(len(zlib.compress(t[0].encode())),1),reverse=True)
print('ranking_zlib',[(x.strip(),round(float(v)/len(zlib.compress(x.encode())),4)) for x,v in ordering],flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Relate a likelihood ratio with the power of a membership test.
0
Suppose two simple hypotheses with known densities p_in(s) and p_out(s), and a maximum FPR α.

Step 1 of 2. What statistic orders the examples for the most powerful test?

Numeric
A canary occupies rank 3 among 10^9 candidates. Calculate its exposure in bits.
Numeric
A held-out set contains 1000 non-members and 200 members. A threshold produces 10 false positives and 40 true positives. What is the TPR at that threshold?
Quiz
Why can an AUC hide a privacy risk for some examples?
Code
Implement lira_offline_score(target_loss, out_losses). The inputs are -ln(p) losses of the correct class. Convert each loss to p, clip p to [10⁻⁷, 1-10⁻⁷], transform with logit and return (logit target - mean of exclusions shadows) divided by its sample standard deviation, with floor 0.05. Reject negative losses and less than two shadows.
def lira_offline_score(target_loss, out_losses):
  pass
Shift+Enter to run
Code
Implement audit_rates(scores, labels, threshold): labels contains 1 for members and 0 for non-members. Predict member if score≥threshold and return (TPR,FPR). Reject an entry without either of the two classes.
def audit_rates(scores, labels, threshold):
  pass
Shift+Enter to run
Key idea
A privacy audit needs a defined threat, distribution controls, and tail measurements with uncertainty; an aggregated result does not guarantee absence of individual leakage.