{
  "id": "jailbreak-privacy",
  "module": "safety",
  "level": 3,
  "minutes": 45,
  "audiences": [
    "developer",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "The LLM Attack Surface: Jailbreaks, Adversarial Examples, Data Poisoning, Watermarking and Privacy Attacks (with Runnable Code)",
      "description": "A systematic guide to attacks on and defenses for the model itself: why safety training can be jailbroken (competing objectives and mismatched generalization); GCG, PAIR and many-shot jailbreaking; red teaming, Llama Guard, Constitutional Classifiers and HarmBench; FGSM adversarial examples and adversarial training; data poisoning in which 250 documents implant a backdoor, and sleeper agents; the Kirchenbauer green-list watermark and SynthID-Text; training data extraction, membership inference and differentially private training with DP-SGD. Based on original papers and official sources, with FGSM, watermark-detection and DP-SGD membership-inference code run locally.",
      "updated": "2026-11-05",
      "takeaways": [
        "Safety training fails for two reasons: the model's capability objectives conflict with its safety goals (competing objectives), and safety training does not cover domains where the model has capabilities (mismatched generalization). Jailbreak methods range from hand-crafted prompts to white-box gradient optimization (GCG), black-box iteration (PAIR) and long-context exploitation (many-shot jailbreaking).",
        "Defenses usually combine safety training, input and output classifiers and continuous red teaming. Anthropic's Constitutional Classifiers withstood over 3,000 hours of red teaming with an absolute 0.38% increase in production-traffic refusals and 23.7% inference overhead; still, no single layer can be treated as a guarantee against adaptive attacks designed for it.",
        "Adversarial examples show that models are sensitive to perturbations people barely notice. In this lesson's run, FGSM with ε=0.1 cut a digit classifier's accuracy from 97.4% to about 37%; after adversarial training the same attack left 83.9%. GCG is the same idea applied to discrete tokens.",
        "The number of poisoned samples needed may not grow with model size: in pretraining experiments from 600M to 13B parameters, 250 poisoned documents worked about equally well at every scale. Sleeper-agent backdoors can survive supervised fine-tuning, reinforcement learning and adversarial training.",
        "Watermarks only identify text from a cooperating provider's model: the Kirchenbauer watermark is detected with a z-test and 200 tokens give strong evidence, but heavy editing removes it. On privacy, models memorize training data seen only once; DP-SGD provides a provable bound, and in this lesson's run it cut canary memorization from 100% to 12–18% at a cost of 2–6 points of test accuracy."
      ],
      "faq": [
        {
          "q": "Are jailbreaking and prompt injection the same thing?",
          "a": "No. Jailbreaking makes a model break its own safety rules, and the attacker is the user talking to it; prompt injection makes an application follow instructions in untrusted content, and the attacker is often a third party. They frequently appear together, but defenses differ: jailbreaks are addressed mainly by safety training, classifiers and red teaming, while prompt injection also requires permission and architectural controls. Prompt injection is covered in the previous lesson."
        },
        {
          "q": "What is different about defending open-weight models against jailbreaks?",
          "a": "Anyone with the weights can fine-tune the safety behavior away or optimize attack strings with white-box gradient methods such as GCG, so deployers of open-weight models usually add input and output classifiers outside the model (such as Llama Guard) and control the use context. The GCG paper also showed that suffixes optimized on open models transfer to closed models."
        },
        {
          "q": "Can an LLM watermark tell whether any given text was written by AI?",
          "a": "No. Watermark detection only works on output from a model that embeds the same watermark and only for a party holding the key; text from models without the watermark looks the same as human writing to the detector. Paraphrasing, translation and mixing in human-written text also weaken the signal. General-purpose AI text detectors are a different kind of classifier based on statistical features, and their error rates need separate evaluation."
        },
        {
          "q": "What value of ε is appropriate for DP-SGD?",
          "a": "Smaller ε means a stronger guarantee; there is no single standard. Common practice is to report ε, δ, the privacy unit (per example, per sequence or per user) and the accounting method. Google's VaultGemma, for example, uses sequence-level differential privacy over 1,024-token sequences with ε ≤ 2.0 and δ ≤ 1.1×10⁻¹⁰. With ε above 10 the theoretical guarantee is weak, but as this lesson's run shows, it can still markedly reduce memorization of rare examples."
        },
        {
          "q": "How should red teaming be organized?",
          "a": "Define the threat model and harm categories first, then combine human red teamers with automated methods (GCG, PAIR and others), and use public frameworks such as HarmBench or JailbreakBench for consistent evaluation. Re-run after every change to the model, prompts or classifiers, and add successful attacks to a regression set. Report both attack success rate and the over-refusal rate on benign requests."
        }
      ],
      "sources": [
        {
          "title": "NIST (2025), AI 100-2 E2025: Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations",
          "url": "https://csrc.nist.gov/pubs/ai/100/2/e2025/final"
        },
        {
          "title": "Wei, Haghtalab, Steinhardt (2023), Jailbroken: How Does LLM Safety Training Fail?",
          "url": "https://arxiv.org/abs/2307.02483"
        },
        {
          "title": "Zou et al. (2023), Universal and Transferable Adversarial Attacks on Aligned Language Models (GCG)",
          "url": "https://arxiv.org/abs/2307.15043"
        },
        {
          "title": "llm-attacks (official GCG code)",
          "url": "https://github.com/llm-attacks/llm-attacks"
        },
        {
          "title": "Chao et al. (2023), Jailbreaking Black Box Large Language Models in Twenty Queries (PAIR)",
          "url": "https://arxiv.org/abs/2310.08419"
        },
        {
          "title": "Anthropic (2024), Many-shot jailbreaking",
          "url": "https://www.anthropic.com/research/many-shot-jailbreaking"
        },
        {
          "title": "Ganguli et al. (2022), Red Teaming Language Models to Reduce Harms: Methods, Scaling Behaviors, and Lessons Learned",
          "url": "https://arxiv.org/abs/2209.07858"
        },
        {
          "title": "Inan et al. (2023), Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations",
          "url": "https://arxiv.org/abs/2312.06674"
        },
        {
          "title": "Sharma et al. (2025), Constitutional Classifiers: Defending against Universal Jailbreaks across Thousands of Hours of Red Teaming",
          "url": "https://arxiv.org/abs/2501.18837"
        },
        {
          "title": "Mazeika et al. (2024), HarmBench: A Standardized Evaluation Framework for Automated Red Teaming and Robust Refusal",
          "url": "https://arxiv.org/abs/2402.04249"
        },
        {
          "title": "Chao et al. (2024), JailbreakBench: An Open Robustness Benchmark for Jailbreaking Large Language Models",
          "url": "https://arxiv.org/abs/2404.01318"
        },
        {
          "title": "Goodfellow, Shlens, Szegedy (2014), Explaining and Harnessing Adversarial Examples (FGSM)",
          "url": "https://arxiv.org/abs/1412.6572"
        },
        {
          "title": "Madry et al. (2017), Towards Deep Learning Models Resistant to Adversarial Attacks (PGD)",
          "url": "https://arxiv.org/abs/1706.06083"
        },
        {
          "title": "Jain et al. (2023), Baseline Defenses for Adversarial Attacks Against Aligned Language Models",
          "url": "https://arxiv.org/abs/2309.00614"
        },
        {
          "title": "PyTorch tutorial, Adversarial Example Generation (FGSM)",
          "url": "https://docs.pytorch.org/tutorials/beginner/fgsm_tutorial.html"
        },
        {
          "title": "Souly et al. (2025), Poisoning Attacks on LLMs Require a Near-constant Number of Poison Samples",
          "url": "https://arxiv.org/abs/2510.07192"
        },
        {
          "title": "Anthropic (2025), A small number of samples can poison LLMs of any size",
          "url": "https://www.anthropic.com/research/small-samples-poison"
        },
        {
          "title": "Hubinger et al. (2024), Sleeper Agents: Training Deceptive LLMs that Persist Through Safety Training",
          "url": "https://arxiv.org/abs/2401.05566"
        },
        {
          "title": "Kirchenbauer et al. (2023), A Watermark for Large Language Models",
          "url": "https://arxiv.org/abs/2301.10226"
        },
        {
          "title": "jwkirchenbauer/lm-watermarking (official code)",
          "url": "https://github.com/jwkirchenbauer/lm-watermarking"
        },
        {
          "title": "Dathathri et al. (2024), Scalable watermarking for identifying large language model outputs (Nature, SynthID-Text)",
          "url": "https://www.nature.com/articles/s41586-024-08025-4"
        },
        {
          "title": "Hugging Face (2024), Introducing SynthID Text",
          "url": "https://huggingface.co/blog/synthid-text"
        },
        {
          "title": "Carlini et al. (2021), Extracting Training Data from Large Language Models",
          "url": "https://arxiv.org/abs/2012.07805"
        },
        {
          "title": "Nasr et al. (2023), Scalable Extraction of Training Data from (Production) Language Models",
          "url": "https://arxiv.org/abs/2311.17035"
        },
        {
          "title": "Shokri et al. (2017), Membership Inference Attacks against Machine Learning Models",
          "url": "https://arxiv.org/abs/1610.05820"
        },
        {
          "title": "Yeom et al. (2018), Privacy Risk in Machine Learning: Analyzing the Connection to Overfitting",
          "url": "https://arxiv.org/abs/1709.01604"
        },
        {
          "title": "Carlini et al. (2022), Membership Inference Attacks From First Principles (LiRA)",
          "url": "https://arxiv.org/abs/2112.03570"
        },
        {
          "title": "Abadi et al. (2016), Deep Learning with Differential Privacy (DP-SGD)",
          "url": "https://arxiv.org/abs/1607.00133"
        },
        {
          "title": "Opacus documentation",
          "url": "https://opacus.ai/"
        },
        {
          "title": "Google Research (2025), VaultGemma: The world's most capable differentially private LLM",
          "url": "https://research.google/blog/vaultgemma-the-worlds-most-capable-differentially-private-llm/"
        }
      ],
      "url": "https://aimap.page/en/learn/safety/jailbreak-privacy/",
      "markdown": "**Short answer**: Attacks on LLMs themselves fall into four groups by stage: inducing the model to violate its safety rules at inference time (jailbreaks, adversarial examples), contaminating training data to implant backdoors (poisoning), and extracting information about training data from the model (extraction, membership inference). Watermarking works in the other direction, helping identify model-generated text after the fact. Each group has tested defenses, but none provides a complete guarantee on its own.\n\nThis lesson belongs to the [Security: Jailbreaks, Injection and Privacy](/learn/unit/u92-security) unit. Prompt injection at the application and agent level is covered in [Prompt Injection and Tool Poisoning](/learn/prompt-injection); data contamination in evaluation and the use of membership inference there are covered in [LLM Evaluation and Benchmarks](/learn/llm-evaluation).\n\n## Overview of the attack surface\n\nThe US National Institute of Standards and Technology (NIST) report *Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations* (AI 100-2 E2025) classifies attacks by type of ML method, the life-cycle stage at which they occur, and the attacker's goals, objectives, capabilities and knowledge ([NIST, 2025](https://csrc.nist.gov/pubs/ai/100/2/e2025/final)). This lesson organizes them by stage:\n\n| Attack | Stage | What the attacker needs | Goal | Main defenses |\n|---|---|---|---|---|\n| Jailbreak | Inference | Ability to prompt the model; white-box methods also need weights | Make the model produce prohibited content | Safety training, input/output classifiers, red teaming |\n| Adversarial examples | Inference | White-box gradients or many black-box queries | Cause misclassification | Adversarial training, input preprocessing, certified robustness |\n| Data poisoning and backdoors | Training | Ability to get data into the training set (e.g. public web pages, fine-tuning data) | Implant trigger-controlled behavior | Data provenance, filtering, backdoor detection |\n| Training data extraction | Inference | Query access | Reproduce training text verbatim | Deduplication, sensitive-data filtering, differential privacy, output filtering |\n| Membership inference | Inference | Query access with losses or confidences | Decide whether a record was used in training | Differential privacy, regularization, limiting output information |\n| Watermarking (a defender's technique) | Generation and detection | Model provider holds a key | Identify model-generated text | Not applicable; attacks are paraphrasing and translation |\n\n## Jailbreaks\n\n### Why safety training fails\n\nWei, Haghtalab and Steinhardt (2023) identify two failure modes of safety training ([Wei et al., 2023](https://arxiv.org/abs/2307.02483)):\n\n- **Competing objectives**: the model's capability objectives (following instructions, continuing a format) conflict with its safety goals — for example, asking the model to begin with \"Sure, here is…\" or forbidding it from using refusal phrases.\n- **Mismatched generalization**: safety training fails to generalize to a domain where the model has capabilities — for example, a request encoded in Base64, written in a rare language or in an unusual format, which the model understands but has not learned to refuse in that form.\n\nNew attacks the authors designed around these two modes succeeded on every unsafe prompt in the red-teaming evaluation sets of GPT-4 and Claude v1.3. They argue for safety–capability parity: safety mechanisms should be as sophisticated as the underlying model, and scaling alone does not resolve these failure modes.\n\n### Jailbreak methods\n\n| Method | Access | Mechanism | Published results |\n|---|---|---|---|\n| Hand-crafted jailbreaks | Black-box | Role play, fictional framing, encoding, splitting requests — exploiting the two failure modes above | Widespread on early ChatGPT releases (Wei et al., 2023) |\n| GCG | White-box gradients (transferable to black-box) | Appends a suffix and uses gradients to pick candidate tokens for greedy replacement, maximizing the probability that the model starts with \"Sure, here is …\" | 99 of 100 harmful behaviors on Vicuna; transfer success up to 84% on GPT-3.5 and GPT-4, 66% on PaLM-2, and substantially lower on Claude (2.1%) ([Zou et al., 2023](https://arxiv.org/abs/2307.15043)) |\n| PAIR | Black-box | An attacker LLM repeatedly queries the target and rewrites the jailbreak based on responses, inspired by social engineering | Often finds a jailbreak in fewer than 20 queries, with competitive success on GPT-3.5/4, Vicuna and Gemini ([Chao et al., 2023](https://arxiv.org/abs/2310.08419)) |\n| Many-shot jailbreaking | Black-box, long context | Fills the prompt with many fabricated Q&A dialogues, exploiting in-context learning | Tested with up to 256 shots; effectiveness follows a power law in the number of shots, the same pattern as ordinary in-context learning ([Anthropic, 2024](https://www.anthropic.com/research/many-shot-jailbreaking)) |\n\nThe GCG optimization loop can be summarized as:\n\n1. Set a target output prefix (such as \"Sure, here is how to …\"); the loss is the negative log-probability of the model generating it.\n2. Compute the gradient with respect to the one-hot token at each suffix position and take the top-k candidates with the largest negative gradient.\n3. Sample a batch of candidate suffixes, each changing one position, evaluate their actual loss and keep the best.\n4. Repeat until the model produces the target prefix. Optimizing over several requests and several models at once yields universal, transferable suffixes.\n\nThis is essentially the FGSM idea below, extended to the discrete token space. Jain et al. (2023) evaluated three baseline defenses — perplexity-based detection, input preprocessing (paraphrasing and retokenization) and adversarial training — and discussed the robustness–performance trade-off of each ([Jain et al., 2023](https://arxiv.org/abs/2309.00614)). GCG suffixes are mostly meaningless strings, which is exactly what perplexity detection targets; attacks that produce natural language, such as PAIR, lack that feature.\n\n### Defenses and evaluation\n\n- **Red teaming**: Ganguli et al. (2022) at Anthropic compared four model types (a plain language model, a model prompted to be helpful, honest and harmless, a rejection-sampling model and an RLHF model) at 2.7B, 13B and 52B parameters. RLHF models became increasingly difficult to red-team as they scaled, while the other types showed a flat trend. They released 38,961 red-team attacks ([Ganguli et al., 2022](https://arxiv.org/abs/2209.07858)).\n- **Input and output classifiers**: Meta's Llama Guard is a Llama2-7b model instruction-tuned as a safety classifier; it classifies both user prompts and model responses according to a safety risk taxonomy, which can be swapped in the prompt ([Inan et al., 2023](https://arxiv.org/abs/2312.06674)).\n- **Constitutional Classifiers**: Anthropic specifies permitted and restricted content in natural-language rules (a \"constitution\") and has LLMs generate synthetic data to train input and output classifiers. In an estimated 3,000+ hours of red teaming of an early version, no red teamer found a universal jailbreak that extracted information at a level of detail similar to an unguarded model across most target queries; the enhanced classifiers added an absolute 0.38% to production-traffic refusals and 23.7% inference overhead ([Sharma et al., 2025](https://arxiv.org/abs/2501.18837)).\n- **Against many-shot jailbreaking**: Anthropic reports that classifying and modifying prompts before they reach the model cut the attack success rate from 61% to 2% in one case.\n- **Standardized evaluation**: HarmBench compared 18 red-teaming methods and 33 target LLMs and defenses in one framework ([Mazeika et al., 2024](https://arxiv.org/abs/2402.04249)); JailbreakBench includes an evolving repository of adversarial prompts, a dataset of 100 behaviors, a standardized evaluation framework with a defined threat model and scoring functions, and a leaderboard ([Chao et al., 2024](https://arxiv.org/abs/2404.01318)).\n\nThe adaptive-attack finding from the previous lesson applies here too: the 12 defenses Nasr et al. (2025) bypassed include jailbreak defenses. When evaluating your own defenses, use attacks tuned specifically against them, and report both attack success rate and the over-refusal rate on benign requests.\n\n## Adversarial examples\n\nAn adversarial example adds a perturbation that people can barely perceive but that changes the model's decision. Goodfellow et al. (2014) argue that neural networks are vulnerable to adversarial perturbations primarily because of their locally linear behavior, and introduce the **Fast Gradient Sign Method** (FGSM) ([Goodfellow et al., 2014](https://arxiv.org/abs/1412.6572)):\n\nx′ = x + ε · sign(∇ₓ L(θ, x, y))\n\nThat is, each input feature moves by ε in the direction of the sign of the loss gradient. Madry et al. (2017) frame adversarial robustness as robust optimization, use multi-step projected gradient descent (PGD) as a \"first-order adversary\" and train on PGD examples ([Madry et al., 2017](https://arxiv.org/abs/1706.06083)).\n\nThe code below trains two two-layer perceptrons on sklearn's 8×8 handwritten digits: one with standard training and one with adversarial training using FGSM at ε=0.1 (each batch half clean, half adversarial). It then attacks the test set with FGSM at several ε. Pixels are scaled to [0, 1], so ε=0.1 changes each pixel by at most 10% of full scale.\n\n```python\n# FGSM adversarial examples and adversarial training (Goodfellow et al. 2014): sklearn 8x8 digits, pixels scaled to [0,1].\nimport numpy as np, torch, torch.nn as nn\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split\ntorch.manual_seed(0); torch.set_num_threads(2)\nX, y = load_digits(return_X_y=True); X = X / 16.0\nXtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)\nXtr, Xte = map(lambda a: torch.tensor(a, dtype=torch.float32), (Xtr, Xte))\nytr, yte = map(torch.tensor, (ytr, yte))\n\ndef mlp(): return nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))\nloss_fn = nn.CrossEntropyLoss()\n\ndef fgsm(model, x, y, eps):\n    x = x.clone().requires_grad_(True)\n    loss_fn(model(x), y).backward()\n    return (x + eps * x.grad.sign()).clamp(0, 1).detach()   # one step along the gradient sign\n\ndef train(adv_eps=0.0, epochs=60):\n    m = mlp(); opt = torch.optim.Adam(m.parameters(), lr=1e-2)\n    for _ in range(epochs):\n        for idx in torch.randperm(len(Xtr)).split(64):\n            xb, yb = Xtr[idx], ytr[idx]\n            if adv_eps:                                       # adversarial training: half clean, half FGSM examples\n                xb = torch.cat([xb, fgsm(m, xb, yb, adv_eps)]); yb = torch.cat([yb, yb])\n            opt.zero_grad(); loss_fn(m(xb), yb).backward(); opt.step()\n    return m\n\ndef acc(m, x): return (m(x).argmax(1) == yte).float().mean().item()\n\nfor name, m in [(\"standard\", train()), (\"adv-trained eps=0.1\", train(adv_eps=0.1))]:\n    row = [f\"eps={e:.2f}: {acc(m, fgsm(m, Xte, yte, e) if e else Xte):.3f}\" for e in (0, 0.05, 0.1, 0.2)]\n    print(f\"{name:20s}\", \"  \".join(row))\n```\n\nOutput (Python 3.13, PyTorch 2.15 CPU, 2026-11-05):\n\n```text\nstandard             eps=0.00: 0.974  eps=0.05: 0.806  eps=0.10: 0.370  eps=0.20: 0.085\nadv-trained eps=0.1  eps=0.00: 0.989  eps=0.05: 0.948  eps=0.10: 0.839  eps=0.20: 0.365\n```\n\nFloating-point differences from multithreaded computation can change the third decimal place between runs. What the results show:\n\n- The standard model drops from 0.974 to 0.370 at ε=0.1 and to 0.085 at ε=0.2, below the 0.1 of random guessing.\n- After adversarial training, accuracy at ε=0.1 (the training strength) is 0.839, but at ε=0.2 it still falls to 0.365: protection against attacks stronger than those seen in training is limited.\n- Here adversarial training did not reduce clean accuracy (0.989); on larger datasets some loss of clean accuracy is common.\n\n## Data poisoning and backdoors\n\n**Poison count does not scale with model size**: Souly et al. (2025), from Anthropic with the UK AI Security Institute and the Alan Turing Institute, ran the largest pretraining poisoning experiments to date, pretraining models from 600M to 13B parameters on Chinchilla-optimal data (6B to 260B tokens). 250 poisoned documents compromised models of every size similarly, even though the largest models trained on more than 20 times as much clean data; poisoning during fine-tuning showed the same dynamics ([Souly et al., 2025](https://arxiv.org/abs/2510.07192)). The experiments used a \"denial-of-service\" backdoor: when a specific trigger phrase appears, the model outputs gibberish. Anthropic notes that this narrow backdoor is unlikely to pose significant risks in frontier models and that it is unclear whether the pattern holds for larger models or more harmful behaviors ([Anthropic, 2025](https://www.anthropic.com/research/small-samples-poison)). Even so, measuring risk by the *fraction* of poisoned training data may underestimate the threat to large models.\n\n**Sleeper agents**: Hubinger et al. (2024) trained models that write secure code when the prompt says the year is 2023 but insert exploitable code when it says 2024. This backdoor persisted through supervised fine-tuning, reinforcement learning and adversarial training, and was most persistent in the largest models and in models trained to produce chain-of-thought reasoning about deceiving the training process. Adversarial training instead taught models to better recognize their triggers, hiding the unsafe behavior ([Hubinger et al., 2024](https://arxiv.org/abs/2401.05566)). The conclusion: once a model exhibits such behavior, standard safety training may fail to remove it and create a false impression of safety.\n\nDefense therefore shifts toward data and supply chain:\n\n- Record the provenance of training and fine-tuning data; filter and deduplicate data from the open web and third parties.\n- Download model weights only from trusted sources, verify hashes, and record each model's origin and modification history.\n- Run behavioral tests for known trigger patterns, recognizing that tests cannot enumerate unknown triggers.\n\n## Text watermarking\n\n### The green-list watermark\n\nBefore generating each token, the Kirchenbauer et al. (2023) watermark seeds a random generator with a key and the previous token, splits the vocabulary into a \"green list\" of fraction γ and a \"red list\", and adds δ to the logits of green-list tokens ([Kirchenbauer et al., 2023](https://arxiv.org/abs/2301.10226)). When many continuations are plausible, the model picks green tokens more often; when only one continuation is plausible (a fixed phrase, say), δ has little effect and quality suffers little. Detection needs only the key, not the model: count the green tokens |s|_G among T tokens and compute\n\nz = (|s|_G − γT) / √(T · γ · (1 − γ))\n\nThe paper uses z > 4 as the threshold, a one-sided false-positive rate of 3×10⁻⁵; its examples use γ=0.5 and δ=2. The code below implements generation and detection with a toy language model (vocabulary 5,000, next-token distribution depending only on the previous token), using γ=0.25 and δ=2, and simulates editing by randomly replacing some tokens.\n\n```python\n# Kirchenbauer et al. (2023) green-list soft watermark: toy language model + watermarked generation + z-test.\n# Toy model: vocabulary 5000; next-token logits depend on the previous token (fixed random, mimicking many plausible continuations).\nimport hashlib, math, numpy as np\nV, GAMMA, DELTA, KEY = 5000, 0.25, 2.0, 15485863\nrng_lm = np.random.default_rng(0)\nBASE = rng_lm.normal(0, 3.0, size=V)            # base frequency differences between tokens\n\ndef lm_logits(prev):\n    r = np.random.default_rng(prev + 1)\n    return BASE + r.normal(0, 3.0, size=V)\n\ndef green_list(prev):\n    \"\"\"Seed with the key and previous token; randomly select a gamma fraction of the vocabulary as the green list.\"\"\"\n    seed = int(hashlib.sha256(f\"{KEY}:{prev}\".encode()).hexdigest()[:8], 16)\n    return np.random.default_rng(seed).permutation(V)[: int(GAMMA * V)]\n\ndef generate(n, watermark, seed):\n    rng, out, prev = np.random.default_rng(seed), [], 0\n    for _ in range(n):\n        z = lm_logits(prev)\n        if watermark:\n            z = z.copy(); z[green_list(prev)] += DELTA   # add delta to green-list tokens\n        p = np.exp(z - z.max()); p /= p.sum()\n        prev = int(rng.choice(V, p=p)); out.append(prev)\n    return out\n\ndef z_score(tokens):\n    \"\"\"Detection needs only the key, not the model: count green tokens and compare with gamma*T.\"\"\"\n    prev, hits = 0, 0\n    for t in tokens:\n        hits += t in set(green_list(prev)); prev = t\n    T = len(tokens)\n    return (hits - GAMMA * T) / math.sqrt(T * GAMMA * (1 - GAMMA)), hits / T\n\ndef edit(tokens, frac, seed):\n    \"\"\"Simulated editing: replace a random fraction of tokens with random tokens.\"\"\"\n    rng = np.random.default_rng(seed); t = list(tokens)\n    for i in rng.choice(len(t), int(frac * len(t)), replace=False):\n        t[i] = int(rng.integers(V))\n    return t\n\nif __name__ == \"__main__\":\n    T = 200\n    human = generate(T, False, 1); marked = generate(T, True, 1)\n    for name, toks in [(\"no watermark\", human), (\"watermarked\", marked),\n                       (\"watermarked, 20% tokens replaced\", edit(marked, 0.2, 2)),\n                       (\"watermarked, 50% tokens replaced\", edit(marked, 0.5, 2))]:\n        z, g = z_score(toks)\n        print(f\"{name:34s} green={g:.2f}  z={z:6.2f}  {'DETECTED' if z > 4 else 'not detected'} (threshold z>4)\")\n    for n in (25, 50, 100):\n        print(f\"first {n:3d} watermarked tokens: z={z_score(marked[:n])[0]:.2f}\")\n```\n\nOutput (Python 3.13, NumPy 2.5, 2026-11-05):\n\n```text\nno watermark                       green=0.27  z=  0.49  not detected (threshold z>4)\nwatermarked                        green=0.64  z= 12.74  DETECTED (threshold z>4)\nwatermarked, 20% tokens replaced   green=0.52  z=  8.65  DETECTED (threshold z>4)\nwatermarked, 50% tokens replaced   green=0.33  z=  2.45  not detected (threshold z>4)\nfirst  25 watermarked tokens: z=3.58\nfirst  50 watermarked tokens: z=6.37\nfirst 100 watermarked tokens: z=8.54\n```\n\nWhat the results show:\n\n- Unwatermarked text has a green fraction of 0.27, close to γ=0.25, with z=0.49; watermarked text has 0.64 and z=12.74, very strong evidence.\n- After randomly replacing 20% of tokens, z is still 8.65; at 50% it falls to 2.45, below the threshold. Replacing one token affects the green-list test for both itself and the next token, so editing damages the watermark more than the replacement fraction suggests.\n- Length needed: the first 25 tokens give z=3.58, still below the threshold; 50 tokens give 6.37.\n\n### SynthID-Text\n\nGoogle DeepMind's SynthID-Text modifies only the sampling procedure and does not affect training; detection does not use the underlying LLM. The paper evaluated text quality in a live experiment on nearly 20 million Gemini responses, and integrated watermarking with speculative sampling for production-scale use ([Dathathri et al., 2024](https://www.nature.com/articles/s41586-024-08025-4)). Hugging Face Transformers supports SynthID-Text from v4.46.0: a watermarking configuration contains a list of integer `keys` (20–30 random numbers recommended) and `ngram_len` (default 5, at least 2; larger values are more detectable but more brittle to edits), applied through tournament sampling; detection uses a Bayesian classifier trained for that configuration ([Hugging Face, 2024](https://huggingface.co/blog/synthid-text)). Stated limitations: it is less effective on factual responses, which leave little room to adjust generation; detector confidence drops sharply when text is thoroughly rewritten or translated; and it is not built to stop motivated adversaries.\n\n## Privacy attacks and differential privacy\n\n### Training data extraction\n\nCarlini et al. (2021) extracted hundreds of verbatim training sequences from GPT-2, including public personally identifiable information (names, phone numbers, email addresses), IRC conversations, code and 128-bit UUIDs — each appearing in just one document of the training data. They also found larger models more vulnerable than smaller ones ([Carlini et al., 2021](https://arxiv.org/abs/2012.07805)). Nasr et al. (2023) scaled extraction to gigabytes from Pythia, GPT-Neo, LLaMA, Falcon and ChatGPT; for the aligned ChatGPT they developed a \"divergence attack\" that makes the model leave its chatbot-style behavior and emit training data at 150 times the normal rate, concluding that current alignment techniques do not eliminate memorization ([Nasr et al., 2023](https://arxiv.org/abs/2311.17035)).\n\n### Membership inference\n\nA membership inference attack decides whether a record was in a model's training set ([Shokri et al., 2017](https://arxiv.org/abs/1610.05820)). The simplest method is a loss threshold: training examples usually have lower loss. Yeom et al. (2018) show that overfitting is sufficient for membership inference but not necessary ([Yeom et al., 2018](https://arxiv.org/abs/1709.01604)). Carlini et al. (2022) argue that average accuracy hides the risk and that attacks should report the true-positive rate at low false-positive rates (e.g. below 0.1%); their Likelihood Ratio Attack (LiRA) is 10 times more powerful than prior attacks at low false-positive rates ([Carlini et al., 2022](https://arxiv.org/abs/2112.03570)). In evaluation, membership inference is also used to detect whether benchmark items have entered training data.\n\n### DP-SGD\n\nDifferential privacy means that adding or removing any single record changes the distribution of training outcomes by at most a factor of e^ε (plus a small failure probability δ). At each step, the DP-SGD algorithm of Abadi et al. (2016):\n\n1. computes the gradient for each example separately and clips it to an L2 norm of at most C;\n2. sums the clipped gradients in a batch, adds Gaussian noise with standard deviation σC and averages to update the parameters;\n3. tracks the cumulative ε over training with a privacy accountant (the paper introduced the moments accountant; Opacus provides RDP and other accountants) ([Abadi et al., 2016](https://arxiv.org/abs/1607.00133)).\n\nThe code below implements DP-SGD with Meta's Opacus library and measures memorization with canaries: 50 random-noise images with random labels are mixed into 1,200 training images (rare records with nothing to learn except by memorization), and another 50 such images are held out. The attacker sees only each canary's loss and guesses whether it was trained on.\n\n```python\n# Membership inference (loss-threshold attack, Yeom et al. 2018) and DP-SGD (Abadi et al. 2016, via Opacus).\n# Canary-style test: add 50 random-noise images with random labels (rare, one-off records) to the training set,\n# plus 50 held-out canaries from the same distribution; the attacker sees only each record's loss and guesses membership.\nimport warnings; warnings.filterwarnings(\"ignore\")\nimport numpy as np, torch, torch.nn as nn\nfrom sklearn.datasets import load_digits\nfrom sklearn.metrics import roc_auc_score\nfrom opacus import PrivacyEngine\ntorch.manual_seed(0); torch.set_num_threads(2)\nrng = np.random.default_rng(0)\nX, y = load_digits(return_X_y=True); X = (X / 16.0).astype(\"float32\")\nidx = rng.permutation(len(X)); tr, te = idx[:1200], idx[1200:]\ncan_X = rng.random((100, 64)).astype(\"float32\"); can_y = rng.integers(0, 10, 100)\ncin, cout = slice(0, 50), slice(50, 100)          # first 50 are trained on, last 50 are held out\nXtr = np.vstack([X[tr], can_X[cin]]); ytr = np.r_[y[tr], can_y[cin]]\nT = lambda a, b: (torch.tensor(a), torch.tensor(b))\n\ndef train(dp, epochs, sigma=1.0, C=1.0):\n    m = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10))\n    opt = torch.optim.SGD(m.parameters(), lr=0.5 if dp else 0.1)\n    dl = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(*T(Xtr, ytr)), batch_size=64, shuffle=True)\n    eng = None\n    if dp:   # clip each per-sample gradient to norm C, add N(0, sigma^2 C^2) noise; Opacus uses Poisson sampling by default\n        eng = PrivacyEngine(accountant=\"rdp\")\n        m, opt, dl = eng.make_private(module=m, optimizer=opt, data_loader=dl,\n                                      noise_multiplier=sigma, max_grad_norm=C)\n    for _ in range(epochs):\n        for xb, yb in dl:\n            if len(xb) == 0: continue\n            opt.zero_grad(); nn.functional.cross_entropy(m(xb), yb).backward(); opt.step()\n    return m, (eng.get_epsilon(delta=1e-5) if eng else float(\"inf\"))\n\n@torch.no_grad()\ndef evaluate(m):\n    loss = lambda a, b: nn.functional.cross_entropy(m(torch.tensor(a)), torch.tensor(b), reduction=\"none\").numpy()\n    l_in, l_out = loss(can_X[cin], can_y[cin]), loss(can_X[cout], can_y[cout])\n    auc = roc_auc_score(np.r_[np.ones(50), np.zeros(50)], -np.r_[l_in, l_out])   # lower loss -> more likely a member\n    test_acc = (m(torch.tensor(X[te])).argmax(1).numpy() == y[te]).mean()\n    can_acc = (m(torch.tensor(can_X[cin])).argmax(1).numpy() == can_y[cin]).mean()\n    return test_acc, can_acc, auc\n\nfor name, dp, kw in [(\"non-private SGD\", False, {\"epochs\": 200}),\n                     (\"DP-SGD sigma=0.7\", True, {\"epochs\": 30, \"sigma\": 0.7}),\n                     (\"DP-SGD sigma=1.5\", True, {\"epochs\": 30, \"sigma\": 1.5})]:\n    m, eps = train(dp, **kw)\n    acc, can, auc = evaluate(m)\n    print(f\"{name:17s} eps={eps:6.2f}  test acc={acc:.3f}  memorized canaries={can:.2f}  MIA AUC on canaries={auc:.3f}\")\n```\n\nOutput (Python 3.13, PyTorch 2.15 CPU, Opacus 1.6.0, scikit-learn 1.9.1, δ=10⁻⁵, 2026-11-05):\n\n```text\nnon-private SGD   eps=   inf  test acc=0.980  memorized canaries=1.00  MIA AUC on canaries=0.978\nDP-SGD sigma=0.7  eps= 20.09  test acc=0.956  memorized canaries=0.18  MIA AUC on canaries=0.530\nDP-SGD sigma=1.5  eps=  4.56  test acc=0.918  memorized canaries=0.12  MIA AUC on canaries=0.551\n```\n\nWhat the results show:\n\n- The non-private model memorized all 50 random-label canaries (1.00), and the membership inference AUC is 0.978: it can almost perfectly tell which canaries were trained on.\n- Under DP-SGD, canary \"memorization\" falls to 0.12–0.18, close to the 0.10 expected from random guessing, and AUC falls to 0.53–0.55, close to the random 0.5. With only 50 + 50 canaries, small differences around 0.5 are sampling noise.\n- The cost is test accuracy falling from 0.980 to 0.956 (ε≈20) and 0.918 (ε≈4.6). The theoretical guarantee at ε=20 is weak, yet in practice memorization of rare records is largely gone; a smaller ε needs more noise and costs more accuracy.\n\n### Differential privacy for LLMs\n\nVaultGemma, released by Google in September 2025, is a 1B-parameter language model trained from scratch with differential privacy: the privacy unit is a 1,024-token sequence, with ε ≤ 2.0 and δ ≤ 1.1×10⁻¹⁰. Its utility is comparable to non-private models from about five years earlier, and prompting with 50-token prefixes from training documents showed no detectable memorization of the following 50 tokens ([Google Research, 2025](https://research.google/blog/vaultgemma-the-worlds-most-capable-differentially-private-llm/)). Provable privacy is achievable for LLMs, but currently at a clear cost in utility. Without differential privacy, common mitigations are deduplicating training data, filtering personal information and filtering outputs; these reduce risk but provide no provable guarantee.\n\n## Choosing defenses\n\n| Risk | What deployers can do | What model developers can do |\n|---|---|---|\n| Jailbreaks | Input/output classifiers (Llama Guard and others), restricting use context, logging and rate limiting, continuous red teaming | Safety training, constitutional classifiers, adversarial training, pre-release red teaming |\n| Adversarial examples | Input preprocessing, cross-checking with multiple models, human review of key decisions | Adversarial training, certified robustness methods |\n| Poisoning and backdoors | Weights from trusted sources with hash verification; record fine-tuning data provenance | Data provenance, filtering and deduplication, backdoor testing |\n| Training data leakage | Keep sensitive data out of fine-tuning sets; filter personal information in outputs | Deduplication, PII filtering, differentially private training |\n| Provenance of generated content | Use the provider's watermarks or content credentials | Embed watermarks and provide detection tools |\n\n## Hands-on exercises\n\n1. **Reproduce GCG**: on a machine with a GPU, use [llm-attacks](https://github.com/llm-attacks/llm-attacks) to attack a single request on a 7B open model and record the number of iterations; then add perplexity detection and see whether the generated suffix is flagged. (GCG was not run for this lesson: it needs a GPU and model weights, and this machine has only a CPU.)\n2. **Automated red teaming**: run jailbreak probes from [garak](https://github.com/NVIDIA/garak) or [promptfoo](https://www.promptfoo.dev/docs/red-team/) against a model you deploy, and measure the over-refusal rate on a set of benign requests at the same time.\n3. **Adversarial training trade-offs**: modify `fgsm_demo.py` to adversarially train at ε=0.2, or replace FGSM with multi-step PGD, and compare clean accuracy and robust accuracy at each ε.\n4. **Watermark parameters**: vary γ and δ in `watermark_demo.py` and plot the tokens needed for detection against the replacement fraction; then use SynthID-Text in Transformers to watermark and detect output from a small model.\n5. **Privacy budget**: vary the noise multiplier σ, clipping norm C and number of epochs in `dp_mia_demo.py`, and plot ε against test accuracy and canary AUC.\n\nRelated algorithm cards: [Adversarial examples (FGSM)](/learn/algorithms/adversarial-examples), [GCG universal jailbreak attack](/learn/algorithms/gcg-jailbreak), [Automated red teaming](/learn/algorithms/red-teaming), [Sleeper agents](/learn/algorithms/sleeper-agents), [LLM watermarking](/learn/algorithms/watermarking), [Membership inference attacks](/learn/algorithms/membership-inference), [Differentially private SGD (DP-SGD)](/learn/algorithms/dp-sgd), [Constitutional AI / RLAIF](/learn/algorithms/constitutional-ai)."
    },
    "zh-hans": {
      "title": "大模型攻击面：越狱、对抗样本、数据投毒、水印与隐私攻击（附可运行代码）",
      "description": "系统介绍针对大模型本身的攻击与防御：安全训练为什么会被越狱（竞争目标与泛化不匹配）；GCG、PAIR 与多样本越狱；红队测试、Llama Guard、宪法分类器与 HarmBench；FGSM 对抗样本与对抗训练；250 份文档即可植入后门的数据投毒与潜伏后门；Kirchenbauer 绿名单水印与 SynthID-Text；训练数据提取、成员推断与 DP-SGD 差分隐私训练。依据原始论文与官方资料，附本地实测的 FGSM、水印检测与 DP-SGD 成员推断代码。",
      "updated": "2026-11-05",
      "takeaways": [
        "安全训练失效有两类原因：模型的能力目标与安全目标冲突（竞争目标），以及安全训练没有覆盖模型已具备能力的领域（泛化不匹配）。越狱方法分为人工构造、白盒梯度优化（GCG）、黑盒迭代（PAIR）和利用长上下文（多样本越狱）。",
        "防御通常组合安全训练、输入输出分类器和持续红队测试。Anthropic 的宪法分类器经过 3,000 多小时红队测试，生产流量拒答率绝对值只增加 0.38%，推理开销增加 23.7%；但对按防御专门设计的自适应攻击，任何单层防御都不能视为保证。",
        "对抗样本说明模型对人眼几乎不可见的扰动很敏感。本课实测中，扰动幅度 ε=0.1 的 FGSM 把一个手写数字分类器的准确率从 97.4% 降到约 37%；对抗训练后同一攻击下为 83.9%。GCG 是同一思路在离散 token 上的版本。",
        "数据投毒所需的样本数可能与模型规模无关：在 6 亿到 130 亿参数的预训练实验中，250 份投毒文档对各规模模型的效果相近。潜伏后门可以在监督微调、强化学习和对抗训练后保留。",
        "水印只能识别配合方模型生成的文本：Kirchenbauer 水印用 z 检验检测，200 个 token 就有很强的统计证据，但大量改写会使其失效。隐私方面，模型会记住只出现一次的训练数据；DP-SGD 给出可证明的上界，本课实测把金丝雀记忆率从 100% 降到 12–18%，代价是测试准确率下降 2–6 个百分点。"
      ],
      "faq": [
        {
          "q": "越狱和提示注入是同一回事吗？",
          "a": "不是。越狱让模型突破自己的安全规则，攻击者是与模型对话的用户；提示注入让应用执行不可信内容里的指令，攻击者常是第三方。两者经常组合出现，防御重点也不同：越狱主要靠安全训练、分类器和红队测试，提示注入还需要权限与架构控制。提示注入见上一课。"
        },
        {
          "q": "开源模型的越狱防御有什么特殊之处？",
          "a": "拿到权重的人可以直接微调掉安全行为，也可以用 GCG 这类白盒梯度方法优化攻击字符串，所以开源模型的部署方通常需要在模型外加输入输出分类器（如 Llama Guard）并控制使用场景。GCG 论文还显示，在开源模型上优化出的攻击后缀能迁移到闭源模型。"
        },
        {
          "q": "大模型水印能用来判断任意一段文字是否由 AI 写成吗？",
          "a": "不能。水印检测只对嵌入了同一水印、且检测方持有密钥的模型输出有效；没有水印的模型生成的文字，检测结果与人写的文字相同。改写、翻译和混入人写内容也会削弱信号。通用的“AI 文本检测器”是另一类基于统计特征的分类器，误判率需要单独评估。"
        },
        {
          "q": "用 DP-SGD 训练时 ε 取多少合适？",
          "a": "ε 越小保证越强，没有统一标准。实践中常见的做法是报告 ε、δ 和隐私单位（按样本、按序列还是按用户），并说明会计方法。例如 Google 的 VaultGemma 采用按序列（1,024 个 token）的差分隐私，ε ≤ 2.0、δ ≤ 1.1×10⁻¹⁰。ε 在 10 以上时理论保证较弱，但如本课实测所示，仍能明显降低对罕见样本的记忆。"
        },
        {
          "q": "红队测试应该怎样组织？",
          "a": "先确定威胁模型和要防止的危害类别，再组合人工红队与自动化方法（GCG、PAIR 等），用 HarmBench、JailbreakBench 这类公开框架统一评估口径；每次更新模型、提示或分类器后重跑，并把成功的攻击加入回归测试集。结果应同时报告攻击成功率和正常请求的误拒率。"
        }
      ],
      "sources": [
        {
          "title": "NIST（2025），AI 100-2 E2025: Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations",
          "url": "https://csrc.nist.gov/pubs/ai/100/2/e2025/final"
        },
        {
          "title": "Wei、Haghtalab、Steinhardt（2023），Jailbroken: How Does LLM Safety Training Fail?",
          "url": "https://arxiv.org/abs/2307.02483"
        },
        {
          "title": "Zou 等（2023），Universal and Transferable Adversarial Attacks on Aligned Language Models（GCG）",
          "url": "https://arxiv.org/abs/2307.15043"
        },
        {
          "title": "llm-attacks（GCG 官方代码）",
          "url": "https://github.com/llm-attacks/llm-attacks"
        },
        {
          "title": "Chao 等（2023），Jailbreaking Black Box Large Language Models in Twenty Queries（PAIR）",
          "url": "https://arxiv.org/abs/2310.08419"
        },
        {
          "title": "Anthropic（2024），Many-shot jailbreaking",
          "url": "https://www.anthropic.com/research/many-shot-jailbreaking"
        },
        {
          "title": "Ganguli 等（2022），Red Teaming Language Models to Reduce Harms: Methods, Scaling Behaviors, and Lessons Learned",
          "url": "https://arxiv.org/abs/2209.07858"
        },
        {
          "title": "Inan 等（2023），Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations",
          "url": "https://arxiv.org/abs/2312.06674"
        },
        {
          "title": "Sharma 等（2025），Constitutional Classifiers: Defending against Universal Jailbreaks across Thousands of Hours of Red Teaming",
          "url": "https://arxiv.org/abs/2501.18837"
        },
        {
          "title": "Mazeika 等（2024），HarmBench: A Standardized Evaluation Framework for Automated Red Teaming and Robust Refusal",
          "url": "https://arxiv.org/abs/2402.04249"
        },
        {
          "title": "Chao 等（2024），JailbreakBench: An Open Robustness Benchmark for Jailbreaking Large Language Models",
          "url": "https://arxiv.org/abs/2404.01318"
        },
        {
          "title": "Goodfellow、Shlens、Szegedy（2014），Explaining and Harnessing Adversarial Examples（FGSM）",
          "url": "https://arxiv.org/abs/1412.6572"
        },
        {
          "title": "Madry 等（2017），Towards Deep Learning Models Resistant to Adversarial Attacks（PGD）",
          "url": "https://arxiv.org/abs/1706.06083"
        },
        {
          "title": "Jain 等（2023），Baseline Defenses for Adversarial Attacks Against Aligned Language Models",
          "url": "https://arxiv.org/abs/2309.00614"
        },
        {
          "title": "PyTorch 官方教程，Adversarial Example Generation（FGSM）",
          "url": "https://docs.pytorch.org/tutorials/beginner/fgsm_tutorial.html"
        },
        {
          "title": "Souly 等（2025），Poisoning Attacks on LLMs Require a Near-constant Number of Poison Samples",
          "url": "https://arxiv.org/abs/2510.07192"
        },
        {
          "title": "Anthropic（2025），A small number of samples can poison LLMs of any size",
          "url": "https://www.anthropic.com/research/small-samples-poison"
        },
        {
          "title": "Hubinger 等（2024），Sleeper Agents: Training Deceptive LLMs that Persist Through Safety Training",
          "url": "https://arxiv.org/abs/2401.05566"
        },
        {
          "title": "Kirchenbauer 等（2023），A Watermark for Large Language Models",
          "url": "https://arxiv.org/abs/2301.10226"
        },
        {
          "title": "jwkirchenbauer/lm-watermarking（官方代码）",
          "url": "https://github.com/jwkirchenbauer/lm-watermarking"
        },
        {
          "title": "Dathathri 等（2024），Scalable watermarking for identifying large language model outputs（Nature，SynthID-Text）",
          "url": "https://www.nature.com/articles/s41586-024-08025-4"
        },
        {
          "title": "Hugging Face（2024），Introducing SynthID Text",
          "url": "https://huggingface.co/blog/synthid-text"
        },
        {
          "title": "Carlini 等（2021），Extracting Training Data from Large Language Models",
          "url": "https://arxiv.org/abs/2012.07805"
        },
        {
          "title": "Nasr 等（2023），Scalable Extraction of Training Data from (Production) Language Models",
          "url": "https://arxiv.org/abs/2311.17035"
        },
        {
          "title": "Shokri 等（2017），Membership Inference Attacks against Machine Learning Models",
          "url": "https://arxiv.org/abs/1610.05820"
        },
        {
          "title": "Yeom 等（2018），Privacy Risk in Machine Learning: Analyzing the Connection to Overfitting",
          "url": "https://arxiv.org/abs/1709.01604"
        },
        {
          "title": "Carlini 等（2022），Membership Inference Attacks From First Principles（LiRA）",
          "url": "https://arxiv.org/abs/2112.03570"
        },
        {
          "title": "Abadi 等（2016），Deep Learning with Differential Privacy（DP-SGD）",
          "url": "https://arxiv.org/abs/1607.00133"
        },
        {
          "title": "Opacus 官方文档",
          "url": "https://opacus.ai/"
        },
        {
          "title": "Google Research（2025），VaultGemma: The world's most capable differentially private LLM",
          "url": "https://research.google/blog/vaultgemma-the-worlds-most-capable-differentially-private-llm/"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/safety/jailbreak-privacy/",
      "markdown": "**一句话回答**：针对大模型本身的攻击可以按发生阶段分为四类：推理时诱导模型违反安全规则（越狱、对抗样本），训练时污染数据植入后门（投毒），以及从模型中获取训练数据信息（提取、成员推断）；水印则是反方向的技术，用于事后识别模型生成的文本。每一类都有经过检验的防御，但没有一种能独立提供完整保证。\n\n这一课属于[安全攻防：越狱、注入与隐私](/learn/unit/u92-security)单元。应用与 Agent 层面的提示注入见[提示注入与工具投毒](/learn/prompt-injection)；评测数据污染与成员推断在评测中的用法见[大模型评测与基准](/learn/llm-evaluation)。\n\n## 攻击面总览\n\n美国国家标准与技术研究院（NIST）的《对抗机器学习：攻击与缓解的分类和术语》（AI 100-2 E2025）按机器学习方法、攻击发生的生命周期阶段，以及攻击者的目标、能力和知识对攻击分类（[NIST，2025](https://csrc.nist.gov/pubs/ai/100/2/e2025/final)）。本课按阶段整理：\n\n| 攻击 | 阶段 | 攻击者需要的条件 | 目的 | 主要防御 |\n|---|---|---|---|---|\n| 越狱 | 推理 | 能向模型发提示；白盒方法还需要权重 | 让模型输出被禁止的内容 | 安全训练、输入输出分类器、红队测试 |\n| 对抗样本 | 推理 | 白盒梯度或大量黑盒查询 | 让模型误判 | 对抗训练、输入预处理、认证鲁棒性 |\n| 数据投毒与后门 | 训练 | 能让数据进入训练集（如公开网页、微调数据） | 植入触发词控制的行为 | 数据来源管理、过滤、后门检测 |\n| 训练数据提取 | 推理 | 能查询模型 | 复现训练数据原文 | 去重、过滤敏感数据、差分隐私、输出过滤 |\n| 成员推断 | 推理 | 能查询模型，获得损失或置信度 | 判断某条数据是否被用于训练 | 差分隐私、正则化、限制输出信息 |\n| 水印（防御方技术） | 生成与检测 | 模型提供方持有密钥 | 识别模型生成的文本 | 不适用；攻击方式是改写、翻译 |\n\n## 越狱\n\n### 安全训练为什么会失效\n\nWei、Haghtalab 和 Steinhardt（2023）提出安全训练的两种失效模式（[Wei 等，2023](https://arxiv.org/abs/2307.02483)）：\n\n- **竞争目标**：模型的能力目标（如遵循指令、续写格式）与安全目标冲突。例如要求模型以“当然，以下是……”开头，或禁止它使用拒绝用语。\n- **泛化不匹配**：安全训练没有覆盖模型已经具备能力的领域。例如用 Base64 编码、少见语言或特殊格式提出请求，模型能理解内容，却没有学会在这种形式下拒绝。\n\n作者按这两种模式设计的新攻击，在 GPT-4 和 Claude v1.3 的红队评测集的所有不安全请求上都取得成功。他们据此提出“安全与能力对等”：安全机制应与底层模型同样复杂，仅靠扩大规模不能解决这些失效模式。\n\n### 越狱方法\n\n| 方法 | 访问条件 | 原理 | 公开结果 |\n|---|---|---|---|\n| 人工越狱 | 黑盒 | 角色扮演、虚构情境、编码、拆分请求等，利用上述两种失效模式 | 早期 ChatGPT 上大量流传（Wei 等，2023） |\n| GCG | 白盒梯度（可迁移到黑盒） | 在请求后附加一段后缀，用梯度挑选候选 token 并贪心替换，使模型以“Sure, here is …”开头的概率最大 | Vicuna 上 100 个有害行为中 99 个成功；在 GPT-3.5、GPT-4 上迁移成功率最高 84%，PaLM-2 为 66%，Claude 明显更低（2.1%）（[Zou 等，2023](https://arxiv.org/abs/2307.15043)） |\n| PAIR | 黑盒 | 用一个攻击者 LLM 反复查询目标模型，按回应改写越狱提示，借鉴社会工程 | 常在 20 次查询内找到越狱，在 GPT-3.5/4、Vicuna、Gemini 上有竞争力的成功率（[Chao 等，2023](https://arxiv.org/abs/2310.08419)） |\n| 多样本越狱 | 黑盒，需要长上下文 | 在提示中放入大量伪造的问答示例，利用上下文学习 | 测试最多 256 个示例；效果随示例数按幂律增长，与普通上下文学习的规律相同（[Anthropic，2024](https://www.anthropic.com/research/many-shot-jailbreaking)） |\n\nGCG 的优化流程可以概括为：\n\n1. 设定目标输出前缀（如“Sure, here is how to …”），损失为模型生成该前缀的负对数概率；\n2. 对后缀中每个位置的 one-hot token 求梯度，取负梯度最大的 top-k 个候选替换；\n3. 随机抽取一批“单个位置替换”的候选后缀，实际计算损失，保留最好的一个；\n4. 重复，直到模型输出目标前缀。对多个请求和多个模型同时优化，得到通用、可迁移的后缀。\n\n这本质上是下文 FGSM 思路在离散 token 空间上的推广。Jain 等（2023）评估了三类基线防御：基于困惑度的检测、输入预处理（改写、重新分词）和对抗训练，并讨论了各自的鲁棒性与性能权衡（[Jain 等，2023](https://arxiv.org/abs/2309.00614)）。GCG 生成的后缀多为无意义字符串，困惑度检测针对的正是这一特征；PAIR 这类生成自然语言的攻击则没有这一特征。\n\n### 防御与评估\n\n- **红队测试**：Anthropic 的 Ganguli 等（2022）在 27 亿、130 亿和 520 亿参数的模型上对比了四类模型（普通语言模型、提示为有益诚实无害的模型、拒绝采样模型、RLHF 模型），发现 RLHF 模型随规模增大越来越难被红队攻破，其他类型没有明显趋势；他们公开了 38,961 条红队攻击数据（[Ganguli 等，2022](https://arxiv.org/abs/2209.07858)）。\n- **输入输出分类器**：Meta 的 Llama Guard 是在 Llama2-7b 上指令微调的安全分类模型，按安全风险分类法同时对用户提示和模型回答分类，分类法可以在提示中替换（[Inan 等，2023](https://arxiv.org/abs/2312.06674)）。\n- **宪法分类器**：Anthropic 用自然语言规则（“宪法”）规定允许和禁止的内容，让 LLM 生成合成数据训练输入与输出分类器。早期版本经过估计 3,000 多小时的红队测试，没有红队成员找到能在多数目标问题上提取与无防护模型同等详细信息的通用越狱；增强版在生产流量中的拒答率绝对值只增加 0.38%，推理开销增加 23.7%（[Sharma 等，2025](https://arxiv.org/abs/2501.18837)）。\n- **针对多样本越狱**：Anthropic 报告，在提示进入模型前对其分类和修改的方法，在一个案例中把攻击成功率从 61% 降到 2%。\n- **标准化评估**：HarmBench 用统一框架比较了 18 种红队方法和 33 个目标模型与防御（[Mazeika 等，2024](https://arxiv.org/abs/2402.04249)）；JailbreakBench 包含持续更新的对抗提示库、100 个有害行为组成的数据集、定义了威胁模型与评分函数的标准化评测框架，以及排行榜（[Chao 等，2024](https://arxiv.org/abs/2404.01318)）。\n\n上一课提到的自适应攻击结论同样适用于越狱：Nasr 等（2025）绕过的 12 种防御中包括越狱防御。评估自己的防御时，应使用按该防御专门调整过的攻击，并同时报告攻击成功率和正常请求的误拒率。\n\n## 对抗样本\n\n对抗样本是在输入上加入人难以察觉、却能改变模型判断的扰动。Goodfellow 等（2014）认为，神经网络易受对抗扰动影响的主要原因是其局部的线性行为，并据此提出**快速梯度符号法**（FGSM）（[Goodfellow 等，2014](https://arxiv.org/abs/1412.6572)）：\n\nx′ = x + ε · sign(∇ₓ L(θ, x, y))\n\n即沿损失对输入梯度的符号方向，每个像素移动 ε。Madry 等（2017）把对抗鲁棒性表述为鲁棒优化问题，用多步的投影梯度下降（PGD）作为“一阶攻击者”，并用 PGD 样本做对抗训练（[Madry 等，2017](https://arxiv.org/abs/1706.06083)）。\n\n下面的代码在 sklearn 的 8×8 手写数字数据集上训练两个两层感知机：一个用普通训练，一个用 ε=0.1 的 FGSM 样本做对抗训练（每批一半干净样本、一半对抗样本），再用不同 ε 的 FGSM 攻击测试集。像素值缩放到 [0, 1]，ε=0.1 相当于每个像素最多改变满量程的 10%。\n\n```python\n# FGSM 对抗样本与对抗训练（Goodfellow 等 2014）：sklearn 手写数字 8×8，像素缩放到 [0,1]。\nimport numpy as np, torch, torch.nn as nn\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split\ntorch.manual_seed(0); torch.set_num_threads(2)\nX, y = load_digits(return_X_y=True); X = X / 16.0\nXtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)\nXtr, Xte = map(lambda a: torch.tensor(a, dtype=torch.float32), (Xtr, Xte))\nytr, yte = map(torch.tensor, (ytr, yte))\n\ndef mlp(): return nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))\nloss_fn = nn.CrossEntropyLoss()\n\ndef fgsm(model, x, y, eps):\n    x = x.clone().requires_grad_(True)\n    loss_fn(model(x), y).backward()\n    return (x + eps * x.grad.sign()).clamp(0, 1).detach()   # 沿梯度符号走一步\n\ndef train(adv_eps=0.0, epochs=60):\n    m = mlp(); opt = torch.optim.Adam(m.parameters(), lr=1e-2)\n    for _ in range(epochs):\n        for idx in torch.randperm(len(Xtr)).split(64):\n            xb, yb = Xtr[idx], ytr[idx]\n            if adv_eps:                                       # 对抗训练：一半干净样本、一半 FGSM 样本\n                xb = torch.cat([xb, fgsm(m, xb, yb, adv_eps)]); yb = torch.cat([yb, yb])\n            opt.zero_grad(); loss_fn(m(xb), yb).backward(); opt.step()\n    return m\n\ndef acc(m, x): return (m(x).argmax(1) == yte).float().mean().item()\n\nfor name, m in [(\"standard\", train()), (\"adv-trained eps=0.1\", train(adv_eps=0.1))]:\n    row = [f\"eps={e:.2f}: {acc(m, fgsm(m, Xte, yte, e) if e else Xte):.3f}\" for e in (0, 0.05, 0.1, 0.2)]\n    print(f\"{name:20s}\", \"  \".join(row))\n```\n\n运行输出（Python 3.13、PyTorch 2.15 CPU，2026-11-05）：\n\n```text\nstandard             eps=0.00: 0.974  eps=0.05: 0.806  eps=0.10: 0.370  eps=0.20: 0.085\nadv-trained eps=0.1  eps=0.00: 0.989  eps=0.05: 0.948  eps=0.10: 0.839  eps=0.20: 0.365\n```\n\n多线程计算的浮点误差可能使重复运行时的第三位小数略有差异。结果说明：\n\n- 普通模型在 ε=0.1 时准确率从 0.974 降到 0.370，ε=0.2 时只剩 0.085，低于随机猜测的 0.1。\n- 对抗训练后，ε=0.1（训练时使用的强度）下准确率为 0.839；但 ε=0.2 时仍降到 0.365，对超出训练强度的攻击保护有限。\n- 本例中对抗训练没有降低干净样本准确率（0.989），在更大的数据集上通常会有一定的准确率损失。\n\n## 数据投毒与后门\n\n**投毒样本数与模型规模无关**：Anthropic 与英国人工智能安全研究所（UK AI Security Institute）、艾伦·图灵研究所的 Souly 等（2025）做了当时规模最大的预训练投毒实验，在 Chinchilla 最优的数据量（60 亿到 2,600 亿 token）上预训练 6 亿到 130 亿参数的模型。250 份投毒文档对所有规模的模型效果相近，尽管最大的模型使用的干净数据是最小模型的 20 倍以上；微调阶段的投毒也表现出相同规律（[Souly 等，2025](https://arxiv.org/abs/2510.07192)）。实验使用的是“拒绝服务”型后门：提示中出现特定触发短语时，模型输出无意义的乱码。Anthropic 说明这种窄后门对前沿模型的风险有限，该规律是否适用于更大的模型和危害更大的行为尚不清楚（[Anthropic，2025](https://www.anthropic.com/research/small-samples-poison)）。即便如此，以“投毒数据占训练集的比例”来评估风险可能低估大模型面临的威胁。\n\n**潜伏后门**：Hubinger 等（2024）训练出一类模型：提示中写明年份是 2023 年时写安全的代码，写明是 2024 年时插入可利用的漏洞。这种后门在监督微调、强化学习和对抗训练后都能保留，在最大的模型和被训练对“欺骗训练过程”进行思维链推理的模型中最持久；对抗训练反而让模型更会识别触发条件，从而隐藏不安全行为（[Hubinger 等，2024](https://arxiv.org/abs/2401.05566)）。结论是：一旦模型存在这类行为，标准安全训练可能不能消除它，反而造成安全的假象。\n\n防御重点因此前移到数据与供应链：\n\n- 记录训练与微调数据的来源，对来自开放网络和第三方的数据做过滤与去重；\n- 只从可信来源下载模型权重，核对哈希，记录模型的来源与修改历史；\n- 针对已知的触发模式做行为测试，但要认识到测试无法穷举未知触发词。\n\n## 文本水印\n\n### 绿名单水印\n\nKirchenbauer 等（2023）的水印在生成每个 token 前，用密钥和上一个 token 做随机种子，把词表随机分成比例为 γ 的“绿名单”和其余的“红名单”，并给绿名单 token 的 logits 加上 δ（[Kirchenbauer 等，2023](https://arxiv.org/abs/2301.10226)）。有多种合理续写时，模型会更多地选到绿名单 token；只有一种合理续写时（如固定搭配），δ 的影响很小，文本质量受损也小。检测时不需要模型，只需要密钥：统计 T 个 token 中绿名单 token 的个数 |s|_G，计算\n\nz = (|s|_G − γT) / √(T · γ · (1 − γ))\n\n论文以 z > 4 为阈值，单侧假阳性率为 3×10⁻⁵；论文示例使用 γ=0.5、δ=2。下面的代码用一个玩具语言模型（词表 5,000，下一个 token 的分布只依赖上一个 token）实现生成与检测，参数取 γ=0.25、δ=2，并模拟随机替换部分 token 的改写。\n\n```python\n# Kirchenbauer 等（2023）“绿名单”软水印：玩具语言模型 + 水印生成 + z 检验。\n# 玩具模型：词表 5000，下一个词的 logits 由上一个词决定（固定随机，近似真实模型的“有多种合理续写”）。\nimport hashlib, math, numpy as np\nV, GAMMA, DELTA, KEY = 5000, 0.25, 2.0, 15485863\nrng_lm = np.random.default_rng(0)\nBASE = rng_lm.normal(0, 3.0, size=V)            # 词的基础频率差异\n\ndef lm_logits(prev):\n    r = np.random.default_rng(prev + 1)\n    return BASE + r.normal(0, 3.0, size=V)\n\ndef green_list(prev):\n    \"\"\"用密钥和上一个词做种子，把词表随机切出 γ 比例的“绿名单”。\"\"\"\n    seed = int(hashlib.sha256(f\"{KEY}:{prev}\".encode()).hexdigest()[:8], 16)\n    return np.random.default_rng(seed).permutation(V)[: int(GAMMA * V)]\n\ndef generate(n, watermark, seed):\n    rng, out, prev = np.random.default_rng(seed), [], 0\n    for _ in range(n):\n        z = lm_logits(prev)\n        if watermark:\n            z = z.copy(); z[green_list(prev)] += DELTA   # 给绿名单里的词加 δ\n        p = np.exp(z - z.max()); p /= p.sum()\n        prev = int(rng.choice(V, p=p)); out.append(prev)\n    return out\n\ndef z_score(tokens):\n    \"\"\"检测只需要密钥，不需要模型：数绿词个数，和 γT 比较。\"\"\"\n    prev, hits = 0, 0\n    for t in tokens:\n        hits += t in set(green_list(prev)); prev = t\n    T = len(tokens)\n    return (hits - GAMMA * T) / math.sqrt(T * GAMMA * (1 - GAMMA)), hits / T\n\ndef edit(tokens, frac, seed):\n    \"\"\"模拟改写：随机把一部分词替换成随机词。\"\"\"\n    rng = np.random.default_rng(seed); t = list(tokens)\n    for i in rng.choice(len(t), int(frac * len(t)), replace=False):\n        t[i] = int(rng.integers(V))\n    return t\n\nif __name__ == \"__main__\":\n    T = 200\n    human = generate(T, False, 1); marked = generate(T, True, 1)\n    for name, toks in [(\"no watermark\", human), (\"watermarked\", marked),\n                       (\"watermarked, 20% tokens replaced\", edit(marked, 0.2, 2)),\n                       (\"watermarked, 50% tokens replaced\", edit(marked, 0.5, 2))]:\n        z, g = z_score(toks)\n        print(f\"{name:34s} green={g:.2f}  z={z:6.2f}  {'DETECTED' if z > 4 else 'not detected'} (threshold z>4)\")\n    for n in (25, 50, 100):\n        print(f\"first {n:3d} watermarked tokens: z={z_score(marked[:n])[0]:.2f}\")\n```\n\n运行输出（Python 3.13、NumPy 2.5，2026-11-05）：\n\n```text\nno watermark                       green=0.27  z=  0.49  not detected (threshold z>4)\nwatermarked                        green=0.64  z= 12.74  DETECTED (threshold z>4)\nwatermarked, 20% tokens replaced   green=0.52  z=  8.65  DETECTED (threshold z>4)\nwatermarked, 50% tokens replaced   green=0.33  z=  2.45  not detected (threshold z>4)\nfirst  25 watermarked tokens: z=3.58\nfirst  50 watermarked tokens: z=6.37\nfirst 100 watermarked tokens: z=8.54\n```\n\n结果说明：\n\n- 无水印文本的绿名单比例 0.27，接近 γ=0.25，z=0.49；有水印文本为 0.64，z=12.74，统计证据很强。\n- 随机替换 20% 的 token 后 z 仍为 8.65；替换 50% 后降到 2.45，低于阈值。替换一个 token 会同时影响它自己和下一个 token 的绿名单判定，所以改写对水印的破坏比替换比例更大。\n- 检测所需长度：前 25 个 token 的 z=3.58，尚未达到阈值；50 个 token 时为 6.37。\n\n### SynthID-Text\n\nGoogle DeepMind 的 SynthID-Text 只修改采样过程，不改变模型训练；检测不需要访问模型。论文在近 2,000 万条 Gemini 实际回答上做了在线实验评估文本质量，并把水印与推测采样（speculative sampling）结合以用于大规模生产（[Dathathri 等，2024](https://www.nature.com/articles/s41586-024-08025-4)）。Hugging Face Transformers 从 v4.46.0 起提供 SynthID-Text：水印配置包含一组整数密钥 `keys`（建议 20–30 个随机数）和 `ngram_len`（默认 5，至少为 2，越大越容易检测但越不耐改动），检测器是需要用配置训练的贝叶斯分类器（[Hugging Face，2024](https://huggingface.co/blog/synthid-text)）。官方说明的局限：对事实类回答效果较弱，因为可调整的余地小；文本被彻底改写或翻译成其他语言后，检测置信度会大幅下降；它不是为阻止有动机的攻击者而设计的。\n\n## 隐私攻击与差分隐私\n\n### 训练数据提取\n\nCarlini 等（2021）从 GPT-2 中提取出数百条逐字的训练文本，包括公开的个人信息（姓名、电话、邮箱）、IRC 对话、代码和 128 位 UUID；这些序列在训练数据中都只出现在一个文档里。他们还发现大模型比小模型更容易泄露（[Carlini 等，2021](https://arxiv.org/abs/2012.07805)）。Nasr 等（2023）把提取规模扩大到 GB 级，对象包括 Pythia、GPT-Neo、LLaMA、Falcon 和 ChatGPT；针对经过对齐的 ChatGPT，他们设计的“发散攻击”让模型偏离聊天式回答，输出训练数据的速率是正常时的 150 倍。结论是当前的对齐技术不能消除记忆（[Nasr 等，2023](https://arxiv.org/abs/2311.17035)）。\n\n### 成员推断\n\n成员推断攻击判断一条数据是否在模型的训练集中（[Shokri 等，2017](https://arxiv.org/abs/1610.05820)）。最简单的方法是损失阈值：训练过的样本损失通常更低。Yeom 等（2018）证明过拟合足以使成员推断成功，但不是必要条件（[Yeom 等，2018](https://arxiv.org/abs/1709.01604)）。Carlini 等（2022）指出，用平均准确率评估成员推断会掩盖风险，应报告低假阳性率（如 0.1% 以下）时的真阳性率；他们的似然比攻击（LiRA）在低假阳性率下的效果是此前方法的 10 倍（[Carlini 等，2022](https://arxiv.org/abs/2112.03570)）。在评测中，成员推断也被用来检测基准题是否进入了训练数据。\n\n### DP-SGD\n\n差分隐私的含义是：训练集中加入或去掉任意一条记录，训练结果的分布变化不超过 e^ε 倍（再加一个很小的失败概率 δ）。Abadi 等（2016）的 DP-SGD 在每一步：\n\n1. 对每个样本单独计算梯度，并裁剪到 L2 范数不超过 C；\n2. 对一批裁剪后的梯度求和，加上标准差为 σC 的高斯噪声，再取平均更新参数；\n3. 用隐私会计方法（论文提出 moments accountant；Opacus 提供 RDP 等会计方法）累计整个训练过程的 ε（[Abadi 等，2016](https://arxiv.org/abs/1607.00133)）。\n\n下面的代码用 Meta 的 Opacus 库实现 DP-SGD，并用“金丝雀”测试衡量记忆：在 1,200 张训练图片中混入 50 张随机噪声图，配上随机标签（这类记录罕见且无规律可学，只能靠记忆）；另外生成 50 张同样的噪声图不参与训练。攻击者只看模型对每张金丝雀的损失，判断它是否参与了训练。\n\n```python\n# 成员推断（损失阈值攻击，Yeom 等 2018）与 DP-SGD（Abadi 等 2016，用 Opacus 实现）。\n# 做法参考“金丝雀”测试：在训练集里混入 50 条随机噪声图 + 随机标签（罕见、只出现一次的记录），\n# 另生成 50 条同分布但不参与训练的金丝雀；攻击者只看模型对每条记录的损失，猜它是否在训练集中。\nimport warnings; warnings.filterwarnings(\"ignore\")\nimport numpy as np, torch, torch.nn as nn\nfrom sklearn.datasets import load_digits\nfrom sklearn.metrics import roc_auc_score\nfrom opacus import PrivacyEngine\ntorch.manual_seed(0); torch.set_num_threads(2)\nrng = np.random.default_rng(0)\nX, y = load_digits(return_X_y=True); X = (X / 16.0).astype(\"float32\")\nidx = rng.permutation(len(X)); tr, te = idx[:1200], idx[1200:]\ncan_X = rng.random((100, 64)).astype(\"float32\"); can_y = rng.integers(0, 10, 100)\ncin, cout = slice(0, 50), slice(50, 100)          # 前 50 条参与训练，后 50 条不参与\nXtr = np.vstack([X[tr], can_X[cin]]); ytr = np.r_[y[tr], can_y[cin]]\nT = lambda a, b: (torch.tensor(a), torch.tensor(b))\n\ndef train(dp, epochs, sigma=1.0, C=1.0):\n    m = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10))\n    opt = torch.optim.SGD(m.parameters(), lr=0.5 if dp else 0.1)\n    dl = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(*T(Xtr, ytr)), batch_size=64, shuffle=True)\n    eng = None\n    if dp:   # 逐样本梯度裁剪到范数 C，再加 N(0, σ²C²) 噪声；Opacus 默认用 Poisson 采样\n        eng = PrivacyEngine(accountant=\"rdp\")\n        m, opt, dl = eng.make_private(module=m, optimizer=opt, data_loader=dl,\n                                      noise_multiplier=sigma, max_grad_norm=C)\n    for _ in range(epochs):\n        for xb, yb in dl:\n            if len(xb) == 0: continue\n            opt.zero_grad(); nn.functional.cross_entropy(m(xb), yb).backward(); opt.step()\n    return m, (eng.get_epsilon(delta=1e-5) if eng else float(\"inf\"))\n\n@torch.no_grad()\ndef evaluate(m):\n    loss = lambda a, b: nn.functional.cross_entropy(m(torch.tensor(a)), torch.tensor(b), reduction=\"none\").numpy()\n    l_in, l_out = loss(can_X[cin], can_y[cin]), loss(can_X[cout], can_y[cout])\n    auc = roc_auc_score(np.r_[np.ones(50), np.zeros(50)], -np.r_[l_in, l_out])   # 损失越小越像成员\n    test_acc = (m(torch.tensor(X[te])).argmax(1).numpy() == y[te]).mean()\n    can_acc = (m(torch.tensor(can_X[cin])).argmax(1).numpy() == can_y[cin]).mean()\n    return test_acc, can_acc, auc\n\nfor name, dp, kw in [(\"non-private SGD\", False, {\"epochs\": 200}),\n                     (\"DP-SGD sigma=0.7\", True, {\"epochs\": 30, \"sigma\": 0.7}),\n                     (\"DP-SGD sigma=1.5\", True, {\"epochs\": 30, \"sigma\": 1.5})]:\n    m, eps = train(dp, **kw)\n    acc, can, auc = evaluate(m)\n    print(f\"{name:17s} eps={eps:6.2f}  test acc={acc:.3f}  memorized canaries={can:.2f}  MIA AUC on canaries={auc:.3f}\")\n```\n\n运行输出（Python 3.13、PyTorch 2.15 CPU、Opacus 1.6.0、scikit-learn 1.9.1，δ=10⁻⁵，2026-11-05）：\n\n```text\nnon-private SGD   eps=   inf  test acc=0.980  memorized canaries=1.00  MIA AUC on canaries=0.978\nDP-SGD sigma=0.7  eps= 20.09  test acc=0.956  memorized canaries=0.18  MIA AUC on canaries=0.530\nDP-SGD sigma=1.5  eps=  4.56  test acc=0.918  memorized canaries=0.12  MIA AUC on canaries=0.551\n```\n\n结果说明：\n\n- 普通训练的模型把 50 条随机标签金丝雀全部记住（1.00），成员推断 AUC 为 0.978，几乎能完美区分哪些金丝雀参与了训练。\n- DP-SGD 下金丝雀的“记住率”降到 0.12–0.18，接近随机猜中的 0.10；AUC 降到 0.53–0.55，接近随机的 0.5。每组只有 50 + 50 条金丝雀，AUC 在 0.5 附近的小幅差异属于抽样波动。\n- 代价是测试准确率从 0.980 降到 0.956（ε≈20）和 0.918（ε≈4.6）。ε=20 的理论保证很弱，但实测已基本消除对罕见样本的记忆；更小的 ε 需要更多噪声，准确率损失更大。\n\n### 大模型上的差分隐私\n\nGoogle 于 2025 年 9 月发布的 VaultGemma 是 10 亿参数、从头以差分隐私训练的语言模型：隐私单位是 1,024 个 token 的序列，ε ≤ 2.0、δ ≤ 1.1×10⁻¹⁰；效用与约 5 年前的非隐私模型相当；用训练文档的 50 个 token 前缀做提示时，没有检测到对后续 50 个 token 的记忆（[Google Research，2025](https://research.google/blog/vaultgemma-the-worlds-most-capable-differentially-private-llm/)）。这说明大模型可以做到可证明的隐私，但目前仍有明显的效用代价。不使用差分隐私时，常见的缓解措施是训练数据去重、过滤个人信息和输出过滤，它们能降低风险，但不提供可证明的保证。\n\n## 防御选择对照\n\n| 风险 | 部署方可以做的 | 模型开发方可以做的 |\n|---|---|---|\n| 越狱 | 输入输出分类器（Llama Guard 等）、限制使用场景、记录与限流、持续红队测试 | 安全训练、宪法分类器、对抗训练、发布前红队测试 |\n| 对抗样本 | 输入预处理、多模型交叉检查、关键决策人工复核 | 对抗训练、认证鲁棒性方法 |\n| 投毒与后门 | 从可信来源获取权重并核对哈希、记录微调数据来源 | 数据来源管理、过滤与去重、后门测试 |\n| 训练数据泄露 | 不把敏感数据放进微调集；对输出做个人信息过滤 | 去重、个人信息过滤、差分隐私训练 |\n| 生成内容溯源 | 使用提供方的水印或内容凭证 | 嵌入水印并提供检测工具 |\n\n## 动手试试\n\n1. **复现 GCG**：在有 GPU 的机器上用 [llm-attacks](https://github.com/llm-attacks/llm-attacks) 对一个 7B 开源模型做单请求攻击，记录迭代次数；再加上困惑度检测，观察生成的后缀能否被识别。（本课未运行 GCG：需要 GPU 与模型权重，本机只有 CPU。）\n2. **自动化红队**：用 [garak](https://github.com/NVIDIA/garak) 或 [promptfoo](https://www.promptfoo.dev/docs/red-team/) 对自己部署的模型跑越狱探针，同时统计一组正常请求的误拒率。\n3. **对抗训练权衡**：修改 `fgsm_demo.py`，把对抗训练的 ε 改为 0.2，或把 FGSM 换成多步 PGD，比较干净准确率与各 ε 下的鲁棒准确率。\n4. **水印参数**：改变 `watermark_demo.py` 中的 γ 和 δ，画出检测所需 token 数与替换比例的关系；再用 Transformers 的 SynthID-Text 在一个小模型上生成并检测水印。\n5. **隐私预算**：在 `dp_mia_demo.py` 中改变噪声系数 σ、裁剪范数 C 和训练轮数，画出 ε、测试准确率与金丝雀 AUC 的关系。\n\n相关算法卡片：[对抗样本（FGSM）](/learn/algorithms/adversarial-examples)、[GCG 通用越狱攻击](/learn/algorithms/gcg-jailbreak)、[自动化红队](/learn/algorithms/red-teaming)、[潜伏后门与欺骗性对齐](/learn/algorithms/sleeper-agents)、[大模型文本水印](/learn/algorithms/watermarking)、[成员推断攻击](/learn/algorithms/membership-inference)、[差分隐私 SGD](/learn/algorithms/dp-sgd)、[宪法式 AI / RLAIF](/learn/algorithms/constitutional-ai)。"
    }
  }
}