Skip to content
Evaluation, safety and interpretability Core 35 min read

Robustness, fairness and privacy

Average accuracy on a held-out set says nothing about three things that decide whether a model can be trusted: what happens when its inputs change, who bears its errors, and what it reveals about the people in its training data. The one idea to walk away with: each of these properties only exists relative to a precise definition (a threat model, a fairness criterion, a privacy guarantee), and the definitions trade off against accuracy and against each other, so "make it robust, fair and private" is a set of choices, not a checklist.

10,000 ft

Classical ML promises good performance on new data from the same distribution as the training data (evaluation and validation). Deployment breaks that promise three ways. The world shifts or an adversary pushes, and the model fails on inputs a human would find trivially similar: robustness. The model's errors fall more heavily on some groups of people than others, often because the data encoded an old injustice: fairness. And the model, which has absorbed its training data into its weights, gives some of it back to anyone who asks the right way: privacy. These were the founding concerns of "trustworthy ML" before the LLM era, and they did not go away: jailbreaks are adversarial examples for text (red-teaming), LLMs reproduce stereotypes, and large models memorise and regurgitate training text. They are also where law bites first (governance): data-protection statutes, anti-discrimination law and lending rules all speak this page's language.

2,000 ft

One model, three failure surfaces, each with its own formal definition and toolkit:

Three ways a model fails beyond average accuracy
Three ways a model fails beyond average accuracy. Trained model, Robustness inputs differ from training, natural shift, adversarial perturbation, poisoning, Fairness errors fall unevenly, group error-rate gaps, biased labels, stereotypes, Privacy the model leaks its data, membership inference, extraction, memorisation, Tools: shift tests, adversarial training, fairness metrics + constraints, DP-SGThree ways a model fails beyond average accuracy. Trained model, Robustness inputs differ from training, natural shift, adversarial perturbation, poisoning, Fairness errors fall unevenly, group error-rate gaps, biased labels, stereotypes, Privacy the model leaks its data, membership inference, extraction, memorisation, Tools: shift tests, adversarial training, fairness metrics + constraints, DP-SG

  1. Robustness: performance under natural distribution shift (new hospitals, new years, new phrasing) and under adversarial perturbation (a worst-case change within a budget). Adversarial examples exist because high-dimensional linear-ish models add up many tiny changes.
  2. Fairness: pick a criterion (equal selection rates, equal error rates, or calibrated scores per group). When base rates differ, the error-rate and calibration criteria are mathematically incompatible, so fairness is a choice of which to honour.
  3. Privacy: models leak membership and sometimes verbatim training data. Differential privacy bounds every such attack at once by making the trained model nearly independent of any one person's record, at a cost in accuracy.
  4. All three are measured by subgroup and worst-case evaluation, not by the average.

Ground level

Part I. Robustness

Distribution shift: the quiet failure

A model is trained on samples from \(p_\text{train}(x, y)\) and deployed on \(p_\text{test}(x, y)\). When they differ, guarantees vanish. The useful split is by which factor changed:

Shift What changes Example
Covariate shift \(p(x)\) changes, \(p(y\mid x)\) does not a skin-lesion classifier trained on one camera, deployed on phone photos
Label (prior) shift \(p(y)\) changes, \(p(x\mid y)\) does not a fraud model trained when 0.1% of transactions were fraud, deployed during an attack wave
Concept drift \(p(y\mid x)\) itself changes what counts as spam, or as a good credit risk after an interest-rate shock

Shift is not exotic. Recht et al. (2019) rebuilt the CIFAR-10 and ImageNet test sets by following the original collection procedures as closely as they could, and found accuracy drops of 3–15% on CIFAR-10 and 11–14% on ImageNet for a broad range of models. Nothing adversarial happened: a new sample of "the same" distribution was enough. Benchmarks such as ImageNet-C (15 kinds of corruption at five severities; Hendrycks and Dietterich, 2019) and WILDS (real-world shifts across hospitals, regions, time and users; Koh et al., 2020) exist to measure this.

The deeper cause is shortcut learning (Geirhos et al., 2020): networks pick up whatever cue predicts the label in training, intended or not. A model recognises cows by the grass they stand on and fails on a cow on a beach; a pneumonia detector trained on X-rays from several hospitals learned to recognise which hospital a scan came from (by a hospital-specific metal token on the image) and used that hospital's pneumonia rate, then failed on scans from new hospitals. This is the same underdetermination as goal misgeneralisation, seen in supervised learning: the training data could not distinguish the intended rule from the shortcut.

LLMs have their own version. Sclar et al. (2023) found that meaning-preserving changes to prompt formatting (separators, spacing, casing) changed few-shot accuracy by up to 76 points for LLaMA-2-13B, and that the best format for one model was a poor guide to the best for another. Report performance across plausible prompt variants, not on one.

Two practical defences follow. Evaluate on the shift you expect: hold out by time, site or source rather than at random (validation and leakage). Keep the model honest about uncertainty: modern networks are often overconfident (Guo et al., 2017), and a one-parameter temperature scaling of the logits on a validation set fixes much of the calibration error, so downstream decisions can use the probabilities.

Adversarial examples

In 2013 Szegedy et al. found that adding a perturbation invisible to humans could make an accurate image classifier output any label they chose. Goodfellow, Shlens and Szegedy (2014) explained why, and the explanation is the single most useful idea in adversarial ML: it is the linearity, in high dimensions.

Take a linear score \(w^\top x\). Change every input coordinate by at most \(\varepsilon\) (an \(L_\infty\) budget). The change that hurts most is \(\delta = -\varepsilon\,\operatorname{sign}(w)\), which moves the score by \(\varepsilon\lVert w\rVert_1\). If \(w\) has \(d\) comparable entries, \(\lVert w\rVert_1 \approx \sqrt d\,\lVert w\rVert_2\): the worst case grows with \(\sqrt d\) while each coordinate's change stays tiny. A random \(\pm\varepsilon\) change moves the score only by about \(\varepsilon\lVert w\rVert_2\), because its terms cancel. The first snippet in Build it shows it with a classifier whose clean accuracy is 97% in every dimension:

input dimension \(d\) clean random \(\pm\tfrac{8}{255}\) worst case (FGSM) \(\tfrac{8}{255}\) score shift \(\varepsilon\lVert w\rVert_1\)
10 0.975 0.975 0.936 0.099
100 0.977 0.981 0.762 0.314
1,000 0.973 0.968 0.024 0.992
3,072 (a 32×32 colour image) 0.974 0.978 0.000 1.739
0.000.250.500.751.001101001,00010,00032×32×3 imagerandom ±8/255 (any d)ε = 8/255 (dots: snippet 1)ε = 4/255ε = 2/255input dimension d (log scale)accuracy
Accuracy of the same linear classifier under the worst-case L∞ perturbation, as the input dimension grows. At the standard CIFAR-10 budget of 8/255 per pixel, a 3,072-dimensional input is always flipped, while random noise of the same size does nothing. Curves are the exact formula Φ((0.5 − ε√d)/0.25); the table above is the simulation.

For a neural network the same logic applies locally. The fast gradient sign method (FGSM) perturbs along the sign of the input gradient of the loss in one step; projected gradient descent (PGD) takes many small steps and projects back into the budget, and is the standard strong first-order attack (Madry et al., 2017). Carlini and Wagner (2016) built optimisation attacks that broke the defences of the day. Attacks transfer between models trained on similar data, so hiding the model does not protect it.

Defences. Most published defences were later broken; Athalye, Carlini and Wagner (2018) showed that many relied on obfuscated gradients, which defeat gradient-based attacks without making the model robust. Two defences have survived scrutiny:

  • Adversarial training (Madry et al.): train on PGD-perturbed inputs, which turns training into a min-max problem (see The maths). It works, at a price: robust models lose clean accuracy and cost several times more to train. Tsipras et al. (2018) showed the trade-off can be inherent, and Ilyas et al. (2019) showed why: standard models rely on non-robust features, patterns that genuinely predict the label in the data but that humans cannot see, so removing reliance on them costs accuracy. "Adversarial examples are not bugs, they are features."
  • Certified defences, which prove no perturbation within a radius changes the output. Randomised smoothing (Cohen, Rosenfeld and Kolter, 2019) classifies by majority vote under Gaussian noise and certifies an \(L_2\) radius; they reported 49% certified top-1 accuracy on ImageNet for perturbations of \(L_2\) norm below 0.5.

RobustBench tracks the state of the art under standardised attacks (AutoAttack), so defence claims can be compared. As of 2026, robust accuracy on CIFAR-10 at \(\varepsilon = 8/255\) remains far below clean accuracy; adversarial robustness for vision is not solved.

Poisoning and backdoors

Attacks can also target training. A poisoning attack inserts crafted examples into the training data; a backdoor is a poison that teaches a trigger ("when you see this patch, or this phrase, output that"). Web-scale data makes this practical. Carlini et al. (2023) showed that an attacker could have poisoned 0.01% of the LAION-400M or COYO-700M image datasets for about USD 60, by buying expired domains that dataset URLs pointed to (split-view poisoning) or by timing edits to Wikipedia before a snapshot (front-running). For language models, Souly et al. (2025) trained models from 600M to 13B parameters and found that about 250 poisoned documents installed a backdoor at every scale, even though the larger models saw over 20 times more clean data: the number of poisons needed stayed roughly constant rather than growing with the dataset. The defences are data provenance (hashes of what you downloaded), filtering, and tests for known trigger behaviours (sleeper agents are the deliberate version).

Part II. Fairness

Where unfairness comes from

Models are rarely unfair because someone wrote a biased rule. They learn it from data and objectives. Suresh and Guttag's framework locates the entry points:

Where bias enters the ML life cycle (after Suresh and Guttag)
Where bias enters the ML life cycle (after Suresh and Guttag). World (historical bias), Measurement proxies, labels, Dataset (representation bias), Training (aggregation bias), Evaluation (benchmark bias), Deployment (use in a new context), decisions change future dataWhere bias enters the ML life cycle (after Suresh and Guttag). World (historical bias), Measurement proxies, labels, Dataset (representation bias), Training (aggregation bias), Evaluation (benchmark bias), Deployment (use in a new context), decisions change future data
  • Historical bias: the world the data records was unjust. A model trained on past lending decisions learns past discrimination even with perfect measurement.
  • Measurement bias: the label is a proxy. "Was re-arrested" stands in for "re-offended", but arrest rates depend on policing.
  • Representation bias: some groups are under-sampled. Buolamwini and Gebru's Gender Shades (2018) audited three commercial gender classifiers on a benchmark balanced by gender and skin type: error rates reached 34.7% for darker-skinned women, against at most 0.8% for lighter-skinned men.
  • Aggregation and evaluation bias: one model for groups whose data behave differently, judged on a benchmark that does not report per-group results.
  • Feedback loops: denied applicants never generate repayment data, so the model never learns it was wrong about them.

Language models inherit all of this from web text. Bolukbasi et al. (2016) showed word embeddings encode analogies like man : computer programmer :: woman : homemaker; benchmarks such as BBQ (Parrish et al., 2021) test whether question-answering models fall back on stereotypes when the context is ambiguous. Which attributes matter is jurisdiction-specific: in India, caste, religion, region and language are as central as gender, and few public benchmarks cover them well.

The criteria

Let \(\hat Y\) be the decision (1 = flagged, for example "will default"), \(Y\) the outcome, \(A\) the group, and \(S\) a score. The three families of group fairness:

Criterion Formal statement Plain meaning
Independence (demographic parity) \(\hat Y \perp A\): \(P(\hat Y=1\mid A=a)\) equal for all \(a\) every group is selected at the same rate
Separation (equalised odds; Hardt, Price and Srebro, 2016) \(\hat Y \perp A \mid Y\): equal false-positive and false-negative rates among people with the same true outcome, the same treatment
Sufficiency (calibration within groups, predictive parity) \(Y \perp A \mid S\): \(P(Y=1\mid S=s, A=a) = s\) for all \(a\) a score means the same thing whoever it is about

Equal opportunity is the half of separation that equalises false-negative rates only. Individual fairness (Dwork et al., 2011) asks instead that similar individuals be treated similarly, which moves all the difficulty into defining "similar".

The impossibility, and why it is arithmetic

In 2016 ProPublica analysed COMPAS, a recidivism risk score used in US courts. Among defendants who did not reoffend, 45% of Black defendants had been labelled higher risk against 23% of white defendants; among those who did reoffend, 48% of white defendants had been labelled low risk against 28% of Black defendants. The vendor replied that the score was calibrated: a given score meant the same reoffence probability for both groups. Both were right. Kleinberg, Mullainathan and Raghavan (2016) and Chouldechova (2017) proved that when base rates differ between groups, no imperfect classifier can be calibrated within groups and have equal false-positive and equal false-negative rates.

Chouldechova's version is one line of algebra on the confusion matrix. With prevalence \(p\) (the base rate) in a group,

\[ \mathrm{FPR} = \frac{p}{1-p}\cdot\frac{1-\mathrm{PPV}}{\mathrm{PPV}}\cdot(1-\mathrm{FNR}). \]

If two groups have equal PPV (predictive parity) and equal FNR but different \(p\), their FPRs must differ. Fairness is a choice about which equality to give up. The second snippet in Build it makes this concrete with a loan-default model whose score is calibrated in both groups, base rates 20% and 40%:

One threshold, 0.50 for everyone0.040.19FPR0.760.46FNR0.610.65PPVPer-group thresholds (A 0.38, B 0.59)0.100.10FPR0.570.62FNR0.510.72PPVgroup A, base rate 0.20group B, base rate 0.40
A calibrated default score, two groups with base rates 0.20 and 0.40. One threshold for everyone (left): creditworthy applicants in group B are wrongly denied almost five times as often (FPR 0.19 vs 0.04). Thresholds chosen per group to equalise FPR at 0.10 (right): now a denial is far more often correct in group B (PPV 0.72 vs 0.51), and the same score gets a different decision depending on group. From the second snippet in Build it.

The picture to keep

Different base rates mean the two groups' score distributions sit in different places. Any single threshold cuts them at different quantiles (unequal error rates); any pair of thresholds that equalises error rates gives the same score different meanings (unequal precision, and disparate treatment). There is no third option unless the classifier is perfect or the base rates are equal.

What practitioners do

  • Measure per group, always. Report selection rate, FPR, FNR and calibration for every group you can identify; a single accuracy number hides all of it. Fairlearn and AIF360 implement the metrics.
  • Choose the criterion from the harm. If a false positive denies someone a loan they would have repaid, equalising FPR protects creditworthy applicants. If the score is shared with decision-makers who must interpret it, calibration matters most. Write the choice down.
  • Interventions: pre-processing (re-weight or repair the data), in-processing (train with a fairness constraint or penalty), post-processing (group-specific thresholds, as in Hardt et al.). Check the law first: group-specific thresholds can be unlawful disparate treatment in some jurisdictions and sectors even when they reduce disparate impact.
  • Do not "fix" fairness by deleting the protected attribute. Other features (postcode, name, spending patterns) proxy for it, and without the attribute you cannot even measure the gap.
  • Document: model cards (Mitchell et al., 2018) and datasheets for datasets (Gebru et al., 2018) record intended use, per-group evaluation and known limitations.

Part III. Privacy

What a model gives away

Training compresses data into weights, and an attacker can sometimes run the compression backwards:

Privacy attacks, from weakest to strongest
Privacy attacks, from weakest to strongest. Membership inference was x in the training set?, Attribute inference infer a hidden field of a known person, Reconstruction rebuild training examples, Extraction the model emits them verbatim, Differential privacy bounds all of them at oncePrivacy attacks, from weakest to strongest. Membership inference was x in the training set?, Attribute inference infer a hidden field of a known person, Reconstruction rebuild training examples, Extraction the model emits them verbatim, Differential privacy bounds all of them at once
  • Membership inference (Shokri et al., 2016): decide whether a given record was in the training set. Models fit their training data better than unseen data, so a low loss on \(x\) is evidence that \(x\) was trained on. Knowing someone was in a hospital's training set can itself be sensitive. Carlini et al.'s LiRA (2021) made the attack rigorous by comparing the loss with its distribution over "shadow" models trained with and without the record, and argued attacks should be judged by their true-positive rate at a low false-positive rate, not by average accuracy.
  • Training-data extraction: Carlini et al. (2020) extracted hundreds of verbatim sequences from GPT-2, including names, phone numbers and email addresses, and found larger models more vulnerable. Memorisation grows log-linearly with model size, with how often an example is duplicated in the data, and with the length of the prompt used to elicit it (Carlini et al., 2022). Nasr et al. (2023) extracted gigabytes of training data from open and closed models, including ChatGPT, with a "divergence attack" (asking the model to repeat a word forever), which made it emit training data 150 times more often than normal use.
  • Anonymisation is not privacy. Narayanan and Shmatikov (2006) re-identified Netflix Prize users from a handful of movie ratings and dates by linking with public IMDb reviews. Removing names does not stop linkage.

The first snippet of Part 3 in Build it shows the simplest attack of all, the differencing attack: two harmless-looking aggregate queries (the mean salary of 1,000 people, and of the same people minus one) reveal one person's exact salary.

Differential privacy

Differential privacy (Dwork, McSherry, Nissim and Smith, 2006) is the one definition that survives all of these, because it is a property of the algorithm, not of the data or the attacker. A randomised algorithm \(M\) is \((\varepsilon,\delta)\)-differentially private if for every pair of datasets \(D, D'\) differing in one person's record, and every set of outcomes \(S\),

\[ P[M(D)\in S] \;\le\; e^{\varepsilon}\,P[M(D')\in S] + \delta . \]

Whatever an attacker does with the output, and whatever else they know, their view barely changes whether or not you are in the data. Small \(\varepsilon\) (around 1) is strong; \(\delta\) should be much smaller than \(1/n\).

  • The Laplace mechanism answers a numeric query \(f\) with \(f(D) + \mathrm{Lap}(\Delta f/\varepsilon)\), where the sensitivity \(\Delta f\) is the most one person can change \(f\). For a mean of \(n\) values capped at \(c\), \(\Delta f = c/n\).
  • Composition: answering \(k\) queries at \(\varepsilon\) each costs at most \(k\varepsilon\) in total (better bounds exist). Privacy is a budget that every release spends.
  • DP-SGD (Abadi et al., 2016) makes training private: clip each example's gradient to norm \(C\), sum, add Gaussian noise of standard deviation \(\sigma C\), step. An accountant converts the noise multiplier \(\sigma\), sampling rate and number of steps into \((\varepsilon,\delta)\). Opacus (PyTorch) implements it.

DP is deployed at scale: the US Census Bureau used it for the 2020 census releases, and Apple and Google use the local variant to collect usage statistics. Its costs are real. Accuracy drops, especially on small datasets, and the drop is not shared equally: Bagdasaryan, Poursaeed and Shmatikov (2019) showed DP-SGD reduces accuracy most on under-represented groups, because clipping and noise erase exactly the rare, high-gradient examples that minority subgroups contribute. Privacy and fairness pull against each other.

Privacy for LLM builders

  • Deduplicate training data. Kandpal, Wallace and Raffel (2022) showed that sequences duplicated many times are regurgitated far more often, and that deduplication sharply reduces extraction (quality filtering and dedup).
  • Scrub personal data before training, and assume what was not scrubbed can come back out.
  • Fine-tuning on customer data is the high-risk step: small datasets, many epochs, rare records. Use DP fine-tuning or keep sensitive data in retrieval, where it can be access-controlled and deleted, rather than in weights, where it cannot (RAG).
  • Machine unlearning (removing a person's influence after training) is an active research area; for large models no efficient method gives guarantees as strong as retraining without the data. This matters because data-protection law gives people a right to erasure.
  • Federated learning (McMahan et al., 2016) keeps raw data on devices, but model updates still leak information; it needs secure aggregation and DP to give a guarantee.

History

Three literatures that met

Fairness has legal roots older than ML: US disparate-impact doctrine dates from the 1971 Griggs v. Duke Power decision. In ML, Dwork et al.'s Fairness Through Awareness (2011) started the formal study; 2016 was the turning point, with ProPublica's COMPAS analysis, Hardt et al.'s equalised odds and the impossibility theorems of Kleinberg et al. and Chouldechova; Gender Shades (2018) and the model-card and datasheet proposals made auditing practice. Privacy: Sweeney showed in the late 1990s that ZIP code, birth date and sex identify most Americans; the Netflix re-identification followed in 2006, the same year differential privacy was defined. DP-SGD (2016), membership inference (2016) and extraction from GPT-2 (2020) brought it to deep learning. Robustness: adversarial examples (2013), the linearity explanation and FGSM (2014), the break-everything era (Carlini and Wagner 2016, Athalye et al. 2018), PGD adversarial training (2017), randomised smoothing (2019), and since 2023 the transfer of the whole field to language models as jailbreaks and data poisoning.

First principles

Each property is a statement about a counterfactual, not about the test set. Robustness asks what the model would do on inputs it was not tested on; fairness asks how errors would be distributed across people; privacy asks what the output would look like without one person. A held-out accuracy number answers none of these, which is why each needed its own definition.

Each definition must name an adversary or a norm. "Robust" is meaningless until you say robust to what: which shift, which perturbation set, which budget. "Fair" is meaningless until you say which equality. "Private" is meaningless until you say against what attacker, or adopt DP, which quantifies over all attackers at once. Most disputes in these fields are definitions being talked past each other (COMPAS is the textbook case).

Each costs something, for a structural reason. Robustness costs accuracy because standard models exploit genuinely predictive non-robust features. Fairness criteria cost each other because of the confusion-matrix identity whenever base rates differ. Privacy costs accuracy because a model that cannot depend much on any one record cannot learn rare patterns, which are also often the patterns of minority groups. None of these trade-offs is an engineering failure to be optimised away; they are arithmetic.

And they interact. DP worsens subgroup accuracy (privacy against fairness). Adversarial training can widen accuracy gaps between classes. Removing a protected attribute for privacy makes fairness unmeasurable. Good practice decides these jointly, per use case.

The maths

FGSM and the linear argument. For loss \(L(\theta, x, y)\), the fast gradient sign method takes

\[ x' = x + \varepsilon\,\operatorname{sign}\!\big(\nabla_x L(\theta, x, y)\big), \]

the maximiser of the first-order change \(\nabla_x L^\top\delta\) over \(\lVert\delta\rVert_\infty\le\varepsilon\), with value \(\varepsilon\lVert\nabla_x L\rVert_1\). For a linear score \(w^\top x\) this is exact: the score moves by \(\varepsilon\lVert w\rVert_1\). For a random sign vector \(r\), \(w^\top(\varepsilon r)\) has mean 0 and standard deviation \(\varepsilon\lVert w\rVert_2\). When \(w\)'s entries are comparable, \(\lVert w\rVert_1/\lVert w\rVert_2\approx\sqrt d\); for \(w = \mathbf 1/\sqrt d\) it is exactly \(\sqrt d\), so at \(d = 3{,}072\) the worst case is 55 times the typical random effect.

PGD and adversarial training. PGD iterates \(x^{t+1} = \Pi_{\mathcal B_\varepsilon(x)}\big(x^t + \alpha\,\operatorname{sign}(\nabla_x L(\theta,x^t,y))\big)\), projecting back into the \(\varepsilon\)-ball. Adversarial training solves the saddle-point problem

\[ \min_\theta\; \mathbb E_{(x,y)}\Big[\max_{\lVert\delta\rVert\le\varepsilon} L(\theta,\,x+\delta,\,y)\Big], \]

with PGD approximating the inner maximum at each step (Madry et al., 2017). By Danskin's theorem, the gradient of the inner max with respect to \(\theta\) is the gradient at the maximiser, which justifies training on the attacked inputs.

Randomised smoothing's certificate. Define \(g(x) = \arg\max_c P(f(x+\eta) = c)\) with \(\eta\sim\mathcal N(0,\sigma^2 I)\). If the top class has probability at least \(\underline{p_A}\) and every other at most \(\overline{p_B}\), then \(g\) is constant within the \(L_2\) ball of radius

\[ R = \frac{\sigma}{2}\Big(\Phi^{-1}(\underline{p_A}) - \Phi^{-1}(\overline{p_B})\Big), \]

which is \(\sigma\,\Phi^{-1}(\underline{p_A})\) when \(\overline{p_B} = 1-\underline{p_A}\). With \(\sigma = 0.5\) and \(\underline{p_A} = 0.99\), \(R = 0.5\times2.326 = 1.16\). In practice \(\underline{p_A}\) is a lower confidence bound from Monte Carlo samples, so the certificate holds with high probability.

Derivation: Chouldechova's identity

In a group of \(N\) people with prevalence \(p\), the confusion-matrix counts are

\[ \mathrm{TP} = Np(1-\mathrm{FNR}),\qquad \mathrm{FP} = N(1-p)\,\mathrm{FPR}. \]

Precision is \(\mathrm{PPV} = \mathrm{TP}/(\mathrm{TP}+\mathrm{FP})\), so \(\mathrm{FP} = \mathrm{TP}\,(1-\mathrm{PPV})/\mathrm{PPV}\). Substituting,

\[ N(1-p)\,\mathrm{FPR} = Np(1-\mathrm{FNR})\frac{1-\mathrm{PPV}}{\mathrm{PPV}} \;\Longrightarrow\; \mathrm{FPR} = \frac{p}{1-p}\cdot\frac{1-\mathrm{PPV}}{\mathrm{PPV}}\cdot(1-\mathrm{FNR}). \]

Fix PPV and FNR equal across groups; then FPR is proportional to the odds \(p/(1-p)\), which differ whenever base rates differ. Kleinberg et al. prove the stronger, score-based version: calibration within groups plus balance of the average score among positives and among negatives forces either equal base rates or perfect prediction.

Why the Laplace mechanism is \(\varepsilon\)-DP. For neighbouring \(D, D'\), the output densities at any \(z\) are proportional to \(e^{-\varepsilon|z-f(D)|/\Delta}\) and \(e^{-\varepsilon|z-f(D')|/\Delta}\). Their ratio is \(e^{\varepsilon(|z-f(D')|-|z-f(D)|)/\Delta}\le e^{\varepsilon|f(D)-f(D')|/\Delta}\le e^{\varepsilon}\) by the triangle inequality and the definition of sensitivity. Integrating over any set \(S\) gives the definition with \(\delta = 0\).

What DP means for membership inference. Treat membership inference as a hypothesis test between "\(x\in D\)" and "\(x\notin D\)". For any test against an \((\varepsilon,\delta)\)-DP mechanism,

\[ \mathrm{TPR} \;\le\; e^{\varepsilon}\,\mathrm{FPR} + \delta . \]

At \(\varepsilon = 1\) and a false-positive rate of 1%, no attack can reach a true-positive rate above 2.7% (plus \(\delta\)). This is the cleanest way to read an \(\varepsilon\): it caps how much more often an attacker can correctly accuse you than wrongly accuse a stranger.

DP-SGD. For a mini-batch \(B\) with per-example gradients \(g_i\),

\[ \tilde g = \frac{1}{|B|}\Big(\sum_{i\in B} g_i\big/\max\!\big(1, \lVert g_i\rVert_2/C\big) \;+\; \mathcal N(0,\sigma^2C^2 I)\Big). \]

Clipping bounds each person's influence on the sum to \(C\) (the sensitivity); the Gaussian noise masks it. Sampling each batch at random amplifies privacy, and an accountant composes the per-step guarantees over training.

Build it

1. Adversarial examples from linearity in high dimensions (NumPy):

import numpy as np
rng = np.random.default_rng(0)

# Two classes, y = ±1. Each input has d "pixels": x = y * mu + noise, noise std 0.25 per pixel.
# The signal is spread evenly over all pixels so clean accuracy is the same (~97.7%) for every d.
def experiment(d, eps, n=2000, attack="fgsm"):
    w = np.ones(d) / np.sqrt(d)                    # the (optimal) linear classifier, unit norm
    mu = 0.5 * w                                   # projection of the class mean on w is 0.5
    y = rng.choice([-1, 1], n)
    X = y[:, None] * mu + 0.25 * rng.standard_normal((n, d))
    if attack == "fgsm":                           # worst case in the L-inf ball: -eps*y*sign(w)
        X = X - eps * y[:, None] * np.sign(w)
    elif attack == "random":                       # same size, random signs
        X = X + eps * rng.choice([-1, 1], (n, d))
    return np.mean(np.sign(X @ w) == y)

eps = 8 / 255                                      # the standard CIFAR-10 budget, ~0.031 per pixel
print("    d   clean   random ±eps   FGSM eps   margin shift eps*||w||_1")
for d in [10, 100, 1000, 3072]:
    print(f"{d:5d}   {experiment(d, 0):.3f}      {experiment(d, eps, attack='random'):.3f}"
          f"       {experiment(d, eps):.3f}        {eps*np.sqrt(d):.3f}")
    d   clean   random ±eps   FGSM eps   margin shift eps*||w||_1
   10   0.975      0.975       0.936        0.099
  100   0.977      0.981       0.762        0.314
 1000   0.973      0.968       0.024        0.992
 3072   0.974      0.978       0.000        1.739

2. The fairness impossibility on a calibrated credit score (NumPy):

import numpy as np
rng = np.random.default_rng(0)

# A loan-default model. Two groups with different base rates of default (y = 1).
# The score s is calibrated in both groups by construction: P(default | s) = s.
def group(n, base_rate, k=4.0):
    s = rng.beta(k * base_rate, k * (1 - base_rate), n)   # scores with mean = base rate
    y = rng.random(n) < s                                  # outcomes drawn from the score
    return s, y

def report(name, s, y, t):
    flag = s >= t                                          # flagged as "will default": deny
    fpr = np.mean(flag[~y]); fnr = np.mean(~flag[y]); ppv = np.mean(y[flag])
    print(f"  {name}: base {y.mean():.2f}  threshold {t:.2f}  deny {flag.mean():.2f}  "
          f"FPR {fpr:.2f}  FNR {fnr:.2f}  PPV {ppv:.2f}")
    return fpr, fnr, ppv

A = group(50_000, 0.20); B = group(50_000, 0.40)
for lo, hi in [(0.1, 0.2), (0.4, 0.5)]:                    # calibration check, both groups
    print(f"P(default | s in [{lo},{hi})):  A {A[1][(A[0]>=lo)&(A[0]<hi)].mean():.3f}"
          f"  B {B[1][(B[0]>=lo)&(B[0]<hi)].mean():.3f}")

print("Policy 1: one threshold for everyone")
report("A", *A, 0.5); report("B", *B, 0.5)

print("Policy 2: group thresholds chosen to equalise FPR at 0.10")
tA = np.quantile(A[0][~A[1]], 0.90); tB = np.quantile(B[0][~B[1]], 0.90)
fA, nA, pA = report("A", *A, tA); fB, nB, pB = report("B", *B, tB)

# Chouldechova's identity: FPR = p/(1-p) * (1-PPV)/PPV * (1-FNR) holds exactly in each group
for name, (s, y), f, n_, p_ in [("A", A, fA, nA, pA), ("B", B, fB, nB, pB)]:
    p = y.mean()
    print(f"  identity check {name}: FPR {f:.4f} vs p/(1-p)*(1-PPV)/PPV*(1-FNR) = {p/(1-p)*(1-p_)/p_*(1-n_):.4f}")
P(default | s in [0.1,0.2)):  A 0.146  B 0.153
P(default | s in [0.4,0.5)):  A 0.432  B 0.445
Policy 1: one threshold for everyone
  A: base 0.20  threshold 0.50  deny 0.08  FPR 0.04  FNR 0.76  PPV 0.61
  B: base 0.40  threshold 0.50  deny 0.33  FPR 0.19  FNR 0.46  PPV 0.65
Policy 2: group thresholds chosen to equalise FPR at 0.10
  A: base 0.20  threshold 0.38  deny 0.16  FPR 0.10  FNR 0.57  PPV 0.51
  B: base 0.40  threshold 0.59  deny 0.21  FPR 0.10  FNR 0.62  PPV 0.72
  identity check A: FPR 0.1000 vs p/(1-p)*(1-PPV)/PPV*(1-FNR) = 0.1000
  identity check B: FPR 0.1000 vs p/(1-p)*(1-PPV)/PPV*(1-FNR) = 0.1000

The score is calibrated in both groups (first two lines), yet under one threshold a creditworthy applicant in group B is denied almost five times as often as one in group A. Equalising that error rate requires a group-dependent threshold: an applicant with score 0.45 is denied in group A and approved in group B.

3. Differencing, the Laplace mechanism, and membership inference against DP-SGD (NumPy):

import numpy as np
rng = np.random.default_rng(0)

# --- Part 1: a differencing attack, and the Laplace mechanism that stops it ---
income = rng.lognormal(13, 0.6, 1000).clip(0, 5e6)       # 1,000 salaries in rupees, capped at 50 lakh
mean_all, mean_wo = income.mean(), income[1:].mean()      # two "harmless" aggregate queries
print(f"person 0 earns {income[0]:,.0f}; recovered from two means: {1000*mean_all - 999*mean_wo:,.0f}")
sens = 5e6 / 1000                                         # one person moves the mean by at most cap/n
for eps in [0.1, 1.0]:
    noisy = lambda m: m + rng.laplace(0, sens / eps)      # Laplace mechanism, scale = sensitivity/eps
    guess = 1000 * noisy(mean_all) - 999 * noisy(mean_wo)
    print(f"eps={eps:>4}: noise scale {sens/eps:,.0f} on the mean; differencing now gives {guess:,.0f}")

# --- Part 2: membership inference against logistic regression, with and without DP-SGD ---
d, n = 200, 100                                           # more features than people: memorisation
w_true = rng.standard_normal(d) / np.sqrt(d)
def data(m):
    X = rng.standard_normal((m, d)); y = (rng.random(m) < 1/(1+np.exp(-3 * X @ w_true))).astype(float)
    return X, y
Xin, yin = data(n); Xout, yout = data(n)                  # members (training set) and non-members
loss = lambda w, X, y: np.logaddexp(0, X @ w) - y * (X @ w)

def train(dp=False, sigma=1.0, C=1.0, epochs=300, lr=0.5, batch=50):
    w = np.zeros(d)
    for _ in range(epochs):
        for idx in np.split(rng.permutation(n), n // batch):
            g = (1/(1+np.exp(-Xin[idx] @ w)) - yin[idx])[:, None] * Xin[idx]   # per-example grads
            if dp:
                g = g / np.maximum(1, np.linalg.norm(g, axis=1, keepdims=True) / C)  # clip each to C
                g = g.sum(0) + rng.normal(0, sigma * C, d)                        # add noise
                w -= lr * g / batch
            else:
                w -= lr * g.mean(0)
    return w

def auc(a, b):                                            # P(member loss < non-member loss)
    return np.mean(a[:, None] < b[None, :]) + 0.5 * np.mean(a[:, None] == b[None, :])

Xt, yt = data(5000)
for sigma in [0, 2, 4, 8, 16]:
    w = train() if sigma == 0 else train(dp=True, sigma=sigma, epochs=30)
    acc = np.mean((Xt @ w > 0) == yt)
    print(f"noise sigma {sigma:2d}: train acc {np.mean((Xin @ w > 0) == yin):.2f}  test acc {acc:.3f}"
          f"  membership-inference AUC {auc(loss(w, Xin, yin), loss(w, Xout, yout)):.3f}")
person 0 earns 477,079; recovered from two means: 477,079
eps= 0.1: noise scale 50,000 on the mean; differencing now gives 66,982,811
eps= 1.0: noise scale 5,000 on the mean; differencing now gives 5,795,003
noise sigma  0: train acc 1.00  test acc 0.608  membership-inference AUC 0.844
noise sigma  2: train acc 0.91  test acc 0.569  membership-inference AUC 0.770
noise sigma  4: train acc 0.86  test acc 0.570  membership-inference AUC 0.657
noise sigma  8: train acc 0.65  test acc 0.523  membership-inference AUC 0.564
noise sigma 16: train acc 0.62  test acc 0.500  membership-inference AUC 0.576

Read the second half as a trade-off curve. The non-private model memorises its 100 training people perfectly (train accuracy 1.00) and a simple loss-threshold attack identifies members with AUC 0.84. Adding DP-SGD noise pushes the attack towards chance (0.5; with 100 members and 100 non-members, differences of a few hundredths are noise) and costs test accuracy: on a dataset this small, privacy is expensive. With a million examples the same noise costs far less, because each person's clipped gradient is a smaller share of the sum. The snippet reports \(\sigma\), not \(\varepsilon\): converting to a formal guarantee needs a privacy accountant (Opacus has one).

Things to try

  • In snippet 1, replace w = ones/√d with a sparse \(w\) (signal in 10 pixels only). How does the FGSM effect change with \(d\) now? Why does sparsity help robustness here?
  • In snippet 2, set both base rates to 0.3. Show that one threshold now satisfies calibration, equal FPR and equal FNR at once.
  • In snippet 2, find thresholds that equalise selection rates (demographic parity) and report FPR, FNR and PPV. Which applicants pay for that equality?
  • In snippet 3, increase n to 2,000 and rerun the noise sweep. How much does the accuracy cost of \(\sigma = 4\) shrink?
  • In snippet 3, implement a LiRA-style attack: train 16 shadow models with and without a target record and compare its loss with both distributions. How much stronger is it than the global threshold?

In practice

  • Robustness: build a shift test set before launch (new time period, new sources, new phrasing, typos, other languages) and track the gap to the in-distribution score. For LLM features, evaluate several prompt formats. Calibrate probabilities with temperature scaling, and route low-confidence cases to humans.
  • Fairness: decide the groups and criterion with domain and legal experts before modelling; report per-group metrics with confidence intervals (small groups have wide ones); re-audit after deployment, because feedback loops move the numbers. In credit, insurance and hiring, sector regulators already expect this (governance).
  • Privacy: minimise what you collect, deduplicate and scrub before training, prefer retrieval over fine-tuning for personal data, use DP for any model trained on sensitive records that will be shared, and test with membership-inference and extraction attacks as part of red-teaming.
  • Write it down: a model card with intended use, per-group results, robustness results and the privacy treatment of the data. In regulated domains this is becoming mandatory documentation.

In Jarvis

A planning assistant handles exactly the data this page warns about: salaries, holdings, family members' ages. The design choice that matters most is architectural: user data lives in the planning engine and is retrieved per request under access control, rather than being trained into any model's weights, so there is nothing to extract and erasure is a database delete. See the Jarvis case study.

Common misconceptions

\"Adversarial examples are a quirk of neural networks' non-linearity.\"

The opposite: Goodfellow et al.'s point is that they arise from linear behaviour in high dimensions. A plain logistic regression on images is just as vulnerable (snippet 1).

\"Remove the protected attribute and the model is fair.\"

Correlated features reconstruct it, and without it you cannot measure disparities. "Fairness through unawareness" fails every formal criterion in general.

\"A calibrated score is fair.\"

Calibration is one criterion (sufficiency). With different base rates it guarantees unequal error rates. Whether that is acceptable depends on who bears the errors.

\"Anonymised data is private.\"

Re-identification by linkage is routine (Netflix, and Sweeney's ZIP code, birth date and sex). Only a guarantee about the algorithm, such as differential privacy, survives an attacker with side information.

\"An ε of 10 is still differential privacy, so it is fine.\"

Formally yes; practically the bound \(\mathrm{TPR}\le e^{10}\mathrm{FPR}\) is vacuous. Always ask what \(\varepsilon\) was used and what an attack achieves against the released model.

Check yourself

Why does a perturbation of 8/255 per pixel flip a linear classifier on 3,072-dimensional inputs but not on 10-dimensional ones?

The worst-case score change is \(\varepsilon\lVert w\rVert_1\), which for comparable weights grows like \(\varepsilon\sqrt d\lVert w\rVert_2\): 0.099 at \(d = 10\) but 1.739 at \(d = 3{,}072\), larger than the 0.5 margin. Random perturbations only move the score by about \(\varepsilon\lVert w\rVert_2\), so they do nothing in either case.

Distinguish covariate shift, label shift and concept drift, with an example of each from lending.

Covariate: applicants' features change (a new customer segment), but default given features does not. Label: the overall default rate rises (a recession), with the profile of defaulters per class unchanged. Concept: the relationship itself changes (a new government scheme makes previously risky borrowers safe).

State Chouldechova's identity and use it to explain the COMPAS dispute.

\(\mathrm{FPR} = \frac{p}{1-p}\cdot\frac{1-\mathrm{PPV}}{\mathrm{PPV}}\cdot(1-\mathrm{FNR})\). COMPAS had similar PPV across groups (the vendor's calibration argument) but the groups' recorded reoffence base rates differed, so FPRs had to differ (ProPublica's argument). Both described the same arithmetic.

Why does differential privacy protect against attacks that had not been invented when the guarantee was proved?

Because it bounds how much the output distribution can change when one person's record changes, for any output event. Any attack is a function of the output, so post-processing cannot increase the privacy loss. The guarantee is about the algorithm, not about a particular attacker.

At ε = 1, what is the highest true-positive rate a membership-inference attack can achieve at a 0.1% false-positive rate (δ = 0)?

\(\mathrm{TPR}\le e^{1}\times0.001\approx0.27\%\). The attacker can be at most 2.7 times more likely to flag a true member than a non-member.

Why did Souly et al.'s poisoning result surprise people, and what does it imply for data pipelines?

The intuition was that poisoning needs a fixed fraction of the data, so larger datasets dilute an attacker. They found a roughly constant number (about 250 documents) sufficed across 600M to 13B parameters. As datasets grow, a fixed-size attack becomes a smaller fraction and harder to find, so provenance and filtering matter more, not less.

Hard: why does DP-SGD hurt minority subgroups more than the majority?

Examples from under-represented groups are rare and, because the model fits them poorly, have large gradients. Clipping caps exactly those gradients, and the noise, which is the same for all examples, swamps the small total signal those few examples contribute. The model therefore learns the majority pattern and little else.

Hard: a lender equalises false-positive rates across groups with group-specific thresholds. List two costs and one legal risk.

Precision diverges (a denial means something different per group, per the identity), and overall accuracy or profit usually falls. Applicants with identical scores receive different decisions, which can be unlawful disparate treatment in some jurisdictions or sectors even if intended to reduce disparate impact.

Go deeper

Papers

Videos and lectures

Articles and tutorials

Courses and books

Code

  • Opacus — DP-SGD for PyTorch, with a privacy accountant.
  • Fairlearn and AIF360 — Fairness metrics and mitigation algorithms.
  • RobustBench and WILDS — Standard benchmarks for adversarial robustness and real-world distribution shift.

Where this leads