Sequence packing: what it does, and the attention-mask gotcha
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
What is sequence packing in SFT training, why does it improve throughput, and what is the critical attention-mask gotcha that distinguishes a correct implementation from a broken one?
Sequence packing concatenates short examples into one max-length sequence to kill padding waste. The gotcha: you need a block-diagonal mask so examples don't attend across boundaries.
Imagine grading short essays, each on its own sheet of paper. Most sheets are tiny but you still feed a full-size sheet through the machine, so you waste paper on blank space. Packing means taping several short essays onto one big sheet so almost no space is wasted. But now a danger appears. If the reader's eyes drift, they might read the end of essay A as if it were the start of essay B and grade them as one muddled piece. So you draw thick black borders between essays. Each essay can only see itself, never its neighbor. In training, that border is a block-diagonal attention mask. Forget it, and the model quietly learns nonsense from glued-together examples while the loss looks perfectly fine.
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.
4 min: padding waste motivation + what packing concatenates + the cross-example leakage trap + block-diagonal mask plus position-id reset + cu_seqlens implementation + why the failure is silent.
| Aspect | Naive padding | Packing without mask | Packing with block-diagonal mask |
|---|---|---|---|
| Padding waste | High (mostly padding) | Low | Low |
| Throughput | Baseline | High | High |
| Cross-example leakage | None | Yes, silent | None |
| Model correctness | Correct | Broken, looks fine | Correct |
Real products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Packing examples but reusing the default causal mask, so example B attends into example A. Loss looks normal while the model trains on contaminated cross-example context.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.