Mixed decoder-start-token presence silently corrupts batched encoder-decoder generation
Was working on batched encoder-decoder generation, particularly how decoder prefixes are handled across requests, when I came across this possible defect. Turns out that mixing requests with and without the decoder-start token can silently change the generation results, even though each request works correctly when processed individually.
In Transformers 5.24.0.dev0 (commit fa9c04ea60c5e1d2ecc38064442973fa1ddccc72), GenerationMixin._prepare_decoder_input_ids_for_generation() in src/transformers/generation/utils.py uses (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item() to decide whether to prepend the decoder-start token. When some requests already contain it and others do not, .all() evaluates to False, silently skipping insertion for the remaining requests. Expected: Each request receives the same decoder context whether generated individually or in a batch. Actual: The affected request receives an incorrect decoder context, causing substantial score/logit divergence and potentially different generated tokens without raising an exception. This reproduces on pretrained checkpoints with equal-length decoder prefixes and no decoder padding.
| Evidence | facebook/bart-base |
Helsinki-NLP/opus-mt-en-de |
|---|---|---|
| Decoder start token | 2 |
58100 |
| Request A prefix | [2,133,138,585] |
[58100,3540,314,4523] |
| Request B prefix | [133,2634,2967,10] |
[55,201,377,30120] |
| Start token missing in batched B | Yes | Yes |
| Generated tokens changed | No; logits differ | Yes; malformed translation |
| Maximum score difference (8 steps) | 1.296694 |
13.026532 |
| Maximum raw-logit difference (8 steps) | 1.296694 |
20.635527 |
| Exception raised | No | No |
Reproduction
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
device = "cuda" if torch.cuda.is_available() else "cpu"
cases = [
("facebook/bart-base", [[2,133,138,585], [133,2634,2967,10]],
["The company announced record quarterly revenue and expanded into several new markets.",
"Researchers discovered a new material that could substantially improve battery storage."]),
("Helsinki-NLP/opus-mt-en-de", [[58100,3540,314,4523], [55,201,377,30120]],
["Good morning. Thank you for joining us today.",
"We will publish the project results tomorrow morning."]),
]
kw = dict(max_new_tokens=8, do_sample=False, num_beams=1, use_cache=True,
eos_token_id=None, forced_bos_token_id=None, forced_eos_token_id=None,
return_dict_in_generate=True, output_scores=True, output_logits=True)
def max_finite_delta(solo_steps, batch_steps):
deltas = []
for s, b in zip(solo_steps, batch_steps):
x, y = s[0].float(), b[1].float()
finite = torch.isfinite(x) & torch.isfinite(y)
if finite.any():
deltas.append((x[finite] - y[finite]).abs().max().item())
return max(deltas)
for checkpoint, prefixes, texts in cases:
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint).to(device).eval()
encoder = tokenizer(texts, padding=True, return_tensors="pt").to(device)
decoder = torch.tensor(prefixes, device=device)
mask = torch.ones_like(decoder)
start = model.generation_config.decoder_start_token_id
with torch.inference_mode():
solo = [
model.generate(**{k: v[i:i+1] for k, v in encoder.items()},
decoder_input_ids=decoder[i:i+1],
decoder_attention_mask=mask[i:i+1], **kw)
for i in range(2)
]
batched = model.generate(**encoder, decoder_input_ids=decoder,
decoder_attention_mask=mask, **kw)
score_delta = max_finite_delta(solo[1].scores, batched.scores)
logit_delta = max_finite_delta(solo[1].logits, batched.logits)
changed = not torch.equal(solo[1].sequences[0, -8:], batched.sequences[1, -8:])
print(f"\n{checkpoint}")
print("Solo start:", solo[1].sequences[0, 0].item(),
"| Batched start:", batched.sequences[1, 0].item(),
"| Expected:", start)
print(f"Tokens changed: {changed} | Score delta: {score_delta:.6f} | Logit delta: {logit_delta:.6f}")
print("Solo:", tokenizer.decode(solo[1].sequences[0], skip_special_tokens=False))
print("Batch:", tokenizer.decode(batched.sequences[1], skip_special_tokens=False))
assert solo[1].sequences[0, 0].item() == start
assert batched.sequences[1, 0].item() != start
assert score_delta > 1e-3
The reproduction uses greedy decoding with EOS stopping and forced-token constraints disabled to isolate decoder-start handling; the repeated special tokens in MarianMT are observed under these test settings. The shared encoder-decoder path was additionally investigated across T5, BART, Speech2Text, ViT-GPT2, ViT-TrOCR, pretrained MarianMT, and pretrained BART. An experimental grouped-generation workaround passed 94/94 validation checks, covering greedy/beam decoding, KV-cache continuation (4+4 vs. 8 tokens), cache isolation, output metadata parity, streaming, sampling reproducibility, and native API regression checks. This workaround is not yet an upstream-compatible replacement.
A minimal fix could raise a clear ValueError for mixed decoder-start states, while full support would require per-row normalization with correct decoder masks and positions. Either approach would prevent silent incorrect generation.
Further validation:
I extended the reproduction to real OPUS-100 examples using pretrained MarianMT, Flan-T5, and BART on the exact reported Transformers 5.24.0.dev0 commit (fa9c04ea60c5e1d2ecc38064442973fa1ddccc72). A FIFO batching simulation mixed requests with and without decoder_start_token_id, preserving default deterministic generation settings, including beam search and EOS handling. Across 36 vulnerable requests, 36/36 silently missed the decoder-start token, all showed substantial first-step logit divergence, and 25/36 produced different decoded continuations (MarianMT: 12/12; Flan-T5: 12/12; BART: 1/12), including repetitive or malformed outputs. Crucially, grouping requests by prefix convention without modifying their decoder tokens restored independent-generation output in 36/36 cases, reducing first-step logit differences to approximately 1e-5. I think it confirms a cross-architecture, batch-dependent generation correctness defect under normal decoding settings.
I don't know if based on user-frequency if this fix is good enough.....But it really fixes this thing in our research purposes and am ready to provide a PR to fix this once I get a green light 👍
cc @Cyrilvallez for generate
Humm, in what real scenario would the sequences be mixed-up with some containing the start token and others not?
Suppose we are batching translation requests where someone explicitly includes the decoder-start token while others leave it to generate(), which works fine individually but breaks when batched together...
I independently reproduced this on main (77ad7c4) with a randomly initialized, one-layer T5 on CPU. The test needs no checkpoint or tokenizer downloads. I used four equal-length decoder prefixes, two beginning with the configured start token 0 and two beginning with ordinary tokens.
- In standalone generation, all four sequences started with
0. - In the mixed batch, the two affected rows started with
16and21. Their first-step logits differed from the standalone runs by up to1.007139and0.267815, respectively. - Grouping those same four requests by prefix convention preserved the standalone sequences and first-step logits for all four rows (
torch.testing.assert_close).
A minimal CPU fixture for the missing start token:
import torch
from transformers import T5Config, T5ForConditionalGeneration
torch.manual_seed(7)
model = T5ForConditionalGeneration(T5Config(
vocab_size=32, d_model=32, d_kv=8, d_ff=64, num_layers=1,
num_decoder_layers=1, num_heads=4, decoder_start_token_id=0,
pad_token_id=0, eos_token_id=1,
)).eval()
encoder = torch.tensor([[2, 3, 4], [5, 6, 7]])
prefixes = torch.tensor([[0, 14, 15], [16, 17, 18]])
def generate(rows):
inputs, decoder = encoder[rows], prefixes[rows]
return model.generate(
input_ids=inputs, attention_mask=torch.ones_like(inputs),
decoder_input_ids=decoder, decoder_attention_mask=torch.ones_like(decoder),
max_new_tokens=1,
)
print(generate([1])[0, 0].item(), generate([0, 1])[1, 0].item())
# 0 16