Attacks on Models
Membership inference, extraction and prompt injection.
A trained model is a compressed, queryable copy of its training data, and a language model is also an interpreter that follows instructions found anywhere in its context. Attackers exploit both: they test whether your record was used, coax out memorized text, copy the model through its API, or slip instructions into the documents it reads. This lesson formalizes each attack, shows how to measure it honestly, and asks what defenses, from differential privacy to machine unlearning, actually guarantee.
What you’ll learn
- Formalize membership inference as a hypothesis test, implement the likelihood-ratio attack (LiRA), and evaluate attacks by their true-positive rate at low false-positive rates.
- Prove that -DP bounds every membership attack, and turn measured attacks into lower bounds on .
- Define memorization and extraction, and derive how a logit API reveals a model's hidden dimension and output layer.
- Analyze prompt injection as a failure to separate instructions from data, and evaluate the defenses and machine unlearning.
Membership inference, done right
Simple membership-inference attacks threshold a per-example statistic, such as the loss (Yeom et al., 2018), whose advantage is tied to the generalization gap; shadow models (Shokri et al., 2017) learn a classifier on the outputs of models trained on data the attacker controls. The best test thresholds a likelihood ratio (the Neyman–Pearson lemma; Evaluating Language Models). The catch is that the two distributions differ from example to example: an atypical example has high loss whether or not it was trained on, and a typical one has low loss either way, so a single global threshold confuses "hard" with "unseen".
LiRA (Carlini et al., 2022) estimates both distributions per example. Train shadow models on random halves of a population dataset, so each candidate is IN for about half of them and OUT for the rest. Record each model's logit-scaled confidence on the true label, , which is close to Gaussian; fit and ; and score the target model's by the likelihood ratio. An offline variant uses only OUT models and a one-sided test, so no shadow model has to be trained on the target.
import numpy as np
from scipy.stats import norm
def logit_conf(p_true): # model's probability of the true label
p = np.clip(p_true, 1e-12, 1 - 1e-12)
return np.log(p) - np.log(1 - p)
def lira_online(phi_target, phi_in, phi_out):
"""phi_in / phi_out: logit confidences on z from shadow models trained with / without z."""
mu_in, sd_in = phi_in.mean(), phi_in.std() + 1e-8
mu_out, sd_out = phi_out.mean(), phi_out.std() + 1e-8
return norm.logpdf(phi_target, mu_in, sd_in) - norm.logpdf(phi_target, mu_out, sd_out)
def lira_offline(phi_target, phi_out): # one-sided test with OUT models only
return norm.logcdf(phi_target, phi_out.mean(), phi_out.std() + 1e-8)Higher scores mean "member". Thresholding the score at different levels traces the attack's ROC curve, best plotted on log–log axes.
Average accuracy and AUC are the wrong yardsticks. An attack with AUC near 0.5 overall can still identify a few members with near certainty, which is a real breach for those people. Carlini et al. therefore report TPR at fixed low FPR, such as 0.1% or 0.001%. There LiRA was about ten times more powerful than earlier attacks, and the most exposed examples were outliers and atypical points. Large language-model pretraining is a different regime: careful evaluations find membership inference near chance for typical pretraining documents (Evaluating Language Models), even though extraction, below, shows that memorization is real.
Which result is the strongest evidence that a model leaks membership?
- The attack's overall accuracy is 60%
- The attack's AUC is 0.65
- TPR of 50% at an FPR of 40%
- TPR of 2% at an FPR of 0.001%
Show the answer
D. TPR of 2% at an FPR of 0.001%
At an FPR of , a 2% TPR is 2,000 times better than chance at confidently picking out members: some individuals are exposed almost with certainty. The other results describe weak average-case signals that could not single anyone out reliably.
Differential privacy as a ceiling, audits as a floor
Fix and the rest of the data, and fold the attack's randomness into the set of trained models on which it answers "member". The DP inequality on , from to , and on its complement in the other direction, gives the two bounds:
Accuracy is largest where both constraints are tight. With that corner is and , which is exactly randomized response's success rate:
At and , an attack with FPR 0.1% has TPR at most 0.27%. At , a value often reported for DP-SGD, and the bound is vacuous for every FPR above about . Yet attacks on models trained at usually come nowhere near this ceiling: the guarantee covers worst-case datasets and an adversary who sees every intermediate step.
Read backwards, the bound turns any measured attack into a lower bound on the privacy actually provided: , with confidence intervals on both rates from many trials. This is privacy auditing (Jagielski, Ullman & Oprea, 2020). Nasr et al. (2021) showed that DP-SGD's analysis is tight against an adversary who inserts crafted gradients and sees every intermediate model, while an adversary who sees only the final model achieves far less; whether the analysis is loose for realistic threat models or attacks are weak is still open. Steinke, Nasr & Jagielski (2023) audit with a single training run by inserting many canaries at once, cheap enough to run routinely, and audits have exposed implementation bugs that voided claimed guarantees.
An audit of a DP training pipeline measures TPR = 5% at FPR = 0.5%, with tight confidence intervals and negligible . What lower bound on does it establish?
Show the answer
2.3
. If the pipeline claims , the audit proves the claim false, whether through a bug in the implementation or in the accounting.
Memorization, extraction and stealing
Two measures make memorization precise. The exposure of an inserted random secret, a canary such as a fake phone number, is , where the rank orders all possible secrets by model likelihood (Carlini et al., 2019): exposure near means the model singles the canary out. A training string is -extractable if some -token prefix , with in the training data, makes greedy decoding produce (Carlini et al., 2023).
Carlini et al. (2021) extracted hundreds of verbatim sequences from GPT-2, including names, phone numbers, email addresses, code and 128-bit UUIDs, by generating many samples and ranking them by perplexity relative to zlib compression or to a smaller model. Across model families, the extractable fraction grew log-linearly with model size, with the number of times a string was duplicated, and with the length of the prompt (Carlini et al., 2023); a sequence present 10 times was generated about 1,000 times more often than one present once, and deduplicating training data reduced it (Kandpal, Wallace & Raffel, 2022). Asking a production chat model to repeat one word forever made it diverge into emitting training data: more than 10,000 unique memorized examples for about $200 of queries (Nasr et al., 2023). Diffusion models regenerate near-copies of some training images, mostly heavily duplicated ones (Carlini et al., 2023).
The consequence is a three-way tension. Differential privacy limits how much any single example can matter, so private training must lose accuracy on the tail, and that loss falls on rare classes and small groups first: DP-SGD reduced accuracy most for underrepresented subgroups (Bagdasaryan, Poursaeed & Shmatikov, 2019), a conflict with the goals of Bias & Fairness.
Model inversion works at the level of classes. Gradient ascent on the input to maximize a face-recognition model's confidence for a person's name reconstructed images in which people could identify that person (Fredrikson, Jha & Ristenpart, 2015), and a warfarin-dosing model plus demographics revealed patients' genetic markers (Fredrikson et al., 2014). Inversion recovers what is typical of a class; when the class is one person, that is a breach. Differential privacy does not prevent it when the attribute is predictable from the population, because DP protects participation, not population-level inference.
A logistic-regression API that returns probabilities leaks a linear equation per query; queries at affinely independent points determine the model exactly (Tramèr et al., 2016):
A language model's logits are with output matrix and hidden size far below the vocabulary size . Stack logit vectors as columns:
So the singular values of collapse to numerical zero after the -th, revealing the hidden size, and the top left singular vectors span the column space of , which determines up to an invertible transformation:
Carlini et al. (2024) ran this attack on a production API, reconstructing full logit vectors from its log-probabilities and logit-bias option. For under $20 they recovered the output projection matrices of two OpenAI models, ada and babbage (hidden sizes 1024 and 2048), and they determined, without publishing it, the hidden size of gpt-3.5-turbo. The API was changed in response.
Prompt injection and unlearning
An application built on a language model places trusted instructions (the system prompt, the user's request) and untrusted data (retrieved pages, emails, tool outputs) in one token sequence, and the model has no reliable way to tell which tokens carry authority. In direct prompt injection a user overrides the system prompt, hijacking the task or leaking the prompt (Perez & Ribeiro, 2022). In indirect injection (Greshake et al., 2023) an attacker plants instructions in content the application will read: a web page telling a browsing assistant to send the conversation to an attacker's URL, or an email telling an email agent to forward the inbox. The analogy with SQL injection is exact except for the remedy: databases keep code and data apart with parameterized queries, but a language model interprets every token.
Jailbreaks are the same weakness approached by users. Safety training fails through competing objectives and mismatched generalization (Wei, Haghtalab & Steinhardt, 2023), and automatically found adversarial suffixes transfer across models (Zou et al., 2023; Adversarial Examples & Robustness).
| Defense | Idea | Guarantee | Limitation |
|---|---|---|---|
| Instruction hierarchy (Wallace et al., 2024) | train the model to rank system over user over tool-provided instructions | none formal; lowers attack success | adaptive attackers find phrasings that still work |
| Spotlighting (Hines et al., 2024) | mark or encode untrusted text so the model can tell it apart | none formal | the model may still follow marked instructions |
| Detection classifiers | flag text that looks like an injected instruction | none formal | evaded by paraphrase, encodings and other languages |
| Least privilege and confirmation | restrict an agent's tools; ask a person before consequential actions | bounds the damage | costs autonomy and convenience |
| Isolation by design (CaMeL; Debenedetti et al., 2025) | a privileged model plans from the trusted request only; a quarantined model reads untrusted data but cannot act; data flows are checked against policies | injected text cannot change the plan's control flow | lower utility; does not stop attacks that work through data values themselves |
Retraining from scratch is exact and expensive. SISA training (Bourtoule et al., 2021) splits the data into disjoint shards, trains a model on each in isolation and aggregates their predictions, checkpointing each shard's training in slices. Deleting a point retrains only its shard, from the checkpoint before the slice that contained it: about times cheaper than full retraining, and on average roughly half that again thanks to slicing, at some cost in accuracy as shards shrink. For convex models, one Newton step on the remaining data plus calibrated noise gives certified approximate removal (Guo et al., 2020).
For large language models, approximate methods such as gradient ascent on the data to forget are evaluated on benchmarks such as TOFU (Maini et al., 2024) and WMDP (Li et al., 2024). Studies have found that "unlearned" knowledge can often be recovered with light fine-tuning or adversarial prompts: suppressing an output is not removing a dependence. Legal rights to erasure, such as Article 17 of the EU's GDPR, keep the problem pressing.
Key takeaways
- Membership inference is a per-example hypothesis test: LiRA fits IN and OUT Gaussians to logit-scaled confidences from shadow models, and attacks must be judged by TPR at low FPR.
- -DP caps every membership attack (, and accuracy at most when ); read backwards, measured attacks give lower bounds on .
- Models memorize, especially duplicated and atypical data: extraction recovers verbatim training text, and fitting the long tail can be necessary for accuracy, so the cost of DP falls on rare groups first.
- Logit APIs leak architecture: the logits lie in an -dimensional subspace, so an SVD reveals the hidden size and the output layer up to an invertible linear map.
- Prompt injection exploits the missing boundary between instructions and data, and robust defenses are architectural; unlearning is exact only by retraining (SISA makes that cheaper), and approximate methods often merely suppress.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why do current evaluations of membership inference report the true-positive rate at a very low false-positive rate instead of accuracy or AUC?
- Because low-FPR numbers are always larger
- Because accuracy cannot be computed for membership inference
- Because a breach means confidently identifying some individuals, which average-case metrics can hide
- Because AUC is undefined for imbalanced data
Show the answer
C. Because a breach means confidently identifying some individuals, which average-case metrics can hide
An attack can be near chance on average yet nearly certain about a few outliers. TPR at FPR of 0.1% or less measures exactly that ability to make confident, mostly correct claims about individuals.
A model is trained with -differential privacy. An attack wrongly flags 5% of non-members. What is the most it can catch of the members?
- 5%
- 10%
- 67%
- 100%
Show the answer
B. 10%
. The same model's best balanced accuracy is .
A prediction API serves a logistic-regression model on features and returns the predicted probability. How many well-chosen queries suffice to recover its parameters exactly?
- It is impossible without the training data
Show the answer
A.
Each answer gives one linear equation, , in unknowns; queries at affinely independent points determine and .
Why is filtering inputs for phrases such as "ignore previous instructions" an inadequate defense against prompt injection?
- Because such filters are too slow to run
- Because injected instructions can be phrased in unlimited ways, and the model treats every token in its context as potential instructions; no syntactic boundary separates data from commands
- Because language models cannot read retrieved documents
- Because injection only works on small models
Show the answer
B. Because injected instructions can be phrased in unlimited ways, and the model treats every token in its context as potential instructions; no syntactic boundary separates data from commands
Paraphrases, other languages, encodings and indirect requests all carry the same intent, and the model interprets them as readily as the filtered phrase. Robust defenses therefore limit what injected text can do (isolation, least privilege, confirmation) instead of trying to recognize it.
Further reading
- R. Shokri, M. Stronati, C. Song & V. Shmatikov, "Membership inference attacks against machine learning models," IEEE Symposium on Security and Privacy (2017).
- N. Carlini, S. Chien, M. Nasr, S. Song, A. Terzis & F. Tramèr, "Membership inference attacks from first principles," IEEE Symposium on Security and Privacy (2022).
- N. Carlini et al., "Extracting training data from large language models," USENIX Security (2021).
- K. Greshake, S. Abdelnabi, S. Mishra, C. Endres, T. Holz & M. Fritz, "Not what you've signed up for: Compromising real-world LLM-integrated applications with indirect prompt injection," ACM AISec (2023).
- M. Rigaki & S. Garcia, "A survey of privacy attacks in machine learning," ACM Computing Surveys (2023).