From ba5c3b3c17cc58243c43f2d51b5033973c9bf318 Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 19:48:31 +0530 Subject: [PATCH 1/9] FIX GCG: compare stripped suffixes and survive an all-rejected candidate batch (#4545, #4546) --- .../executor/promptgen/gcg/default_implementations.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/pyrit/executor/promptgen/gcg/default_implementations.py b/pyrit/executor/promptgen/gcg/default_implementations.py index 1c3a857a5f..47d6ae3a30 100644 --- a/pyrit/executor/promptgen/gcg/default_implementations.py +++ b/pyrit/executor/promptgen/gcg/default_implementations.py @@ -387,13 +387,17 @@ def filter_candidates( vocab_size = tokenizer.vocab_size candidate_tokens[candidate_tokens > vocab_size] = tokenizer("!").input_ids[0] + # ``current_control`` comes from ``control_str``, which strips the + # decoded suffix, while candidates keep their leading separator space. + # Compare stripped forms so an unchanged candidate is still dropped. + stripped_control = current_control.strip() candidates: list[str] = [] for i in range(candidate_tokens.shape[0]): decoded_str = tokenizer.decode( candidate_tokens[i], skip_special_tokens=True, clean_up_tokenization_spaces=False ) if self._filter: - if decoded_str != current_control and len( + if decoded_str.strip() != stripped_control and len( tokenizer(decoded_str, add_special_tokens=False).input_ids ) == len(candidate_tokens[i]): candidates.append(decoded_str) @@ -401,7 +405,10 @@ def filter_candidates( candidates.append(decoded_str) if self._filter: - candidates = candidates + [candidates[-1]] * (len(candidate_tokens) - len(candidates)) + # When every row is rejected, fall back to the current suffix so + # the step re-scores it instead of indexing an empty list. + pad = candidates[-1] if candidates else current_control + candidates = candidates + [pad] * (len(candidate_tokens) - len(candidates)) return candidates From 43ab93e169a5adce362e218886f5d1da0625504c Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 19:49:41 +0530 Subject: [PATCH 2/9] FIX GCG: apply the same filter fixes to legacy get_filtered_cands (#4545, #4546) --- .../promptgen/gcg/attack/base/attack_manager.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py b/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py index 393868cfdf..78e9928541 100644 --- a/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py +++ b/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py @@ -1247,6 +1247,9 @@ def get_filtered_cands( Returns: list[str]: Decoded candidate controls. + + Raises: + RuntimeError: If filtering rejects every candidate and ``curr_control`` is None. """ cands: list[str] = [] count = 0 @@ -1256,12 +1259,15 @@ def get_filtered_cands( vocab_size = worker.tokenizer.vocab_size control_cand[control_cand > vocab_size] = worker.tokenizer("!").input_ids[0] + # ``curr_control`` comes from the stripped ``control_str``; compare + # stripped forms so an unchanged candidate with a leading space is dropped. + stripped_control = curr_control.strip() if curr_control is not None else None for i in range(control_cand.shape[0]): decoded_str = worker.tokenizer.decode( control_cand[i], skip_special_tokens=True, clean_up_tokenization_spaces=False ) if filter_cand: - if decoded_str != curr_control and len( + if decoded_str.strip() != stripped_control and len( worker.tokenizer(decoded_str, add_special_tokens=False).input_ids ) == len(control_cand[i]): cands.append(decoded_str) @@ -1271,6 +1277,11 @@ def get_filtered_cands( cands.append(decoded_str) if filter_cand: + if not cands: + if curr_control is None: + raise RuntimeError("All GCG candidates were filtered out and no current control is available") + # Every row was rejected: re-score the current suffix instead of indexing an empty list. + cands = [curr_control] cands = cands + [cands[-1]] * (len(control_cand) - len(cands)) return cands From 025c68cb2d2e514e99f92823d51c8b3b496b7e4e Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 19:50:26 +0530 Subject: [PATCH 3/9] TEST GCG: cover the all-rejected and leading-space filter cases (#4545, #4546) --- .../gcg/test_default_implementations.py | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/tests/unit/executor/promptgen/gcg/test_default_implementations.py b/tests/unit/executor/promptgen/gcg/test_default_implementations.py index 331143c481..36ad7b4fc5 100644 --- a/tests/unit/executor/promptgen/gcg/test_default_implementations.py +++ b/tests/unit/executor/promptgen/gcg/test_default_implementations.py @@ -503,6 +503,64 @@ def test_filter_candidates_clamps_out_of_vocab_tokens(self) -> None: assert torch.equal(default_input, legacy_input) assert default_input[0, 0].item() == 0 + def test_filter_candidates_pads_with_current_control_when_all_rejected(self) -> None: + """Regression for #4546: when every row is rejected, both code paths + pad with the current control instead of raising ``IndexError``. + + Rows ``[5, 0, 0]`` and ``[2, 0, 1]`` re-tokenize to lengths 5 and 2 + (control length 3), so both are dropped. + """ + candidate_template = torch.tensor([[5, 0, 0], [2, 0, 1]]) + + legacy_attack = self._make_legacy_attack(tokenizer=_make_filter_tokenizer()) + legacy_out = legacy_attack.get_filtered_cands( + 0, candidate_template.clone(), filter_cand=True, curr_control="current" + ) + + default_out = LengthPreservingFilter(filter=True).filter_candidates( + candidate_tokens=candidate_template.clone(), + tokenizer=_make_filter_tokenizer(), + current_control="current", + ) + + assert default_out == legacy_out + assert legacy_out == ["current", "current"] + + def test_legacy_filter_raises_clear_error_when_all_rejected_without_current_control(self) -> None: + legacy_attack = self._make_legacy_attack(tokenizer=_make_filter_tokenizer()) + with pytest.raises(RuntimeError, match="All GCG candidates were filtered out"): + legacy_attack.get_filtered_cands(0, torch.tensor([[5, 0, 0]]), filter_cand=True) + + def test_filter_candidates_drops_unchanged_candidate_with_leading_space(self) -> None: + """Regression for #4545: ``current_control`` is the stripped + ``control_str`` while candidates keep their leading separator space, + so an unchanged candidate must still be recognized and dropped. + + - Row ``[3, 0, 1]`` decodes to ``" ab"`` — same suffix as ``"ab"`` -> DROP. + - Row ``[7, 0, 1]`` decodes to ``" cd"`` (len 3) -> KEEP. + """ + + def make_tokenizer() -> MagicMock: + tokenizer = _make_filter_tokenizer() + tokenizer.decode.side_effect = lambda ids, **_kwargs: {3: " ab", 7: " cd"}[int(ids[0].item())] + return tokenizer + + candidate_template = torch.tensor([[3, 0, 1], [7, 0, 1]]) + + legacy_attack = self._make_legacy_attack(tokenizer=make_tokenizer()) + legacy_out = legacy_attack.get_filtered_cands( + 0, candidate_template.clone(), filter_cand=True, curr_control="ab" + ) + + default_out = LengthPreservingFilter(filter=True).filter_candidates( + candidate_tokens=candidate_template.clone(), + tokenizer=make_tokenizer(), + current_control="ab", + ) + + assert default_out == legacy_out + assert legacy_out == [" cd", " cd"] + def test_init_rejects_enabled_and_legacy_filter_together(self) -> None: with pytest.raises(TypeError, match="Specify either 'enabled' or 'filter', not both"): LengthPreservingFilter(enabled=True, filter=False) From 8ff164b0ad2f86872c74b9770a392eeaf1f12c9e Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 20:21:51 +0530 Subject: [PATCH 4/9] FIX GCG: fall back to the unstripped decode of the current control ids --- .../promptgen/gcg/default_implementations.py | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/pyrit/executor/promptgen/gcg/default_implementations.py b/pyrit/executor/promptgen/gcg/default_implementations.py index 47d6ae3a30..c0d831c940 100644 --- a/pyrit/executor/promptgen/gcg/default_implementations.py +++ b/pyrit/executor/promptgen/gcg/default_implementations.py @@ -32,6 +32,24 @@ logger = logging.getLogger(__name__) +def decode_control_tokens(*, tokenizer: Any, control_tokens: torch.Tensor) -> str: + """ + Decode control token ids exactly as candidate filters decode candidates. + + The result keeps any leading separator space, so re-tokenizing it for scoring yields the + same ids, unlike the stripped ``control_str``. + + Args: + tokenizer (Any): HuggingFace-style tokenizer. + control_tokens (torch.Tensor): One row of control token ids. + + Returns: + str: The decoded control string. + """ + decoded: str = tokenizer.decode(control_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False) + return decoded + + class StandardGCGSampling: """ Top-k by ``-gradient``, uniform pick within top-k at one random position per row. @@ -377,7 +395,11 @@ def filter_candidates( re-tokenization drift; ``tokenizer("!").input_ids[0]`` provides the replacement id for out-of-vocab clamping. current_control (str): Current suffix string. When ``filter`` - is True, candidates that decode to this string are dropped. + is True, candidates that decode to this string (ignoring + surrounding whitespace) are dropped, and it pads the result + when every candidate is rejected. Pass the unstripped decode + of the current control tokens (see ``decode_control_tokens``) + so the padded rows re-tokenize to the current ids. Returns: list[str]: Decoded candidate suffix strings of length exactly @@ -393,9 +415,7 @@ def filter_candidates( stripped_control = current_control.strip() candidates: list[str] = [] for i in range(candidate_tokens.shape[0]): - decoded_str = tokenizer.decode( - candidate_tokens[i], skip_special_tokens=True, clean_up_tokenization_spaces=False - ) + decoded_str = decode_control_tokens(tokenizer=tokenizer, control_tokens=candidate_tokens[i]) if self._filter: if decoded_str.strip() != stripped_control and len( tokenizer(decoded_str, add_special_tokens=False).input_ids From b97b1448852077e67cd78c8bc733b6051e065f7e Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 20:22:43 +0530 Subject: [PATCH 5/9] FIX GCG: pass the unstripped current control decode to candidate filters --- .../executor/promptgen/gcg/attack/gcg/gcg_attack.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py b/pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py index db4e341055..316b215cf5 100644 --- a/pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py +++ b/pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py @@ -22,6 +22,7 @@ CrossEntropyLoss, LengthPreservingFilter, StandardGCGSampling, + decode_control_tokens, ) from pyrit.executor.promptgen.gcg.extension_protocols import CandidateFilter, LossFunction, SamplingStrategy @@ -231,10 +232,13 @@ def _filter_control_candidates( filter_cand: bool, ) -> list[str]: candidate_filter = self._resolve_candidate_filter(filter_cand=filter_cand) + tokenizer = self.workers[worker_index].tokenizer return candidate_filter.filter_candidates( candidate_tokens=control_cand, - tokenizer=self.workers[worker_index].tokenizer, - current_control=self.control_str, + tokenizer=tokenizer, + current_control=decode_control_tokens( + tokenizer=tokenizer, control_tokens=self.prompts[worker_index].control_toks + ), ) def _get_control_length(self, *, control: str) -> int | None: @@ -327,7 +331,9 @@ def step( temp=temp, allow_non_ascii=allow_non_ascii, filter_cand=filter_cand, - current_control_str=self.control_str, + current_control_str=decode_control_tokens( + tokenizer=self.workers[0].tokenizer, control_tokens=self.prompts[0].control_toks + ), ) evaluator = GCGCandidateEvaluator( workers=self.workers, From 6d719299fe06a7a50b3082d51f22b73ccb79f58f Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 20:24:53 +0530 Subject: [PATCH 6/9] TEST GCG: expect the unstripped control decode in the filter wiring test --- tests/unit/executor/promptgen/gcg/test_gcg_core.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/unit/executor/promptgen/gcg/test_gcg_core.py b/tests/unit/executor/promptgen/gcg/test_gcg_core.py index 14e4403864..f640b67a19 100644 --- a/tests/unit/executor/promptgen/gcg/test_gcg_core.py +++ b/tests/unit/executor/promptgen/gcg/test_gcg_core.py @@ -1916,7 +1916,11 @@ def test_step_uses_custom_protocol_implementations_when_supplied(self) -> None: assert sampling.calls[0]["batch_size"] == 2 assert sampling.calls[0]["top_k"] == 4 assert sampling.calls[0]["allow_non_ascii"] is False - assert candidate_filter.calls[0]["current_control"] == "current control" + # The filter gets the unstripped decode of the current ids, not the stripped control_str, + # so a padded fallback re-tokenizes to the same ids. + assert candidate_filter.calls[0]["current_control"] == tokenizer.decode( + control_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) def test_gcg_multi_prompt_attack_init_with_custom_protocols(self) -> None: """Test GCGMultiPromptAttack.__init__ stores custom sampling/loss/filter.""" From 05df73433343f697d483cf6e1d227f423dbfb84d Mon Sep 17 00:00:00 2001 From: K L Aadithya Date: Wed, 25 Nov 2026 20:26:08 +0530 Subject: [PATCH 7/9] TEST GCG: fallback re-tokenizes to the current control ids --- .../promptgen/gcg/test_gcg_proposal.py | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/tests/unit/executor/promptgen/gcg/test_gcg_proposal.py b/tests/unit/executor/promptgen/gcg/test_gcg_proposal.py index 2a87f064d8..cb809f53f8 100644 --- a/tests/unit/executor/promptgen/gcg/test_gcg_proposal.py +++ b/tests/unit/executor/promptgen/gcg/test_gcg_proposal.py @@ -3,6 +3,7 @@ # ruff: noqa: E402 +import re from unittest.mock import MagicMock import pytest @@ -437,10 +438,51 @@ def test_proposal_uses_last_worker_in_each_group( assert sample_kwargs["allow_non_ascii"] is False filter_kwargs = candidate_filter.filter_candidates.call_args_list[group_index].kwargs assert filter_kwargs["tokenizer"] is workers[worker_index].tokenizer - assert filter_kwargs["current_control"] == "seed" + # The attack callback decodes the worker's current ids unstripped instead of passing control_str through. + assert filter_kwargs["current_control"] == (f"worker-{worker_index}" if use_callbacks else "seed") assert torch.equal(filter_kwargs["candidate_tokens"], prompts[worker_index].control_toks.repeat(2, 1)) group_start = worker_index + 1 if sample_fn is not None and filter_fn is not None: assert [call.kwargs["worker_index"] for call in sample_fn.call_args_list] == representatives assert [call.kwargs["worker_index"] for call in filter_fn.call_args_list] == representatives assert all(call.kwargs["filter_cand"] is False for call in filter_fn.call_args_list) + + +class _SpacePrefixTokenizer: + """Byte-level-BPE-like tokenizer where ``" !"`` and ``"!"`` are different tokens.""" + + vocab_size = 10 + _vocab = {"!": 1, " !": 2} + + def __call__(self, text: str, **_kwargs): + result = MagicMock() + result.input_ids = [self._vocab[piece] for piece in re.findall(r" ?[^ ]", text)] + return result + + def decode(self, ids, **_kwargs) -> str: + inverse = {value: key for key, value in self._vocab.items()} + return "".join(inverse[int(token)] for token in ids) + + +def test_all_rejected_fallback_retokenizes_to_current_ids() -> None: + """Regression for #4546 review: the fallback must score the current ids, not a stripped re-tokenization.""" + tokenizer = _SpacePrefixTokenizer() + current_ids = torch.tensor([2, 2]) # " ! !", whose stripped control_str "! !" tokenizes to [1, 2] + worker = MagicMock(spec=ModelWorker) + worker.tokenizer = tokenizer + prompt = MagicMock(spec=PromptManager) + prompt.control_toks = current_ids + prompt.control_str = tokenizer.decode(current_ids).strip() + + attack = object.__new__(GCGMultiPromptAttack) + attack.workers = [worker] + attack.prompts = [prompt] + attack._candidate_filter = LengthPreservingFilter(enabled=True) + + # Every row is the unchanged suffix, so every row is rejected. + candidates = attack._filter_control_candidates( + worker_index=0, control_cand=current_ids.repeat(3, 1), filter_cand=True + ) + + assert len(candidates) == 3 + assert all(tokenizer(candidate).input_ids == current_ids.tolist() for candidate in candidates) From 27eeb5efbad2850937759087a42afc892ed788a1 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 26 Nov 2026 21:38:07 -0800 Subject: [PATCH 8/9] TEST GCG: call get_filtered_cands with control_cand as a keyword The keyword-only migration in #4693 makes control_cand keyword-only; using the keyword form now keeps these new tests valid in either merge order. Co-Authored-By: Claude Fable 5 --- .../executor/promptgen/gcg/test_default_implementations.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit/executor/promptgen/gcg/test_default_implementations.py b/tests/unit/executor/promptgen/gcg/test_default_implementations.py index 36ad7b4fc5..fb12fc745c 100644 --- a/tests/unit/executor/promptgen/gcg/test_default_implementations.py +++ b/tests/unit/executor/promptgen/gcg/test_default_implementations.py @@ -514,7 +514,7 @@ def test_filter_candidates_pads_with_current_control_when_all_rejected(self) -> legacy_attack = self._make_legacy_attack(tokenizer=_make_filter_tokenizer()) legacy_out = legacy_attack.get_filtered_cands( - 0, candidate_template.clone(), filter_cand=True, curr_control="current" + 0, control_cand=candidate_template.clone(), filter_cand=True, curr_control="current" ) default_out = LengthPreservingFilter(filter=True).filter_candidates( @@ -529,7 +529,7 @@ def test_filter_candidates_pads_with_current_control_when_all_rejected(self) -> def test_legacy_filter_raises_clear_error_when_all_rejected_without_current_control(self) -> None: legacy_attack = self._make_legacy_attack(tokenizer=_make_filter_tokenizer()) with pytest.raises(RuntimeError, match="All GCG candidates were filtered out"): - legacy_attack.get_filtered_cands(0, torch.tensor([[5, 0, 0]]), filter_cand=True) + legacy_attack.get_filtered_cands(0, control_cand=torch.tensor([[5, 0, 0]]), filter_cand=True) def test_filter_candidates_drops_unchanged_candidate_with_leading_space(self) -> None: """Regression for #4545: ``current_control`` is the stripped @@ -549,7 +549,7 @@ def make_tokenizer() -> MagicMock: legacy_attack = self._make_legacy_attack(tokenizer=make_tokenizer()) legacy_out = legacy_attack.get_filtered_cands( - 0, candidate_template.clone(), filter_cand=True, curr_control="ab" + 0, control_cand=candidate_template.clone(), filter_cand=True, curr_control="ab" ) default_out = LengthPreservingFilter(filter=True).filter_candidates( From 20d857b1b7a943d6eebe7f67404a9895239d8c5c Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Thu, 26 Nov 2026 22:34:21 -0800 Subject: [PATCH 9/9] DOC GCG: tell get_filtered_cands callers to pass the unstripped control decode Mirrors the filter_candidates docstring so the legacy fallback also re-tokenizes to the current control ids. Co-Authored-By: Claude Fable 5 --- pyrit/executor/promptgen/gcg/attack/base/attack_manager.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py b/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py index 1f74a6fc90..75d73593b0 100644 --- a/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py +++ b/pyrit/executor/promptgen/gcg/attack/base/attack_manager.py @@ -1292,6 +1292,11 @@ def get_filtered_cands( """ Decode candidates and retain controls whose token length is stable. + ``curr_control`` is compared ignoring surrounding whitespace, and pads the result when + every candidate is rejected. Pass the unstripped decode of the current control tokens + (see ``decode_control_tokens``) rather than the stripped ``control_str`` so the padded + rows re-tokenize to the current ids. + Returns: list[str]: Decoded candidate controls.