Repository navigation
FEAT: Add FLRT fluent adversarial prompt generator - #4692
Hunar Pasricha (hunar2006) wants to merge 17 commits into
Conversation
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.
|
@microsoft-github-policy-service agree
…On Thu, Nov 26, 2026 at 7:50 PM microsoft-github-policy-service[bot] < ***@***.***> wrote:
*microsoft-github-policy-service[bot]* left a comment
(microsoft/PyRIT#4692)
<#4692 (comment)>
hunar2006 <https://github.com/hunar2006> please read the following
Contributor License Agreement(CLA). If you agree with the CLA, please reply
with the following information.
@microsoft-github-policy-service agree [company="{your company}"]
Options:
- (default - no company specified) I have sole ownership of
intellectual property rights to my Submissions and I am not making
Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
- (when company given) I am making Submissions in the course of work
for my employer (or my employer has intellectual property rights in my
Submissions by contract or applicable law). I have permission from my
employer to make Submissions and enter into this Agreement on behalf of my
employer. By signing below, the defined term “You” includes me and my
employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement Contribution License Agreement
This Contribution License Agreement (*“Agreement”*) is agreed to by the
party signing below (*“You”*),
and conveys certain license rights to Microsoft Corporation and its
affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is
effective as of the latest signature
date below.
1. *Definitions*.
*“Code”* means the computer software code, whether in human-readable
or machine-executable form,
that is delivered by You to Microsoft under this Agreement.
*“Project”* means any of the projects owned or managed by Microsoft
and offered under a license
approved by the Open Source Initiative (www.opensource.org).
*“Submit”* is the act of uploading, submitting, transmitting, or
distributing code or other content to any
Project, including but not limited to communication on electronic
mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf
of, the Project for the purpose of
discussing and improving that Project, but excluding communication
that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”
*“Submission”* means the Code and any other copyrightable material
Submitted by You, including any
associated comments and documentation.
2. *Your Submission*. You must agree to the terms of this Agreement
before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now
or in the future (except as
described in Section 4 below), Submit to any Project.
3. *Originality of Work*. You represent that each of Your Submissions
is entirely Your original work.
Should You wish to Submit materials that are not Your original work,
You may Submit them separately
to the Project if You (a) retain all copyright and license information
that was in the materials as You
received them, (b) in the description accompanying Your Submission,
include the phrase “Submission
containing materials of a third party:” followed by the names of the
third party and any licenses or other
restrictions of which You are aware, and (c) follow any other
instructions in the Project’s written
guidelines concerning Submissions.
4. *Your Employer*. References to “employer” in this Agreement include
Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a
contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your
employer has intellectual
property rights in Your Submission by contract or applicable law, You
must secure permission from Your
employer to make the Submission before signing this Agreement. In that
case, the term “You” in this
Agreement will refer to You and the employer collectively. If You
change employers in the future and
desire to Submit additional Submissions for the new employer, then You
agree to sign a new Agreement
and secure permission from the new employer before Submitting those
Submissions.
5. *Licenses*.
- *Copyright License*. You grant Microsoft, and those who receive the
Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive,
royalty-free, irrevocable license in the
Submission to reproduce, prepare derivative works of, publicly
display, publicly perform, and distribute
the Submission and such derivative works, and to sublicense any or all
of the foregoing rights to third
parties.
- *Patent License*. You grant Microsoft, and those who receive the
Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive,
royalty-free, irrevocable license under
Your patent claims that are necessarily infringed by the Submission or
the combination of the
Submission with the Project to which it was Submitted to make, have
made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the
Project.
- *Other Rights Reserved*. Each party reserves all rights not
expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without
limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.
6. *Representations and Warranties*. You represent that You are
legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your
original work (except as You may
have disclosed under Section 3). You represent that You have secured
permission from Your employer to
make the Submission in cases where Your Submission is made in the
course of Your work for Your
employer or Your employer has intellectual property rights in Your
Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You
represent and warrant that You
have the necessary authority to bind the listed employer to the
obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless
You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE
WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED
UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO,
ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7. *Notice to Microsoft*. You agree to notify Microsoft in writing of
any facts or circumstances of which
You later become aware that would make Your representations in this
Agreement inaccurate in any
respect.
8. *Information about Submissions*. You agree that contributions to
Projects and information about
contributions may be maintained indefinitely and disclosed publicly,
including Your name and other
information that You submit with Your Submission.
9. *Governing Law/Jurisdiction*. This Agreement is governed by the
laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal
courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in
which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County,
Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.
10. *Entire Agreement/Assignment*. This Agreement is the entire
agreement between the parties, and
supersedes any and all prior agreements, understandings or
communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may
be assigned by Microsoft.
—
Reply to this email directly, view it on GitHub
<#4692?email_source=notifications&email_token=AQQJUARWYICRVNENXXEJUFL53DMXDA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTOMRQG43DCNRZGEZKM4TFMFZW63VHNVSW45DJN5XKKZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#issuecomment-7207616912>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AQQJUAUBE44XNJBEYF4XNIL53DMXDAVCNFSNUABFKJSXA33TNF2G64TZHM3TGMBXGUZTSMBZHNEXG43VMU5TMNRTHAZDONZWGI42C5QC>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
There was a problem hiding this comment.
🟡 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>
Roman Lutz (romanlutz)
left a comment
There was a problem hiding this comment.
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:
- Please merge
main.doc/bibliography.mdanddoc/references.bibconflict; keep both sides in each. - The tests need to pin the optimizer and include one test on a real tokenizer (inline).
- 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.
| special_ids = list(context.tokenizer.all_special_ids) | ||
| if special_ids: | ||
| rows[:, special_ids] = 0.0 |
There was a problem hiding this comment.
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.
| if not overlap.strip(): | ||
| continue |
There was a problem hiding this comment.
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} |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
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.
| class TestExecuteAsyncLifecycle: | ||
| async def test_run_produces_consistent_result(self, tmp_path: Path) -> None: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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": [], |
There was a problem hiding this comment.
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"] |
There was a problem hiding this comment.
Nit: the style guide asks for enums over Literals, and UpdateType is exported from the package. A StrEnum would match #4644.
| if logfile_path is None: | ||
| return FLRTResult(memory_labels=dict(memory_labels), log_path=None) |
There was a problem hiding this comment.
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>
|
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>


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:
gcgextra; no newdependencies are added.
Deviations from the reference implementation
attack parts.
the reference implementation's whole rendered prompt.
buffer[0].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:2.7925to2.1396over 100 steps.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).
in greedy generation, rather than refusing.
Type of change
Tests added
Checklist
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.