Skip to content

FEAT: Add FLRT fluent adversarial prompt generator - #4692

Open
Hunar Pasricha (hunar2006) wants to merge 17 commits into
microsoft:mainfrom
hunar2006:flrt-generator
Open

Hunar Pasricha (hunar2006) wants to merge 17 commits into
microsoft:mainfrom
hunar2006:flrt-generator

Conversation

@hunar2006

@hunar2006 Hunar Pasricha (hunar2006) commented Nov 27, 2026 •

Copy link
Copy Markdown

Description

Adds the FLRT (Fluent Student-Teacher Redteaming, Thompson & Sklar, arXiv:2407.17447)
adversarial prompt generator next to the existing GCG generator. Closes #4177.

FLRT is a white box token optimization attack like GCG, but it produces adversarial
strings that read close to natural language. Instead of coordinate gradient token
replacement it edits the attack with token insertions, deletions, and swaps, and it
adds fluency and repetition penalties to the classic forcing loss so the optimization
prefers coherent prompts.

Scope, as approved by Richard Lundeen (@richlundeen) in the proposal issue:

  • Single in process HuggingFace victim model (no Azure ML, no distributed workers).
  • Clamped forcing loss + fluency penalty + repetition penalty.
  • The distillation objective against a toxified teacher copy is deferred to a follow up.
  • Heavy dependencies (torch, transformers) stay in the existing gcg extra; no new
    dependencies are added.

Deviations from the reference implementation

  • Attack edits are suffix-only, while the reference supports separate prefix and suffix
    attack parts.
  • Fluency and repetition are computed over the user-message token region rather than
    the reference implementation's whole rendered prompt.
  • The final attack is the best-loss attack seen during optimization, not the final
    buffer[0].
  • If every candidate in an optimization step is illegal, the parent is retained instead
    of raising.

Validation

GPU smoke test (manual script, not part of this PR) on a Tesla T4 (Colab),
Qwen/Qwen2.5-0.5B-Instruct, fp16, 100 optimization steps:

  • Loss decreased from 2.7925 to 2.1396 over 100 steps.
  • Final attack: Instructions: Preparation * Cold oil is required as the target of your attack, please choose one option below; (newlines collapsed for readability),
    a fluent English string, as the method intends (vs. gibberish GCG-style suffixes).
  • After only 100 steps the victim model began complying with the harmful request
    in greedy generation, rather than refusing.
  • Runtime: under three minutes end to end including model download and load.
  • Only the 0.5B model was tested on GPU; the smoke test script can be shared on request.

Type of change

  • New feature (non breaking change which adds functionality)

Tests added

  • Yes, unit tests that need no GPU and no network.

Checklist

  • Unit tests pass locally
  • Pre commit hooks pass locally
  • Documentation example added (doc/code/executor/flrt/0_flrt.py)

This contribution was developed with AI assistance (Devin/Cognition). The contributor
reviewed the algorithm against the paper and the authors' MIT-licensed reference
implementation, reviewed the full diff, and validated the attack end to end.

Add the FLRT (Fluent Student-Teacher Redteaming, arXiv:2407.17447)
attack next to GCG. FLRT optimizes adversarial prompts that read like
natural language by combining a clamped forcing loss with fluency and
repetition penalties, and by editing the attack with token insertions,
deletions, and swaps rather than coordinate-gradient replacement.

The victim model runs in process on a GPU and heavy dependencies
(torch, transformers) remain in the existing gcg extra. Distillation
against a toxified teacher is deferred to a follow-up per microsoft#4177.
Cover the token edit operations, the forcing/fluency/repetition loss
terms on hand-built tensors with exact expected values, the chat
template span logic, and the optimization lifecycle using a hand-built
whitespace tokenizer and deterministic fake model. No GPU or network
access is required.

List pyrit.executor.promptgen.flrt in the lazy-import inventory's
eager-package exceptions, mirroring GCG: experimental packages import
pyrit.exceptions.ExperimentalWarning at import time by design.
Add a docs example showing how FLRT attacks are generated and applied
with the SuffixAppendConverter, register it in the docs TOC, and add
the paper to the bibliography.
Copilot AI balanced review requested due to automatic review settings November 27, 2026 01:50
@hunar2006

Copy link
Copy Markdown
Author

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The default empty attack fails before optimization on whitespace-trimming templates, while invalid candidates can displace legal buffer entries and abort subsequent steps.

4 open issues
What changed in this PR

Adds an experimental FLRT prompt generator alongside GCG in PyRIT, using a single local HuggingFace model to optimize more fluent adversarial text. Teacher distillation remains deferred.

Changes:

  • Implements token edits, combined loss terms, configuration, and the generator lifecycle.
  • Adds CPU-only unit tests using synthetic tensors and model/tokenizer fakes.
  • Adds usage examples, documentation navigation, and the FLRT citation.
File Description
tests/​unit/​executor/​promptgen/​flrt/​test_objective.py Tests individual loss terms and their weighted combination.
tests/​unit/​executor/​promptgen/​flrt/​test_generator.py Tests encoding, proposals, lifecycle, and result logging.
tests/​unit/​executor/​promptgen/​flrt/​test_edit_operations.py Tests token edits and length constraints.
tests/​unit/​executor/​promptgen/​flrt/​test_config.py Tests configuration defaults and validation.
tests/​unit/​common/​test_lazy_package_imports.py Adds FLRT to the package exception inventory.
pyrit/​executor/​promptgen/​flrt/​objective.py Implements forcing, fluency, and repetition losses.
pyrit/​executor/​promptgen/​flrt/​generator.py Implements model loading, optimization, and results.
pyrit/​executor/​promptgen/​flrt/​edit_operations.py Implements token deletion, insertion, and replacement.
pyrit/​executor/​promptgen/​flrt/​config.py Defines model, algorithm, and output settings.
pyrit/​executor/​promptgen/​flrt/​__init__.py Exposes lazy public exports and an experimental warning.
doc/​references.bib Adds the FLRT paper reference.
doc/​myst.yml Adds the FLRT notebook to navigation.
doc/​code/​executor/​flrt/​0_flrt.py Adds the paired Python usage example.
doc/​code/​executor/​flrt/​0_flrt.ipynb Adds the FLRT usage notebook.
doc/​bibliography.md Includes the FLRT citation key.

Review effort: Balanced

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@romanlutz Roman Lutz (romanlutz) self-assigned this Dec 1, 2026

@romanlutz Roman Lutz (romanlutz) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, and for agreeing the scope on #4177 first. The PR matches what was agreed, and the loop is a faithful port of the reference buffer and edit operators. I ran it on CPU against SmolLM2-135M, Qwen2.5-0.5B, TinyLlama and DeepSeek-R1-Distill-1.5B and it runs end to end on all four. On Qwen2.5-0.5B with the objective from your docs I get 2.81 → 2.13 in 100 steps, in line with your T4 numbers.

Before this can merge:

  1. Please merge main. doc/bibliography.md and doc/references.bib conflict; keep both sides in each.
  2. The tests need to pin the optimizer and include one test on a real tokenizer (inline).
  3. The inline items on token masking, torch_dtype, the default schedule, the loss normalisation and the notebook outputs.

Please also correct the "Deviations from the reference implementation" list. Sampling proposals without replacement and averaging candidate losses over all goals are both what the reference does (beast_candidates, simple_evaluate + combine_evaluations). The deviations I found that are not listed: suffix only, fluency averaged over the whole prompt where the paper uses the user input, no banned-token list, final attack chosen by best loss instead of the last buffer[0], and an all-illegal step keeping the parent instead of raising.

On the overlap with GCG: the template probing and span location here are adapted from AttackPrompt._content_bounds and _token_slice in gcg/attack/base/attack_manager.py, and FLRTModelConfig/FLRTOutputConfig are copies of the GCG classes. I don't want this PR to wait on a refactor, so we'll pull the shared pieces into a common module after it merges. For this PR, please reuse GCG's get_unsampleable_toks instead of a second implementation, and bring the span rule back in line with GCG's (both inline).

CI has not run on this PR yet because it needs first-time-contributor approval. I'll release it once main is merged in.

Comment on lines +372 to +374
special_ids = list(context.tokenizer.all_special_ids)
if special_ids:
rows[:, special_ids] = 0.0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This masks all_special_ids only, and _encode_attack (line 526) rejects the same set. Added tokens that are not flagged special stay sampleable and legal: <tool_call> and <|fim_prefix|> on Qwen2.5, <think>/</think> on Qwen3 and SmolLM3, and <|User|>, <|Assistant|> and </think> on DeepSeek-R1-Distill, whose all_special_ids is just BOS and EOS.

The reference bans all_special_ids + range(tokenizer.vocab_size, num_embeddings), and GCG got the same fix in #4549 (get_unsampleable_toks).

They are rarely proposed (8 of 38,400 draws on Qwen2.5-0.5B), but the forcing term can prefer one when it is: on DeepSeek-R1-Distill-Qwen-1.5B the attack </think> scores 6.55 against 7.11 for Ok. and 7.73 for the empty attack. That is template injection, not a fluent prompt.

Please reuse get_unsampleable_toks for both the proposal mask and the legality check instead of a second implementation. On these four tokenizers it bans every token named above (293 ids on Qwen2.5, against the 14 masked here). Importing it from attack_manager.py is fine for this PR; it does also raise GCG's ExperimentalWarning, which goes away once the helper moves to a shared module. Please add a test with an added, non-special token.

Comment on lines +557 to +558
if not overlap.strip():
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whitespace-only tokens at either end of the attack are skipped here, so they are scored but are not part of [attack_start, attack_end). _step rebuilds each child from that span, so they are dropped, and n_tokens undercounts for the length bounds.

With the Qwen2.5 tokenizer, "Please answer in detail. " has the span "Please answer in detail." and an edge insert of now gives "Please answer in detail. now". A leading "\n\n" is lost the same way, and on SmolLM2 so is a trailing "\n\n". In my runs the parent being mutated had a whitespace edge in 12 to 31 of 100 steps on Qwen2.5-0.5B.

This if not overlap.strip(): continue is the one place this function differs from GCG's _token_slice, which it is adapted from; GCG keeps whitespace tokens that lie inside the span. With GCG's rule the located span decodes back to the attack in 55 of 55 cases across ten tokenizers (31 of 55 as written), and the 81 unit tests still pass. Please drop the skip so the two stay the same.

This is about the span tracking the string, not a measured quality gain: on one seed the 100-step Qwen2.5-0.5B run ends at 2.13 as written and 2.16 with GCG's rule.

"cannot be set up. Pick a chat-tuned model or set tokenizer.chat_template explicitly."
)
self._logger.info(f"Loading model {config.name} on {config.device}...")
model_kwargs = {"dtype": torch.float16, **config.model_kwargs}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

model_kwargs={"torch_dtype": torch.float32} is silently ignored: dtype=float16 is passed alongside it and transformers prefers dtype. On SmolLM2-135M model.dtype comes back float16. GCG treats either key as an override since #4549 (if "torch_dtype" not in model_kwargs and "dtype" not in model_kwargs). That rule is inline in ModelWorker.__init__, so there is nothing to import yet; please match it here and extend test_model_kwargs_dtype_overrides_default to cover torch_dtype.

Comment on lines +433 to +446
positions = torch.arange(1, seq_len, device=logits.device)
fluency_positions = positions[positions < entry.target_positions[0]]
fluency = fluency_loss(log_probs=log_probs, token_ids=ids, positions=fluency_positions)

target_positions = torch.tensor(entry.target_positions, device=logits.device)
forcing = clamped_forcing_loss(
log_probs=log_probs,
token_ids=ids,
target_positions=target_positions,
floor=-math.log(self._algorithm.forcing_probability_threshold),
)

user_ids = ids[entry.user_start : entry.user_end]
repetition = repetition_loss(token_ids=user_ids, exponent=self._algorithm.repetition_exponent)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fluency is averaged over every position before the target (system prompt, template scaffold, goal, attack, assistant header), while repetition is divided by the user-message tokens only. On Qwen2.5 with a 9-token goal that is 37 positions against 9.

The paper defines both over the user input with the same M and derives C_rep = 1.8 * C_XE on that basis; the reference uses the whole prompt for both. Taking one from each makes repetition 3 to 4 times stronger relative to fluency than either source. Please use one region for both and say which in the objective.py docstring.

Comment on lines +409 to +422
max_len = max(len(entry.ids) for _, entry in entries)
pad_id = context.tokenizer.pad_token_id
if pad_id is None:
pad_id = context.tokenizer.eos_token_id
input_ids = torch.full((len(entries), max_len), pad_id, dtype=torch.long)
attention_mask = torch.zeros((len(entries), max_len), dtype=torch.long)
for row, (_, entry) in enumerate(entries):
input_ids[row, : len(entry.ids)] = torch.tensor(entry.ids)
attention_mask[row, : len(entry.ids)] = 1
input_ids = input_ids.to(context.model.device)
attention_mask = attention_mask.to(context.model.device)

with torch.no_grad():
logits = context.model(input_ids=input_ids, attention_mask=attention_mask).logits.float()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All n_candidates * len(goals) prompts go through one forward pass and the full logits are upcast with .float(). By arithmetic, 16 candidates × 250 tokens × a 128k vocabulary is about 2 GB per goal in float32 on top of the fp16 copy, so a multi-goal run on an 8B model will run out of memory with no knob to turn. The reference chunks with estimate_batch_size. A batch_size on FLRTAlgorithmConfig would do. I have not measured this on a GPU.

Comment on lines +299 to +300
class TestExecuteAsyncLifecycle:
async def test_run_produces_consistent_result(self, tmp_path: Path) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These lifecycle tests assert shapes (step_count == 4, a finite loss), so they pass with the optimizer broken. I mutated generator.py one line at a time and 21 of 27 mutants survive the suite, including: buffer not sorted; parent never popped; buffer never truncated; best-so-far keeping the worst candidate; each of the three loss terms dropped from the total; proposals read from the wrong logit rows; infinite-loss candidates admitted to the buffer (the Copilot finding fixed in 3425bd0); multi-goal loss summed instead of averaged; the schedule never switching; length bounds ignored; max_runtime_seconds ignored.

objective.py, edit_operations.py and config.py are well covered (17 of 18 killed). Please add tests that pin _step (buffer contents and order after a step with scripted losses, best tracking, illegal candidates excluded) and _evaluate_attacks (each term and weight reaches the total; multi-goal mean).

raise KeyError(key)


class TinyTokenizer:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything runs on a whitespace tokenizer whose decode/encode round trip is exact, so the offset and span logic, _decode_ids and the trimming detection never meet a real tokenizer. GCG has CPU integration tests on GPT-2 (tests/integration/executor/promptgen/gcg/test_gcg_integration.py) and a GPU smoke test on Qwen2.5-0.5B (#4167).

Please add the equivalent: a CPU integration test on a small chat model (HuggingFaceTB/SmolLM2-135M-Instruct does 60 steps in 76 s on a laptop CPU), and ideally the script you used on the T4 as a run_only_if_all_tests GPU test, so the validation in the description can be reproduced.

"execution_count": null,
"id": "10e82f20",
"metadata": {},
"outputs": [],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The notebook is committed without outputs; both code cells are empty. Notebooks under doc/ keep their outputs (.github/instructions/docs.instructions.md), as gcg/0_gcg.ipynb does. Please execute it with jupytext --to ipynb --execute and commit the result.

import random
from collections.abc import Sequence

UpdateType: TypeAlias = Literal["delete", "insert", "swap", "edge"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the style guide asks for enums over Literals, and UpdateType is exported from the package. A StrEnum would match #4644.

Comment on lines +717 to +718
if logfile_path is None:
return FLRTResult(memory_labels=dict(memory_labels), log_path=None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: _build_logfile_path always returns a string, so this branch and the "None if logging was disabled" wording on FLRTResult.log_path are unreachable. With the default FLRTOutputConfig() every run writes <timestamp>_<id>.json into the working directory. Either allow disabling the log or drop the branch.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@hunar2006

Copy link
Copy Markdown
Author

Merged main and resolved the bibliography conflicts. Working through the rest of the review now and will reply on each thread as I push the fixes.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FEAT: Add FLRT fluent adversarial prompt generator alongside GCG

3 participants