Left-pad at inference (decoder only generates from the last position), either side at training with the attention mask. Use `padding='longest'` plus bucketing or packing, not fixed `max_length`.
Imagine a row of bookshelves where every shelf has to be the same width. You can either jam every shelf to the warehouse's maximum width (mostly air), or you can size each shelf to the widest book in that group (much less air). The second way wastes far less wood. That is `padding='longest'` versus `padding='max_length'`. Then there is the question of which side of the shelf to put the air pocket on. For a model that reads a story and continues writing it from the last word, the last book on the shelf has to be a real one, not air. So air goes on the left side. That is left padding for decoder only inference.
Detailed answer & concept explanation~5 min readEverything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
5 min: distinguish strategy (longest vs max_length vs packing) from side (left vs right), explain why decoder only inference requires left padding, explain how packing eliminates pad waste, name the two roles of the attention mask, and close on the two production bugs (wrong side, missing mask).
Real products, models, and research that use this idea.
- Axolotl, TRL, and Unsloth all default to sequence packing for Llama 3 instruction fine tuning in 2026, with `sample_packing=true` in the config.
- Hugging Face `Trainer` with `DataCollatorForLanguageModeling` defaults to right padding for training and handles the loss mask via `labels = -100` automatically.
- vLLM and SGLang serving engines avoid request padding entirely via continuous batching plus paged attention, building a custom mask per request.
- Flash Attention 2 and 3 expose `varlen` kernels that take per sequence offsets so packed batches run at near peak throughput.
What an interviewer would ask next. Try answering before peeking at the approach.
QWhy is sequence packing more efficient than longest padding plus bucketing?
Don't say thisRed flags and common mistakes that signal junior thinking. Click to expand.
Red flags and common mistakes that signal junior thinking. Click to expand.
Right padding a Llama 3 model at inference and watching the model generate from a pad position because the last index of the sequence is pad, not the user's last real token.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.
Same topic, related formats. Practice these next.