Repository navigation
fix: sample right-padded prompts from the last attended token #2050
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jlarson4
merged 2 commits into
TransformerLensOrg:dev
from
emerardd:fix/right-padded-generation
Nov 25, 2026
+176
−0
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
143 changes: 143 additions & 0 deletions
143
tests/unit/model_bridge/test_right_padded_generation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| """Right-padded prompts sample from their last attended token.""" | ||
|
|
||
| import pytest | ||
| import torch | ||
| from tokenizers import Tokenizer | ||
| from tokenizers.models import WordLevel | ||
| from transformers import GPT2Config, GPT2LMHeadModel, PreTrainedTokenizerFast | ||
|
|
||
| from transformer_lens.model_bridge.sources import build_bridge_from_module | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def bridge(): | ||
| cfg = GPT2Config(vocab_size=32, n_positions=32, n_embd=16, n_layer=2, n_head=2) | ||
| cfg._attn_implementation = "eager" | ||
| with torch.random.fork_rng(devices=[]): | ||
| torch.manual_seed(0) | ||
| model = GPT2LMHeadModel(cfg).eval() | ||
| return build_bridge_from_module( | ||
| model, "GPT2LMHeadModel", hf_config=cfg, dtype=torch.float32, device="cpu" | ||
| ).eval() | ||
|
|
||
|
|
||
| def _options(cached): | ||
| return dict( | ||
| max_new_tokens=3, | ||
| do_sample=False, | ||
| stop_at_eos=False, | ||
| verbose=False, | ||
| use_past_kv_cache=cached, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("cached", [False, True]) | ||
| @pytest.mark.parametrize("batched", [False, True]) | ||
| @pytest.mark.parametrize("explicit_positions", [False, True]) | ||
| def test_padded_generation_matches_unpadded(bridge, cached, batched, explicit_positions): | ||
| padded = torch.tensor([[2, 3, 4, 0, 0], [7, 8, 0, 0, 0], [1, 2, 3, 4, 5]]) | ||
| mask = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1]]) | ||
| if not batched: | ||
| padded, mask = padded[:1], mask[:1] | ||
| opts = _options(cached) | ||
| positions = mask.cumsum(dim=-1) + 6 if explicit_positions else None | ||
| result = bridge.generate( | ||
| padded, | ||
| attention_mask=mask, | ||
| position_ids=positions, | ||
| output_logits=True, | ||
| **opts, | ||
| ) | ||
| assert torch.equal(result.sequences[:, : padded.shape[1]], padded) | ||
| assert len(result.logits) == 3 | ||
| for row, valid in enumerate(mask.bool()): | ||
| row_positions = positions[row : row + 1, valid] if positions is not None else None | ||
| reference = bridge.generate( | ||
| padded[row : row + 1, valid], | ||
| position_ids=row_positions, | ||
| output_logits=True, | ||
| **opts, | ||
| ) | ||
| assert torch.equal(result.sequences[row, -3:], reference.sequences[0, -3:]) | ||
| for actual, expected in zip(result.logits, reference.logits): | ||
| torch.testing.assert_close(actual[row], expected[0], rtol=1e-5, atol=1e-6) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("cached", [False, True]) | ||
| def test_stream_matches_unpadded(bridge, cached): | ||
| opts = {**_options(cached), "max_tokens_per_yield": 1} | ||
| reference = list(bridge.generate_stream(torch.tensor([[2, 3, 4]]), **opts)) | ||
| padded = list( | ||
| bridge.generate_stream( | ||
| torch.tensor([[2, 3, 4, 0, 0]]), | ||
| attention_mask=torch.tensor([[1, 1, 1, 0, 0]]), | ||
| **opts, | ||
| ) | ||
| ) | ||
| assert len(padded) == len(reference) == 3 | ||
| for actual, expected in zip(padded, reference): | ||
| torch.testing.assert_close(actual[:, -1:], expected[:, -1:]) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("method", ["generate", "generate_stream"]) | ||
| def test_all_masked_prompt_row_raises(bridge, method): | ||
| with pytest.raises(ValueError, match="at least one attended"): | ||
| result = getattr(bridge, method)( | ||
| torch.tensor([[2, 3, 4], [0, 0, 0]]), | ||
| attention_mask=torch.tensor([[1, 1, 1], [0, 0, 0]]), | ||
| **_options(True), | ||
| ) | ||
| if method == "generate_stream": | ||
| list(result) | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def shared_bos_pad_bridge(bridge, monkeypatch): | ||
| tokenizer = PreTrainedTokenizerFast( | ||
| tokenizer_object=Tokenizer(WordLevel({"<bos-pad>": 0, "<unk>": 1}, unk_token="<unk>")), | ||
| bos_token="<bos-pad>", | ||
| pad_token="<bos-pad>", | ||
| unk_token="<unk>", | ||
| ) | ||
| monkeypatch.setattr(bridge, "tokenizer", tokenizer) | ||
| return bridge | ||
|
|
||
|
|
||
| def _collect_generation(bridge, method, tokens, **kwargs): | ||
| result = getattr(bridge, method)(tokens, **kwargs) | ||
| return torch.cat(list(result), dim=1) if method == "generate_stream" else result | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("method", ["generate", "generate_stream"]) | ||
| @pytest.mark.parametrize("cached", [False, True]) | ||
| @pytest.mark.parametrize("batched", [False, True]) | ||
| def test_right_padding_preserves_bos_only_prompt(shared_bos_pad_bridge, method, cached, batched): | ||
| bridge = shared_bos_pad_bridge | ||
| tokens = torch.tensor([[0, 0, 0], [0, 3, 4]]) if batched else torch.tensor([[0]]) | ||
| opts = _options(cached) | ||
| actual = _collect_generation( | ||
| bridge, method, tokens, padding_side="right", prepend_bos=True, **opts | ||
| ) | ||
| assert torch.equal(actual[:, : tokens.shape[1]], tokens) | ||
| prompts = [torch.tensor([[0]])] | ||
| if batched: | ||
| prompts.append(tokens[1:]) | ||
| for row, prompt in enumerate(prompts): | ||
| expected = bridge.generate(prompt, **opts) | ||
| torch.testing.assert_close(actual[row, -3:], expected[0, -3:]) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("method", ["generate", "generate_stream"]) | ||
| @pytest.mark.parametrize("explicit_mask", [False, True]) | ||
| def test_right_padding_does_not_invent_bos(shared_bos_pad_bridge, method, explicit_mask): | ||
| tokens = torch.tensor([[0, 0]]) | ||
| with pytest.raises(ValueError, match="at least one attended"): | ||
| _collect_generation( | ||
| shared_bos_pad_bridge, | ||
| method, | ||
| tokens, | ||
| padding_side="right", | ||
| prepend_bos=explicit_mask, | ||
| attention_mask=torch.zeros_like(tokens) if explicit_mask else None, | ||
| **_options(True), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Where pad and BOS share an id (GPT-2),
padding_side="right"reads a BOS-only row as all padding, so an empty prompt in a right-padded batch, or a lone BOS, now lands here instead of generating. Can that path keep the BOS attended, the way the left-padded side does?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for catching this! The inferred right-padding mask now keeps the leading BOS attended when the prompt includes BOS and BOS shares the padding ID. Explicit masks still take precedence, and rows that are genuinely all masked still raise.