skip to content

Batched generation with a Transformers decoder-only model returns garbled text for every prompt except the longest — which tokenizer settings cause it, and how do you fix them?

level: seniorimportance: should knowfreq 20%

answer

  1. where the short rows end
  2. the class default side
  3. padding_side='left' at load time
  4. causal checkpoints often lack a pad_token
  5. pad equal to EOS hides padding

basics

~20 s

The tokenizer padded on the right, its class default, so shorter prompts end in pad tokens and generate() continues from them. Load it with padding_side='left', give it a pad_token, and pass the attention_mask to generate().

solid answer

~40 s

`padding_side` defaults to `"right"` on the tokenizer class unless the checkpoint's tokenizer config sets it. `generate()` appends each new token after the last position of every row, so a right-padded short prompt ends in padding and the model continues from pad tokens; only the longest row, which has none, comes out clean. Load the tokenizer with `padding_side="left"` (or pass it per call) so every prompt ends at the final position. Many causal checkpoints ship without a `pad_token`, and padding then raises "Asking to pad but the tokenizer does not have a padding token"; set `tokenizer.pad_token = tokenizer.eos_token`. Then call `model.generate(**inputs)` so the `attention_mask` goes too: when pad equals EOS, generate cannot rebuild the mask from the ids.

code

python · 16 lines
python
from transformers import AutoModelForCausalLM, AutoTokenizer

repo = "your-org/your-causal-lm"
tokenizer = AutoTokenizer.from_pretrained(repo, padding_side="left")
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(repo)

prompts = ["1, 2, 3", "A, B, C, D, E"]
inputs = tokenizer(prompts, padding=True, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=20)

new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
for row in new_tokens:
    print(tokenizer.decode(row, skip_special_tokens=True))

go deeper

for a junior

Recall that padding_side can be 'left' or 'right', that decoder-only generation wants 'left', and that many causal tokenizers need a pad_token assigned before they can pad.

for a middle

Explain why right padding breaks generation: generate() continues from the last column, which holds pads for short rows. Show how to set the side at load time or per call.

for a senior

Diagnose the silent failure from the symptom alone: all rows wrong but the longest, a warning nobody read, and a mask that cannot be inferred because pad equals EOS.

for a principal

Weigh reusing EOS as padding against adding a token: no vocabulary change for inference, against an untrained embedding and a resize when training must keep EOS unambiguous.

## Why only the longest prompt survives A **decoder-only** model (a causal language model loaded with `AutoModelForCausalLM`) generates by predicting the token after the last position of its input, appending it, and repeating. In a batch, every row shares one length, so short prompts are **padded** with the tokenizer's `pad_token` until they match the longest. Where that padding goes decides the outcome. The tokenizer attribute **`padding_side`** defaults to `"right"` on the base tokenizer class, and a checkpoint's tokenizer configuration may set a different value. With right padding, a short prompt looks like `prompt, pad, pad, pad`, and `generate()` continues from the last position, which is a pad token. The model was never trained to continue from padding, so short rows come out garbled or repetitive, while the longest row has no padding and comes out fine. That pattern, every row wrong except the longest, is the signature. With **left padding** the batch looks like `pad, pad, prompt`: every real prompt ends at the final position, so every row continues from its own last real token. | Padding side | Where pads sit | Good for | |---|---|---| | `"right"` (class default) | After the text | Encoders, classification, most training batches, where the mask handles padding | | `"left"` | Before the text | Batched `generate()` with a decoder-only model | `generate()` notices the problem: when the attention mask shows padding in the last column it logs a warning that right-padding was detected and suggests `padding_side='left'`. It is only a warning, so a batch job can run for hours producing bad output. ## Setting the side - At load time: `AutoTokenizer.from_pretrained(repo, padding_side="left")`. - On the object: `tokenizer.padding_side = "left"`. - Per call: `tokenizer(prompts, padding=True, padding_side="left", return_tensors="pt")`. Keep the generation tokenizer separate from the one your training or classification code uses if those want right padding. ## Truncating prompts for generation The same reasoning applies to cutting long prompts. `truncation_side` also defaults to `"right"`, which drops the **end** of an over-long prompt, usually the part the model must continue from. For generation, `truncation_side="left"` keeps the most recent text and drops the oldest. Printing the tokenizer object shows both `padding_side` and `truncation_side`, along with `model_max_length` and the special tokens, which makes it the quickest check before a long batch job. ## The missing pad token Many causal checkpoints define a BOS and an EOS token but no pad token, because they were pretrained on unpadded streams. Asking such a tokenizer to pad raises: "Asking to pad but the tokenizer does not have a padding token", and the message itself names the two fixes. 1. **Reuse EOS**: `tokenizer.pad_token = tokenizer.eos_token`. No new vocabulary, no change to the model. This is the usual choice for inference. 2. **Add a new token**: `tokenizer.add_special_tokens({"pad_token": "[PAD]"})`, then `model.resize_token_embeddings(len(tokenizer))`, because the model needs an embedding row for the new id. Its embedding starts untrained. ## Pass the mask, especially when pad equals EOS The **attention mask** tells the model which positions are real. Pass the whole encoding, `model.generate(**inputs, max_new_tokens=...)`, rather than `inputs["input_ids"]` alone. If you pass only the ids, `generate()` tries to rebuild the mask by marking pad ids as padding, and it cannot do so when the pad token is the same as EOS: a real EOS and a pad look identical. It then logs that the mask cannot be inferred and falls back to attending to every position, padding included. ## Reading the outputs back With left padding, every prompt in the batch occupies the same leading columns of the output, so one slice removes them all: ```python new_tokens = outputs[:, inputs["input_ids"].shape[1]:] for row in new_tokens: print(tokenizer.decode(row, skip_special_tokens=True)) ``` `skip_special_tokens=True` drops the pad and EOS tokens from the decoded text. With right padding, that slice would cut each row at a different real position, which is one more reason the bug shows up as mangled text rather than an error. ## A quick diagnosis checklist - Print `tokenizer.padding_side` and `tokenizer.pad_token` before the first batch. - Decode one padded input row and look at where the pads are. - Search the logs for the right-padding warning and the mask-inference warning. - Compare one prompt run alone against the same prompt inside a batch; they should agree.

  • Why is right padding fine when the same model is fine-tuned, but wrong for generate()?
    In a training forward pass the attention mask hides the pads and the data collator typically excludes them from the loss, so where the pads sit does not matter. `generate()` is different: it always appends after the final column, so that column must hold each row's last real token, which only left padding guarantees.
  • When would you add a new pad token instead of reusing EOS?
    When EOS must stay unambiguous, for example in training data where the model has to learn to emit EOS and pads equal to EOS could be masked out with it. Adding one means `tokenizer.add_special_tokens({"pad_token": "[PAD]"})` plus `model.resize_token_embeddings(len(tokenizer))`, and the new embedding row starts untrained.

Like right-aligning a column of numbers so the last digits line up: generation always reads each row's final column, so the real text must end there and the blanks go in front.

  • AutoTokenizer always pads on the left for causal models.
  • Passing the attention_mask makes the padding side irrelevant for generate().
  • A missing pad_token is fixed by setting padding_side='left'.
  • generate() raises an error when it detects right padding.
  • Passing input_ids alone is safe because generate() rebuilds the mask from pad ids.