Skip to content
Evaluation, safety and interpretability Advanced 34 min read

Red-teaming and dangerous-capability evals

Red-teaming asks "can this system be made to do harm?"; dangerous-capability evaluation asks "how much harm could it do if it were?". Both are searches for the worst case rather than measurements of the average case. The one idea to walk away with: a red team can prove a system unsafe with a single example but can never prove it safe, so everything in this field is about making the search strong enough, and the statistics honest enough, that "we found nothing" means something.

10,000 ft

Benchmarks measure what a model does on typical inputs. Safety needs the tail: the one prompt in a million that extracts weapon instructions, the agent run that deletes the database, the capability the model has but does not show unless pushed. This page covers the two disciplines built for the tail. Red-teaming stress-tests a system's safeguards with adversarial inputs, from hand-written jailbreaks to optimisation attacks and automated attacker models. Dangerous-capability evaluations estimate the upper bound of what a model could do in high-stakes domains (biological and chemical weapons, cyber-offence, autonomous AI research) and feed "if-then" commitments in frontier labs' safety frameworks and in law (governance). They are the empirical arm of alignment; their engineering cousins are guardrails and prompt-injection defence and adversarial robustness.

2,000 ft

The modern evaluation pipeline runs from a threat model to a deployment decision:

From threat model to deployment decision
From threat model to deployment decision. Threat model who, what harm, what uplift, Elicit the maximum fine-tune, scaffold, tools, best-of-k, Evaluate, automated evals (benchmarks, agents), human red team + uplift trials, Compare with pre-set thresholds, Safeguards classifiers, security, access, Attack the safeguards (adversarial red team), Deploy + monitor, threshold crossed, patch, below threshoFrom threat model to deployment decision. Threat model who, what harm, what uplift, Elicit the maximum fine-tune, scaffold, tools, best-of-k, Evaluate, automated evals (benchmarks, agents), human red team + uplift trials, Compare with pre-set thresholds, Safeguards classifiers, security, access, Attack the safeguards (adversarial red team), Deploy + monitor, threshold crossed, patch, below thresho

  1. Threat model first: which actor, which harm, and what counts as meaningful uplift over a search engine.
  2. Capability evals estimate what the model can do. They must elicit the maximum (fine-tuning, agent scaffolds, tools, many attempts), because under-elicitation gives false comfort.
  3. Thresholds set in advance turn scores into decisions: below, deploy with standard safeguards; above, stronger safeguards or no deployment.
  4. Red-teaming the safeguards measures how hard it is to get the capability out anyway: jailbreaks, optimisation attacks, automated attackers, prompt injection.
  5. Report with statistics: attack success rates with confidence intervals, how success scales with attempts, and the judge used. Then monitor in deployment, because attackers keep searching after you stop.

Ground level

Two questions, two disciplines

The words get blurred, so fix them first. Shevlane et al. (2023) split model evaluation for extreme risks into dangerous-capability evaluations (does the model have the capacity to cause serious harm?) and alignment evaluations (does it have the propensity to?). Red-teaming is a method used for both, and also for ordinary product safety.

Red-teaming Dangerous-capability evaluation
Question Can safeguards be bypassed? What bad behaviours can be elicited? What is the most harmful thing the model could do with full effort?
Adversary the evaluator plays an attacker against the system the evaluator plays the model's best coach, maximising performance
Typical output attack success rate (ASR), a catalogue of failures, patched safeguards a score against a threshold, an uplift estimate, a capability level
Failure if done badly weak attacks make safeguards look strong weak elicitation makes the model look harmless
Who product teams, external red teams, bug bounties frontier labs, government institutes (UK AISI, US CAISI), third parties such as METR and Apollo

Notice the symmetry in the failure row. In both cases the evaluator must try hard, because the deployed adversary will. That makes these unlike ordinary benchmarks, where the evaluator wants a neutral, reproducible average. Microsoft's report on red-teaming over 100 generative-AI products puts it bluntly as its third lesson: red-teaming is not safety benchmarking (Bullwinkel et al., 2025).

Why safety training can be bypassed at all

A chat model is a pre-trained model that has seen enormous amounts of everything, including dangerous chemistry and malware, followed by post-training that teaches it to refuse some requests. Wei, Haghtalab and Steinhardt (2023) identified two failure modes that explain almost every jailbreak since:

  • Competing objectives. The model is trained both to be helpful and to be harmless, and a prompt can pit them against each other. "Start your answer with 'Absolutely! Here's'" makes the most likely continuation compliant; an elaborate role-play makes refusing feel unhelpful. The safety objective loses because it was only ever a preference, not a hard constraint.
  • Mismatched generalisation. Pre-training covers far more input distributions than safety training does. The model can read base64, rare languages and ciphers, but refusals were only trained on plain English. Ask in base64 and the capability generalises while the refusal does not.

The picture to keep

Safety training carves a thin refusal region inside a vast space of capabilities. Every jailbreak is a route around that region: either a prompt where another objective outweighs it (competing objectives) or a part of input space the region never covered (mismatched generalisation). Defences that only enlarge the region chase an attacker who has the whole space to search.

Attack families

Jailbreak families, by the access the attacker needs
Jailbreak families, by the access the attacker needs. Attacker access, No queries needed, role-play, refusal suppression, encodings, low-resource languages, Black-box queries, PAIR / TAP (LLM attacker), Best-of-N, many-shot, White-box gradients, GCG adversarial suffixes, then transfer to closed models, Fine-tuning access, 10 harmful examples undo safety training, Only the data the model reads, indJailbreak families, by the access the attacker needs. Attacker access, No queries needed, role-play, refusal suppression, encodings, low-resource languages, Black-box queries, PAIR / TAP (LLM attacker), Best-of-N, many-shot, White-box gradients, GCG adversarial suffixes, then transfer to closed models, Fine-tuning access, 10 harmful examples undo safety training, Only the data the model reads, ind
Attack Mechanism Headline result
Hand-crafted (role-play, "DAN", refusal suppression, prefix injection, base64) competing objectives and mismatched generalisation Wei et al. (2023) designed attacks from these two failure modes that succeeded on every prompt in a collection of unsafe requests drawn from GPT-4's and Claude v1.3's own red-teaming sets
GCG (Zou et al., 2023) greedy coordinate search over a token suffix, guided by gradients, to maximise the probability that the reply begins "Sure, here is…" suffixes optimised on open Vicuna models transferred to ChatGPT, Bard, Claude and LLaMA-2-Chat
PAIR (Chao et al., 2023), TAP (Mehrotra et al., 2023) an attacker LLM iteratively rewrites the request using the target's replies; TAP adds tree search and pruning PAIR often needs fewer than twenty queries
Many-shot jailbreaking (Anil et al., 2024) fill a long context with hundreds of fake dialogues in which an assistant complies effectiveness follows a power law in the number of shots, up to hundreds
Best-of-N (Hughes et al., 2024) resample random augmentations (capitalisation, character noise) until one gets through 89% ASR on GPT-4o and 78% on Claude 3.5 Sonnet with 10,000 augmented prompts; success grows power-law-like in \(N\)
Fine-tuning attacks (Qi et al., 2023) fine-tune a safety-trained model on a few harmful examples 10 examples, under USD 0.20 of API fine-tuning, removed GPT-3.5 Turbo's guardrails; even benign fine-tuning degraded safety
Indirect prompt injection (Greshake et al., 2023) plant instructions in content the model will read (a web page, an email, a document) the attacker never talks to the model; the victim's own agent carries out the attack

Two lessons hide in the table. First, access is the main variable: open weights admit gradient attacks and fine-tuning, which no amount of refusal training can stop, which is why the release decision for weights is itself a safety decision. Second, cheap stochastic attacks are underrated. Best-of-N needs no cleverness at all, only patience, and its success comes from the fact that a model's refusal is a probability, not a wall.

Automated red-teaming

Human red-teamers are creative but slow and expensive. Perez et al. (2022) showed a language model can red-team another: generate test prompts at scale, run them, and classify the responses. PAIR and TAP close the loop so the attacker learns from each failure:

Automated red-teaming: the attacker–target–judge loop
Automated red-teaming: the attacker–target–judge loop. Harmful goal (from a taxonomy), Attacker LLM proposes a prompt, Target model (+ its safeguards), Judge refused? harmful? useful?, Findings ASR, transcripts, prompt, response, score + response: refine the attack, successAutomated red-teaming: the attacker–target–judge loop. Harmful goal (from a taxonomy), Attacker LLM proposes a prompt, Target model (+ its safeguards), Judge refused? harmful? useful?, Findings ASR, transcripts, prompt, response, score + response: refine the attack, success

Automation buys coverage; humans still find the novel classes of failure. Ganguli et al. (2022) released 38,961 human red-team attacks on models of 2.7B, 13B and 52B parameters and found that RLHF models became harder to red-team as they scaled, while plain, prompted and rejection-sampled models showed a flat trend. Microsoft's lessons paper makes the same split: automation broadens coverage, humans remain essential. Open tools now package the loop: Microsoft's PyRIT, NVIDIA's garak and promptfoo for product teams, and the UK AI Security Institute's Inspect framework for evaluations of every kind.

Measuring a jailbreak honestly

An attack success rate is a ratio of two things, and both are slippery.

The numerator depends on the judge. Does a reply count as a success if it does not refuse? If it contains harmful content? If that content would actually help? Souly et al. (2024) built StrongREJECT after finding that existing automated graders significantly overstate jailbreak effectiveness compared with human judgement, and documented a twist: jailbreaks that bypass safety training tend to reduce the model's capability, so many "successful" jailbreaks produce compliant but useless answers. A credible ASR states the judge and scores harmfulness and usefulness.

The denominator depends on the request set and the attempt budget. HarmBench (Mazeika et al., 2024) standardised this, comparing 18 red-teaming methods against 33 target models and defences on one set of behaviours with one judge; JailbreakBench maintains a leaderboard and an artefact repository. Without such standards, ASRs from different papers are not comparable.

Then the statistics. A red-team run is a binomial experiment, and small runs carry wide intervals. From the first snippet in Build it:

Result Point ASR 95% interval (Wilson)
0 / 50 0% 0% – 7.1%
0 / 300 0% 0% – 1.3%
3 / 100 3% 1.0% – 8.5%
30 / 1,000 3% 2.1% – 4.3%
12 / 40 30% 18% – 45%

"Zero successes in 50 attempts" is consistent with a true ASR of 7%. The rule of three gives a quick one-sided bound: zero successes in \(n\) trials puts the 95% upper limit at about \(3/n\). And detecting a change from 2% to 4% ASR between two model versions at the usual 5% significance and 80% power needs about 1,140 prompts per model. Most published comparisons use far fewer.

Finally, attempts. An attacker gets more than one try. If a fraction of requests have a small per-attempt success probability, the success rate climbs steadily with the number of attempts \(N\):

25% 50% 75% 100% 1 10 100 1,000 10,000 single-attempt ASR: 1.3% ASR(N) = 1 − E[(1 − p)ᴺ] curve: exact; circles: simulation N attempts per request (random augmentations, log scale) attack success rate
A population of 500 harmful requests whose per-attempt success probability is heterogeneous (Beta(0.4, 30)). The single-attempt ASR is 1.3%; with 10,000 attempts per request it is 90%. The tail 1 − ASR(N) falls as a power law, N to the −0.4. Curve from the exact formula, circles from simulation (second snippet in Build it).

This is one simple model of the Best-of-N result: a reported single-attempt ASR says almost nothing about an attacker with a budget. Report ASR as a function of attempts, or at the attempt budget your threat model assumes. The sampling temperature matters for the same reason: a refusal that holds under greedy decoding can fail one sample in a hundred at temperature 1.

Defences, and what they actually buy

Defence in depth: each layer catches what the last missed
Defence in depth: each layer catches what the last missed. User or retrieved content, Input classifier + rate limits, Safety-trained model + instruction hierarchy, Output classifier (streaming), Monitoring account-level review, bans, ResponseDefence in depth: each layer catches what the last missed. User or retrieved content, Input classifier + rate limits, Safety-trained model + instruction hierarchy, Output classifier (streaming), Monitoring account-level review, bans, Response
  • Safety training (RLHF, Constitutional AI, adversarial training on discovered jailbreaks). Necessary, never sufficient, for the reasons above.
  • Instruction hierarchy (Wallace et al., 2024). Train the model to treat system, user and third-party text with different privileges and to ignore lower-privileged instructions that conflict with higher ones. Applied to GPT-3.5 it improved robustness considerably, including to attack types not seen in training, with minimal capability loss. This is the main model-level defence against prompt injection (guardrails).
  • Classifiers around the model. Anthropic's Constitutional Classifiers (Sharma et al., 2025) train input and output classifiers on synthetic data generated from a written constitution of allowed and disallowed content. In a bug-bounty with over 3,000 estimated hours of red-teaming, no red-teamer found a universal jailbreak against a prototype guarding against chemical, biological, radiological and nuclear (CBRN) queries; an updated version cost an absolute 0.38% increase in refusals on production traffic and 23.7% inference overhead. Note what the result claims: no universal jailbreak found in that test, not that no jailbreak exists.
  • Monitoring and response. Real attackers iterate across many requests. Account-level review, rate limits and the ability to patch classifiers quickly matter as much as any single layer.
  • Weight security and access control, for capabilities that must not leak: no defence above survives an attacker who has the weights.

Adaptive attacks

A defence evaluated only against existing attacks is not evaluated. The adversarial-examples literature learned this the hard way: Athalye, Carlini and Wagner (2018) broke most of a year's published image defences by designing attacks for each defence (robustness). For LLM defences, the honest test is a red team that knows how the defence works and has time.

Dangerous-capability evaluations

The second discipline asks a different question: not "will it refuse?" but "if nothing stopped it, could it meaningfully help cause catastrophic harm, or act dangerously on its own?". The domains that recur across labs' frameworks and government evaluators:

Domain What is measured Representative evaluations
Biological and chemical knowledge and, more importantly, practical uplift to a novice or expert attempting weapons work WMDP (Li et al., 2024): 3,668 multiple-choice questions in biosecurity, cybersecurity and chemical security, built as a proxy for hazardous knowledge; expert-designed uplift trials comparing people with and without model access
Cyber-offence finding and exploiting vulnerabilities end to end Cybench (Zhang et al., 2024): 40 professional capture-the-flag tasks from four competitions; without guidance, agents solved only tasks that took the fastest human teams up to 11 minutes
Autonomy and AI R&D long-horizon agentic work, especially automating AI research METR's time horizon (Kwa et al., 2025): the length of tasks, in human time, that a model completes with 50% reliability, about 50 minutes for Claude 3.7 Sonnet in early 2025 and doubling roughly every seven months since 2019; RE-Bench (Wijk et al., 2024): seven ML research-engineering environments, where top agents scored 4× human experts at a 2-hour budget but humans pulled ahead at 8 hours and reached 2× the agents' score at 32; MLE-bench, PaperBench
Persuasion and manipulation shifting beliefs or behaviour in high-stakes settings added as a Critical Capability Level in Google DeepMind's 2025 Frontier Safety Framework
Self-proliferation, situational awareness acquiring resources, copying itself, knowing it is being evaluated Phuong et al. (2024) piloted evaluations of persuasion, cyber, self-proliferation and self-reasoning on Gemini 1.0: no strong dangerous capabilities, but early warning signs
Scheming and sabotage covertly pursuing goals, undermining oversight, sandbagging Apollo's in-context scheming suite; Anthropic's sabotage evaluations (Benton et al., 2024); see alignment

The hard methodological question is elicitation. A capability evaluation is a lower bound on what the model can do; its value as a safety argument depends on how close to the upper bound it gets. Common sources of under-elicitation: a weak agent scaffold, no tools, too few tokens or attempts, refusals that a fine-tune would remove (which matters for open weights), and prompts that a modest amount of engineering would improve. Labs therefore evaluate "helpful-only" variants without refusal training, fine-tune on the task, and give the model the best scaffolding they have.

Then there is the adversarial version of under-elicitation: sandbagging, a model strategically underperforming. Van der Weij et al. (2024) showed GPT-4 and Claude 3 Opus can be prompted to underperform selectively on dangerous-capability questions while keeping general performance, and that models can be fine-tuned to hide capabilities unless given a password, with the behaviour generalising to WMDP. Combined with the rise of verbalised evaluation awareness reported in 2025 scheming studies, this is why mature capability evaluation now includes fine-tuning-based elicitation (much harder to sandbag through) and interpretability checks.

From scores to decisions: frontier safety frameworks

A number only matters if it triggers something. The dominant structure is the if-then commitment: if a model crosses a pre-defined capability threshold, then specific safeguards must be in place before training further or deploying. As of October 2026:

  • Anthropic's Responsible Scaling Policy. Versions 1–2 defined AI Safety Levels (ASLs). In May 2025 Anthropic activated ASL-3 protections (stronger weight security and CBRN-focused deployment safeguards, including constitutional classifiers) for Claude Opus 4 as a precaution, because it could not rule out that the model needed them. Version 3.0 (24 February 2026) was a comprehensive rewrite introducing periodic Risk Reports and a Frontier Safety Roadmap; version 3.4 took effect on 8 July 2026.
  • OpenAI's Preparedness Framework, version 2 (15 April 2025): three tracked categories (biological and chemical, cybersecurity, AI self-improvement), each with "High" and "Critical" capability thresholds, plus research categories such as long-range autonomy and sandbagging.
  • Google DeepMind's Frontier Safety Framework, version 3 (September 2025, revised as 3.1 in April 2026): Critical Capability Levels including a harmful-manipulation level, protocols for misaligned models that resist shutdown or modification, and safety-case reviews extended to large internal deployments.

The argument that connects evaluations to a deployment decision is increasingly written as a safety case: a structured argument, with evidence, that a system is safe enough in a given context. Clymer et al. (2024) group the possible arguments into four kinds: inability (the model cannot do the harmful thing; dangerous-capability evals), control (it could, but our safeguards stop it; red-teaming of safeguards), trustworthiness (it could, but it will not; alignment evaluations, interpretability) and deference (credible AI advisers vouch for it). Inability arguments are the only mature ones today, which is why capability evaluation carries so much weight, and why under-elicitation is the failure that matters most.

Governments run evaluations too. The UK AI Security Institute and the US Center for AI Standards and Innovation (CAISI) conduct pre-deployment testing of frontier models under agreements with developers, and the EU AI Act requires providers of general-purpose models with systemic risk to evaluate them, including adversarial testing (governance).

History

Where red-teaming came from

The term comes from Cold War military exercises, where a "red" team played the adversary, and entered computing through penetration testing. 2013–2014: adversarial examples (Szegedy et al.; Goodfellow et al.) show image classifiers can be fooled by imperceptible perturbations, founding adversarial ML. 2022: Perez et al. use language models to red-team language models; Anthropic releases 38,961 human red-team attacks (Ganguli et al.); ChatGPT launches and "DAN"-style jailbreaks spread on social media within weeks. 2023: Wei et al. explain why jailbreaks work; GCG shows automated, transferable attacks; the Frontier Model Forum, the White House voluntary commitments and the Bletchley summit make pre-deployment red-teaming a public expectation; Anthropic publishes the first RSP and OpenAI the first Preparedness Framework; Shevlane et al. define dangerous-capability evaluation; the UK and US found AI safety institutes. 2024: HarmBench and StrongREJECT standardise measurement; many-shot and Best-of-N jailbreaks; METR, Apollo and the institutes run pre-deployment evaluations; Cybench, RE-Bench and WMDP. 2025: Constitutional Classifiers; Anthropic activates ASL-3; METR's time-horizon metric; the UK institute is renamed the AI Security Institute and the US one becomes CAISI. 2026: frameworks enter their third generations, and the EU AI Act's obligations for systemic-risk models are in force.

First principles

The asymmetry. Showing a system is unsafe needs one example; showing it is safe needs a universal statement over an input space of, for a 1,000-token prompt and a 100,000-token vocabulary, \(10^{5000}\) possibilities. No search covers that. Red-teaming therefore produces evidence that the remaining failure rate is low under a stated threat model, never proof. Read every red-team report as "the best attacks we tried, with the effort we spent, found this", and ask whether a real adversary would try harder.

Attackers adapt; tests do not. A benchmark of known jailbreaks measures robustness to yesterday's attacks. Defences that are trained on a fixed attack set overfit to it (the Goodhart dynamic of the alignment page), so evaluation must include adaptive attacks designed against the defence.

Capability is a lower bound; safety is a claim about an upper bound. Every capability evaluation measures what the model did under your elicitation, which is at most what it can do. Safety arguments built on inability need the gap between "did" and "could" to be small, which is why elicitation effort (fine-tuning, scaffolding, attempts) is the main determinant of an evaluation's value, and why sandbagging and evaluation awareness strike at the foundation.

Stochasticity changes the unit of analysis. Language models sample. A per-request refusal probability of 99% is a 1% leak per attempt, and an attacker with \(N\) attempts sees \(1-0.99^N\). Thresholds and reports must be stated per attempt budget, not per prompt.

Uplift, not knowledge, is the harm. For weapons domains, the question is not whether the model can state a fact found in a textbook but whether it materially increases a real actor's chance of success over what they could already do. That is why the most informative evaluations are controlled uplift trials with human participants, and why multiple-choice proxies such as WMDP are screening tools, not conclusions.

The maths

Confidence interval for an attack success rate. With \(k\) successes in \(n\) independent attempts, the Wilson score interval inverts the normal-approximation test \(|\hat p - p| \le z\sqrt{p(1-p)/n}\) for \(p\) (rather than plugging in \(\hat p\), which collapses to zero width when \(k=0\)):

\[ p \in \frac{\hat p + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}, \qquad \hat p = k/n,\; z = 1.96 \text{ for 95\%}. \]

The rule of three. If the true rate is \(p\), the chance of zero successes in \(n\) attempts is \((1-p)^n\). The largest \(p\) still consistent with observing zero at the 5% level solves \((1-p)^n = 0.05\), so \(p = 1 - 0.05^{1/n} \approx -\ln(0.05)/n = 2.996/n \approx 3/n\).

Sample size to compare two systems. To detect a change from rate \(p_1\) to \(p_2\) with a two-sided test at level \(\alpha\) and power \(1-\beta\), each arm needs

\[ n = \frac{\left(z_{1-\alpha/2}\sqrt{2\bar p(1-\bar p)} + z_{1-\beta}\sqrt{p_1(1-p_1) + p_2(1-p_2)}\right)^2}{(p_1-p_2)^2}, \qquad \bar p = \tfrac{p_1+p_2}{2}. \]

For 2% versus 4%, \(n\approx1{,}140\). Halving the effect quadruples \(n\).

Why attack success grows like a power law in attempts. Let request \(i\) have per-attempt success probability \(p_i\), drawn from a population distribution. With \(N\) independent attempts the request is broken with probability \(1-(1-p_i)^N\), so the population ASR is

\[ \mathrm{ASR}(N) = 1 - \mathbb E_p\big[(1-p)^N\big]. \]
Derivation: the Beta model gives a power-law tail

Take \(p\sim\mathrm{Beta}(a,b)\), density \(p^{a-1}(1-p)^{b-1}/B(a,b)\). Then

\[ \mathbb E[(1-p)^N] = \frac{1}{B(a,b)}\int_0^1 p^{a-1}(1-p)^{b+N-1}\,dp = \frac{B(a,\,b+N)}{B(a,b)} = \frac{\Gamma(a+b)}{\Gamma(b)}\cdot\frac{\Gamma(b+N)}{\Gamma(a+b+N)} . \]

For large \(N\), \(\Gamma(x+N)/\Gamma(x+a+N)\approx N^{-a}\), so

\[ 1-\mathrm{ASR}(N) \approx \frac{\Gamma(a+b)}{\Gamma(b)}\,N^{-a}. \]

The unbroken fraction decays as a power law with exponent \(a\), the shape parameter that controls how much probability mass sits near \(p=0\). Small \(a\) (many very hard requests) means slow decay; but any \(a>0\) means that every request is eventually broken. Snippet 2 fits a log-log slope of \(-0.378\) for \(N\ge100\) against the asymptotic \(-0.4\); the gap is the \(b=30\) offset in \(\Gamma(b+N)\).

The model is a deliberate simplification (attempts are not truly independent, and real attacks adapt), but it captures why a 1% single-attempt ASR and a 90% ASR at 10,000 attempts can describe the same system.

The GCG objective. Given a harmful request \(x_{1:n}\) with an adversarial suffix occupying positions \(\mathcal I\), and a target affirmative prefix \(x^\star_{n+1:n+H}\) ("Sure, here is…"), GCG minimises

\[ \mathcal L(x_{1:n}) = -\log p_\theta\big(x^\star_{n+1:n+H}\,\big|\,x_{1:n}\big) \]

over the discrete tokens \(x_i,\ i\in\mathcal I\). Represent token \(x_i\) as a one-hot vector \(\mathbf e_{x_i}\in\{0,1\}^{|V|}\). The gradient \(\nabla_{\mathbf e_{x_i}}\mathcal L\in\mathbb R^{|V|}\) is a first-order estimate of how the loss changes if position \(i\) is swapped to each vocabulary token. Because the model is non-linear, that estimate is only a proposal: GCG takes the top-\(k\) most negative entries per position, samples a batch of single-token substitutions from them, evaluates each exactly with a forward pass, and keeps the best. Summing \(\mathcal L\) over several requests and several open models gives a suffix that is universal (works across requests) and tends to transfer (works on models never queried), because models trained on similar data share similar vulnerabilities. Snippet 3 runs the same propose-then-verify loop on a toy linear filter.

Build it

1. Statistics for red-team results (NumPy):

import numpy as np

def wilson(k, n, z=1.96):
    """95% Wilson score interval for a success rate k/n."""
    p = k / n
    centre = (p + z*z/(2*n)) / (1 + z*z/n)
    half = z * np.sqrt(p*(1-p)/n + z*z/(4*n*n)) / (1 + z*z/n)
    return centre - half, centre + half

# Attack success rate (ASR) reports from a red-team run
for k, n in [(0, 50), (0, 300), (3, 100), (30, 1000), (12, 40)]:
    lo, hi = wilson(k, n)
    print(f"{k:3d}/{n:<5d} ASR {k/n:6.1%}   95% CI [{lo:6.2%}, {hi:6.2%}]")

# Rule of three: zero successes in n trials -> 95% upper bound ~ 3/n
for n in [50, 300, 3000]:
    exact = 1 - 0.05 ** (1 / n)
    print(f"0/{n}: exact 95% upper bound {exact:.4f}, rule of three {3/n:.4f}")

# How many prompts to tell a 2% ASR from a 4% ASR (two-sided, 5% level, 80% power)?
p1, p2, za, zb = 0.02, 0.04, 1.96, 0.84
pbar = (p1 + p2) / 2
n = (za*np.sqrt(2*pbar*(1-pbar)) + zb*np.sqrt(p1*(1-p1) + p2*(1-p2)))**2 / (p1-p2)**2
print(f"prompts per model to detect 2% vs 4%: {int(np.ceil(n))}")
  0/50    ASR   0.0%   95% CI [ 0.00%,  7.14%]
  0/300   ASR   0.0%   95% CI [ 0.00%,  1.26%]
  3/100   ASR   3.0%   95% CI [ 1.03%,  8.45%]
 30/1000  ASR   3.0%   95% CI [ 2.11%,  4.25%]
 12/40    ASR  30.0%   95% CI [18.07%, 45.43%]
0/50: exact 95% upper bound 0.0582, rule of three 0.0600
0/300: exact 95% upper bound 0.0099, rule of three 0.0100
0/3000: exact 95% upper bound 0.0010, rule of three 0.0010
prompts per model to detect 2% vs 4%: 1140

The Wilson upper limit for 0/50 (7.1%) is above the rule-of-three figure (5.8% exact) because Wilson is a two-sided interval with 2.5% in each tail; the rule of three is one-sided.

2. Attack success versus attempts (NumPy). Heterogeneous requests, many attempts each:

import numpy as np
from math import lgamma
rng = np.random.default_rng(0)
betaln = np.vectorize(lambda x, y: lgamma(x) + lgamma(y) - lgamma(x + y))

# 500 harmful requests. Each has its own per-attempt jailbreak probability p_i,
# heterogeneous across requests: p ~ Beta(a, b). Most requests are hard (p tiny).
a, b, M = 0.4, 30.0, 500
p = rng.beta(a, b, M)

Ns = np.array([1, 10, 100, 1_000, 10_000])
sim = []
for N in Ns:                                   # attack each request with N random augmentations
    hits = rng.random((M, 1)) < 1 - (1 - p[:, None]) ** N   # P(at least one success in N)
    sim.append(hits.mean())
# Exact expectation: ASR(N) = 1 - E[(1-p)^N] = 1 - B(a, b+N) / B(a, b)
exact = 1 - np.exp(betaln(a, b + Ns) - betaln(a, b))

print("     N   ASR(sim)  ASR(exact)  1-ASR")
for N, s, e in zip(Ns, sim, exact):
    print(f"{N:6d}   {s:7.3f}    {e:7.3f}   {1-e:6.3f}")

# Tail is a power law: 1 - ASR(N) ~ C * N^(-a) for large N
slope = np.polyfit(np.log(Ns[2:]), np.log(1 - exact[2:]), 1)[0]
print(f"log-log slope of (1-ASR) for N >= 100: {slope:.3f}   (theory: -a = {-a})")
print(f"single-attempt ASR = mean p = {p.mean():.4f};  share of requests with p < 1e-3: {(p < 1e-3).mean():.2f}")
     N   ASR(sim)  ASR(exact)  1-ASR
     1     0.010      0.013    0.987
    10     0.094      0.110    0.890
   100     0.440      0.445    0.555
  1000     0.768      0.758    0.242
 10000     0.920      0.903    0.097
log-log slope of (1-ASR) for N >= 100: -0.378   (theory: -a = -0.4)
single-attempt ASR = mean p = 0.0131;  share of requests with p < 1e-3: 0.26

A quarter of the requests have a per-attempt success probability below one in a thousand, yet 90% fall within 10,000 attempts.

3. A greedy coordinate attack on a safety filter, and transfer (NumPy). Two bag-of-words logistic-regression "harmfulness filters" are trained on different data. The attacker appends a suffix and optimises it against filter A only, using the gradient to propose candidate tokens and exact evaluation to choose:

import numpy as np
rng = np.random.default_rng(0)
V, L = 400, 12                          # vocabulary size, prompt length
harm = np.zeros(V); harm[:15] = 1       # tokens 0..14 are "harmful" words
style = rng.normal(0, 1, V)             # tokens differ in how often benign chat uses them

def dataset(n):
    X = np.zeros((n, V)); y = rng.integers(0, 2, n)
    for i in range(n):
        w = np.exp(style - 3 * harm); w /= w.sum()      # benign word distribution
        toks = rng.choice(V, L, p=w)
        if y[i]: toks[:2] = rng.choice(15, 2)           # harmful prompts contain harmful words
        np.add.at(X[i], toks, 1)
    return X / L, y                                      # bag of words, length-normalised

def train(X, y, steps=2000, lr=5.0):                    # logistic-regression "safety filter"
    w, b = np.zeros(V), 0.0
    for _ in range(steps):
        g = 1 / (1 + np.exp(-(X @ w + b))) - y
        w -= lr * (X.T @ g / len(y) + 1e-4 * w); b -= lr * g.mean()
    return w, b

A = train(*dataset(3000)); B = train(*dataset(3000))     # two filters, different data
Xt, yt = dataset(2000)
for name, f in [("A", A), ("B", B)]:
    print(f"filter {name}: test accuracy {(((Xt @ f[0] + f[1]) > 0) == yt).mean():.3f}")
score = lambda f, toks: 1 / (1 + np.exp(-(np.bincount(toks, minlength=V) / len(toks) @ f[0] + f[1])))

prompt = np.array([3, 7] + list(rng.choice(np.arange(15, V), 10)))   # a harmful request
print(f"no suffix:                      P(harmful) A={score(A, prompt):.3f}  B={score(B, prompt):.3f}")
for k in [4, 8, 16, 32]:                                # adversarial suffix of k tokens
    suffix = rng.choice(np.arange(15, V), k)
    rand = score(A, np.r_[prompt, suffix])               # baseline: a random benign suffix
    for pos in range(k):                                 # greedy coordinate search against A only
        cands = np.argsort(A[0])[:32]                    # the gradient proposes candidates...
        trials = [score(A, np.r_[prompt, suffix[:pos], c, suffix[pos+1:]]) for c in cands]
        suffix[pos] = cands[int(np.argmin(trials))]      # ...exact evaluation picks the best
    full = np.r_[prompt, suffix]
    print(f"suffix of {k:2d}:  random A={rand:.3f} | optimised A={score(A, full):.3f}  B={score(B, full):.3f}")
filter A: test accuracy 0.996
filter B: test accuracy 0.997
no suffix:                      P(harmful) A=0.768  B=0.757
suffix of  4:  random A=0.681 | optimised A=0.583  B=0.575
suffix of  8:  random A=0.585 | optimised A=0.455  B=0.451
suffix of 16:  random A=0.541 | optimised A=0.316  B=0.317
suffix of 32:  random A=0.471 | optimised A=0.213  B=0.216

Read three things off the output. Both filters are 99.6% accurate on ordinary data, yet an 8-token optimised suffix pushes the request below the 0.5 decision threshold. The optimised suffix beats a random one of the same length, so this is search, not just dilution. And filter B, which the attacker never queried, is fooled almost exactly as much: the two filters learned similar weights from similar data, which is the mechanism behind GCG's transfer to closed models. (For a linear model the gradient with respect to a token's one-hot vector is just that token's weight divided by the length, which is why np.argsort(A[0]) is the gradient proposal.)

Things to try

  • In snippet 1, compute how many prompts you need to claim "ASR below 0.1%" with 95% confidence if you observe zero successes. Then price that red-team run at your model's cost per call.
  • In snippet 2, change \(a\) to 0.1 and to 1.0. How does the attempt budget needed to reach 50% ASR change? What does \(a\) mean about the hardest requests?
  • In snippet 3, train filter B on data from a different style vector (draw a new one). How much does transfer degrade when the training distributions differ?
  • Defend snippet 3: add the optimised suffixes to filter A's training data as harmful examples (adversarial training) and re-attack. Does a fresh attack succeed? With how many more tokens?
  • Run a real evaluation: install Inspect and run one of its published safety evaluations against a small local model, then read the transcript of every "success".

In practice

How to red-team an LLM product you are building, in order:

  1. Write the threat model. Who are the users and attackers, what tools and data can the system touch, and what are the unacceptable outcomes (harmful content, data leakage, unauthorised actions, regulatory breaches)? Microsoft's first lesson: understand what the system can do and where it is applied.
  2. Build a harm taxonomy and seed set. For each outcome, write a few dozen concrete test requests, including borderline ones where refusing would be wrong (over-refusal is a failure too).
  3. Automate the bulk. Expand seeds with an attacker model, run known attack families (garak, PyRIT, promptfoo), and for agents run prompt-injection suites such as AgentDojo (97 tasks, 629 security test cases; Debenedetti et al., 2024).
  4. Bring in humans for depth. Domain experts for the harms that matter most to you, and creative generalists for novel attack classes.
  5. Calibrate the judge. Hand-label a sample of judged transcripts and measure the judge's agreement with you before trusting any ASR it produces.
  6. Report like a scientist. ASR with intervals, per category, per attempt budget; the judge; representative transcripts; what was not tested.
  7. Turn findings into regression tests and rerun them on every model, prompt or tool change. The OWASP Top 10 for LLM applications and MITRE ATLAS are useful checklists for coverage.

In Jarvis

For a financial assistant the harm taxonomy is unusual: alongside the standard categories, the critical failures are regulatory, such as the model giving personalised investment advice in imperative form, inventing a number the planning engine did not compute, or following instructions hidden in an uploaded statement. Those become red-team categories with their own judges and regression suites. See the Jarvis case study.

Common misconceptions

\"We red-teamed it and found nothing, so it is safe.\"

Zero successes in \(n\) attempts bounds the rate at about \(3/n\) for those attacks, that judge and that attempt budget. It says nothing about attacks you did not try. Report the bound, not "safe".

\"A high jailbreak ASR means the model is dangerous.\"

Only if the jailbroken output is actually harmful and useful. StrongREJECT found many jailbreaks produce degraded, low-value answers, and many harmful-content categories add no uplift over a search engine. Pair ASR with a harm-weighted quality score.

\"Capability evals measure what the model can do.\"

They measure what it did under your elicitation: a lower bound. Without fine-tuning, good scaffolding and enough attempts, a dangerous model can score as harmless, and a model that recognises it is being evaluated can score lower on purpose.

\"Open-weight models can be made safe with better refusal training.\"

Fine-tuning access removes refusal training with a handful of examples (Qi et al., 2023). For open weights, the safety question is what the base capabilities enable, not how good the refusals are.

Check yourself

What are the two failure modes of safety training identified by Wei et al., and which does a base64-encoded request exploit?

Competing objectives (helpfulness versus harmlessness pulled against each other) and mismatched generalisation (capabilities cover input distributions that safety training did not). Base64 exploits mismatched generalisation: the model can decode it, but refusals were trained on plain text.

You observe 0 successes in 200 attack attempts. What can you claim?

With 95% confidence the per-attempt ASR is below about \(3/200 = 1.5\%\) (exact \(1-0.05^{1/200} = 1.49\%\)), for that attack distribution, judge and attempt budget. An attacker with 1,000 attempts at a 1.5% per-attempt rate would succeed with probability \(1-0.985^{1000}\approx 1\).

Why does Best-of-N jailbreaking work against a model with a 1% single-attempt ASR?

Because refusal is stochastic per sample and success probabilities are heterogeneous across requests. With \(N\) attempts, the population ASR is \(1-\mathbb E[(1-p)^N]\), which rises towards 1 for any request with \(p>0\); heterogeneous \(p\) gives the power-law-like curve.

In GCG, why is the gradient with respect to the one-hot token only used to propose candidates rather than to choose the substitution directly?

The gradient is a linear approximation of a highly non-linear function of a discrete input; it ranks swaps by their first-order effect, which is often wrong for the actual swap. Exact forward passes on a sampled batch of top-\(k\) proposals find substitutions that genuinely reduce the loss.

Name the four kinds of safety-case argument in Clymer et al. and the evaluation that supports each.

Inability (dangerous-capability evals with strong elicitation), control (red-teaming of safeguards and monitoring, including control evaluations with a red-team model), trustworthiness (alignment and honesty evaluations, interpretability) and deference (trusted AI advisers' judgements, not yet mature).

Why does fine-tuning-based elicitation help against sandbagging?

A model can choose to answer badly when prompted, but supervised fine-tuning on correct answers directly optimises the weights to produce them; a model cannot easily resist gradient updates that reward its hidden capability. If the fine-tuned model performs much better than the prompted one with little data, the capability was there.

Hard: a lab reports its new defence cut ASR from 40% to 2% on a public jailbreak benchmark. List three reasons that number might overstate the defence's robustness.

The attacks were not adaptive (designed without knowledge of the defence); the defence may have been tuned on or near the benchmark's attacks (Goodhart); the judge may score refusals and degraded outputs inconsistently; the attempt budget may be one attempt per request; and the over-refusal cost on benign traffic may not be reported.

Hard: why is uplift, not knowledge, the right target for a biological-weapons evaluation, and why is it hard to measure?

Much relevant knowledge is in textbooks; the harm is the marginal increase in a real actor's probability of success, which depends on tacit, practical, troubleshooting help. Measuring it needs controlled trials with human participants on proxy tasks, which are slow, expensive, ethically constrained and noisy, so labs combine them with cheaper proxies such as WMDP.

Go deeper

Papers

Videos and lectures

Articles and frameworks

Code and tools

Where this leads