`prefix_allowed_tokens_fn` misroutes batch constraints during sampling with `num_return_sequences>1`
System Info
transformersversion: 5.24.0.dev0- Platform: Linux-6.18.55+-x86_64-with-glibc2.39
- Python version: 3.13.16
- Huggingface_hub version: 1.33.0
- Safetensors version: 0.8.0
- Accelerate version: 1.15.0
- PyTorch version : 2.11.0+cu130 (CUDA)
- GPU type: Tesla T4
Who can help?
@Cyrilvallez
Reproduction
generate() expands inputs when num_return_sequences>1, but PrefixConstrainedLogitsProcessor treats the expanded rows as separate original batch entries. This silently applies the wrong per-prompt token constraints or raises IndexError.
import torch
from transformers import GPT2Config, GPT2LMHeadModel
model = GPT2LMHeadModel(GPT2Config(
vocab_size=32,
n_positions=64,
n_embd=32,
n_layer=1,
n_head=2,
bos_token_id=1,
eos_token_id=2,
pad_token_id=0,
)).eval()
inputs = torch.tensor([[10, 11], [20, 21]])
seen = []
def allowed(batch_id, input_ids):
seen.append(batch_id)
return [5 + 2 * batch_id]
with torch.no_grad():
output = model.generate(
inputs,
do_sample=True,
num_beams=1,
num_return_sequences=3,
max_new_tokens=1,
prefix_allowed_tokens_fn=allowed,
)
print("Callback batch IDs:", seen)
print("Generated tokens:", output[:, -1].tolist())
Expected:
Callback batch IDs: [0, 0, 0, 1, 1, 1]
Generated tokens: [5, 5, 5, 7, 7, 7]
Actual:
Callback batch IDs: [0, 1, 2, 3, 4, 5]
Generated tokens: [5, 7, 9, 11, 13, 15]
If the callback indexes a constraint list sized to the original batch, this instead raises IndexError: list index out of range.
Reproduced on GPT-2, Llama, and Qwen2 with tiny random models on CUDA: 15 silent mismatches and 3 IndexError cases across the test matrix. Also reproduced through the standard text-generation pipeline, with and without KV caching. Single-output sampling, single-output beam search, and unconstrained multi-output sampling passed their controls.
The apparent mismatch is between input expansion in generation/utils.py and the num_beams-based batch indexing in PrefixConstrainedLogitsProcessor in generation/logits_process.py.
Expected behavior
Each generated continuation should use the token constraints associated with its original input prompt, regardless of num_return_sequences. Sampling multiple continuations must not change the batch IDs passed to prefix_allowed_tokens_fn, silently violate constraints, or raise an IndexError for valid original-batch indices.
Reproduced on 5.23.0 (CPU, torch 2.15) with your exact snippet — same numbers: the callback sees [0, 1, 2, 3, 4, 5] and the tokens come out [5, 7, 9, 11, 13, 15].
The mismatch is where you suspected. generate() expands the batch by max(num_beams, num_return_sequences), so with num_beams=1 and num_return_sequences=3 your 2 prompts become 6 rows. But PrefixConstrainedLogitsProcessor is built with only num_beams (_get_logits_processor in generation/utils.py), and its __call__ computes batch_size = input_ids.shape[0] // num_beams — 6 — and hands batch ids 0..5 straight to the callback, treating every expanded row as its own prompt.
I checked the fix direction by patching the processor's __call__ to group rows by max(num_beams, num_return_sequences) per prompt and pass row // group_size as the batch id: the same repro then gives [0, 0, 0, 1, 1, 1] and tokens [5, 5, 5, 7, 7, 7], and the num_return_sequences=1 control is unchanged ([0, 1] / [5, 7]). So the processor needs the return-sequences factor, not just num_beams — the cleanest place looks like passing it in alongside num_beams when the processor is constructed in _get_logits_processor. Beam search with num_beams > 1 is unaffected in the same sense: there the expansion factor already is num_beams, which is what the processor assumes.