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
5 changes: 2 additions & 3 deletions pyrit/executor/promptgen/gcg/attack/gcg/gcg_attack.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,8 @@ def sample_control(
top_indices = (-grad).topk(topk, dim=1).indices
control_toks = self.control_toks.to(grad.device)
original_control_toks = control_toks.repeat(batch_size, 1)
new_token_pos = torch.arange(0, len(control_toks), len(control_toks) / batch_size, device=grad.device).type(
torch.int64
)
# Integer math: a float step makes arange return batch_size + 1 positions for some sizes.
new_token_pos = torch.arange(batch_size, device=grad.device) * len(control_toks) // batch_size
new_token_val = torch.gather(
top_indices[new_token_pos],
1,
Expand Down
8 changes: 2 additions & 6 deletions pyrit/executor/promptgen/gcg/default_implementations.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,8 @@ def sample_candidates(
top_indices = (-gradient).topk(top_k, dim=1).indices
control_tokens = control_tokens.to(gradient.device)
original_control_tokens = control_tokens.repeat(batch_size, 1)
new_token_pos = torch.arange(
0,
len(control_tokens),
len(control_tokens) / batch_size,
device=gradient.device,
).type(torch.int64)
# Integer math: a float step makes arange return batch_size + 1 positions for some sizes.
new_token_pos = torch.arange(batch_size, device=gradient.device) * len(control_tokens) // batch_size
new_token_val = torch.gather(
top_indices[new_token_pos],
1,
Expand Down
34 changes: 34 additions & 0 deletions tests/unit/executor/promptgen/gcg/test_default_implementations.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,40 @@ def sample(grad: torch.Tensor) -> torch.Tensor:
with pytest.raises(ValueError, match="Every token id is masked"):
sample(gradient)

@pytest.mark.parametrize("legacy", [False, True])
@pytest.mark.parametrize(("control_length", "batch_size"), [(20, 244), (9, 500), (22, 1000), (17, 7)])
def test_samples_one_position_per_candidate(self, legacy: bool, control_length: int, batch_size: int) -> None:
# torch.arange(0, control_length, control_length / batch_size) has batch_size + 1 elements for these sizes.
gradient = torch.zeros(control_length, 8)
# Token 0 is the current control token; masking it makes every swap visible.
gradient[:, 0] = float("inf")
control_tokens = torch.zeros(control_length, dtype=torch.long)
non_ascii_tokens = torch.tensor([], dtype=torch.long)

if legacy:
prompt_manager = self._make_legacy_prompt_manager(
control_tokens=control_tokens, non_ascii_tokens=non_ascii_tokens
)
candidates = prompt_manager.sample_control(gradient, batch_size=batch_size, topk=4)
else:
candidates = StandardGCGSampling().sample_candidates(
gradient=gradient,
control_tokens=control_tokens,
batch_size=batch_size,
top_k=4,
temperature=1.0,
allow_non_ascii=True,
non_ascii_tokens=non_ascii_tokens,
)

assert candidates.shape == (batch_size, control_length)
changed = candidates != control_tokens
assert (changed.sum(dim=1) == 1).all()
# Candidates are spread evenly over the positions they can reach.
per_position = changed.sum(dim=0)
per_position = per_position[per_position > 0]
assert per_position.max() - per_position.min() <= 1


class TestCrossEntropyLoss:
"""Parity: ``CrossEntropyLoss`` vs ``AttackPrompt.target_loss`` +
Expand Down
Loading