Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion pyrit/executor/promptgen/gcg/attack/base/attack_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1292,8 +1292,16 @@ 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.

Raises:
RuntimeError: If filtering rejects every candidate and ``curr_control`` is None.
"""
cands: list[str] = []
count = 0
Expand All @@ -1303,12 +1311,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)
Expand All @@ -1318,6 +1329,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

Expand Down
12 changes: 9 additions & 3 deletions pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
CrossEntropyLoss,
LengthPreservingFilter,
StandardGCGSampling,
decode_control_tokens,
)
from pyrit.executor.promptgen.gcg.extension_protocols import CandidateFilter, LossFunction, SamplingStrategy

Expand Down Expand Up @@ -233,10 +234,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:
Expand Down Expand Up @@ -329,7 +333,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,
Expand Down
39 changes: 33 additions & 6 deletions pyrit/executor/promptgen/gcg/default_implementations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -387,21 +409,26 @@ 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
)
decoded_str = decode_control_tokens(tokenizer=tokenizer, control_tokens=candidate_tokens[i])
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)
else:
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


Expand Down
58 changes: 58 additions & 0 deletions tests/unit/executor/promptgen/gcg/test_default_implementations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, control_cand=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, 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
``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, control_cand=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)
Expand Down
6 changes: 5 additions & 1 deletion tests/unit/executor/promptgen/gcg/test_gcg_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2037,7 +2037,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."""
Expand Down
44 changes: 43 additions & 1 deletion tests/unit/executor/promptgen/gcg/test_gcg_proposal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# ruff: noqa: E402

import re
from unittest.mock import MagicMock

import pytest
Expand Down Expand Up @@ -463,10 +464,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)
Loading