Skip to content
Merged
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
143 changes: 143 additions & 0 deletions tests/unit/model_bridge/test_right_padded_generation.py
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),
)
33 changes: 33 additions & 0 deletions transformer_lens/model_bridge/transformer_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -3169,6 +3169,24 @@ def _generate_tokens(
the running sequence each step and folded into the finished-sequence mask alongside
EOS, so when it is ``None`` the loop runs the EOS-only path unchanged.
"""
last_prompt_positions = None
if (
initial_attention_mask is not None
and not is_encoder_decoder
and not use_stateful_cache
and not _generate_from_embeds
and pixel_values is None
and not multimodal_kwargs
):
columns = torch.arange(
initial_attention_mask.shape[1], device=initial_attention_mask.device
)
last_prompt_positions = columns.masked_fill(initial_attention_mask == 0, -1).amax(
dim=-1
)
if bool((last_prompt_positions < 0).any()):
raise ValueError("Each prompt row must have at least one attended token.")

Copy link
Copy Markdown
Collaborator

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?

Copy link
Copy Markdown
Contributor Author

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.


_hf_kv_cache = None
# A prior multimodal forward caches mrope deltas on the wrapped model, and a
# text-only generation would inherit them through the KV-cache position path
Expand Down Expand Up @@ -3343,6 +3361,10 @@ def _generate_tokens(
_hf_kv_cache = self._last_hf_cache or _hf_kv_cache
del self._last_hf_cache
raw_logits = logits[:, -1, :]
if gen_step_idx == 0 and last_prompt_positions is not None:
# Decode from the last real prompt token, not a right pad.
rows = torch.arange(logits.shape[0], device=logits.device)
raw_logits = logits[rows, last_prompt_positions.to(logits.device), :]
# Clone so processors may edit scores in place without leaking into raw_logits.
final_logits = raw_logits.clone()

Expand Down Expand Up @@ -3512,6 +3534,14 @@ def _padded_prompt_mask(
)
prepend = self.cfg.default_prepend_bos if prepend_bos is None else prepend_bos
mask = utils.get_attention_mask(self.tokenizer, tokens, prepend, padding_side=padding_side)
if (
padding_side == "right"
and prepend
and self.tokenizer.bos_token_id == self.tokenizer.pad_token_id
and tokens.shape[-1] > 0
):
# A BOS-only row otherwise looks entirely like trailing padding.
mask[..., 0] = 1
# An all-ones mask is what the model assumes anyway; skipping it keeps the
# unpadded path byte-identical.
return None if bool(mask.all()) else mask
Expand Down Expand Up @@ -3655,6 +3685,9 @@ def generate(
paths the mask is forwarded to the model as-is rather than grown per
step, which is what processors emitting one alongside
``pixel_values`` expect.
For ordinary decoder-only text generation, the first token is
sampled from each row's last attended prompt token, and every
row must contain at least one attended token.
forced_bos_token_id: Optional token id seeded as the first decoder token
after ``decoder_start`` on encoder-decoder models. Multilingual
translators (M2M100/MBart/NLLB) select their target language this way.
Expand Down
Loading