If you fine-tune language models on real data, a surprising share of your GPU time goes to multiplying zeros. Training examples vary wildly in length, and the usual fix is to pad every sequence in a batch to the longest one. On instruction-tuning and support-ticket datasets, it is common for 30-60% of tokens in a padded batch to be padding. You pay for that compute, memory and time, and it contributes nothing to the loss.
This tutorial shows three ways to remove it, in increasing order of payoff: length-grouped batching, sequence packing with a correct attention mask, and padding-free (varlen) attention. It also covers the correctness traps that make packed training quietly worse.
1. Measure your padding waste first
Before changing anything, measure. A few lines tell you whether this work is worth doing.
def padding_waste(lengths, batch_size):
total_real = total_padded = 0
for i in range(0, len(lengths), batch_size):
chunk = lengths[i:i + batch_size]
total_real += sum(chunk)
total_padded += max(chunk) * len(chunk)
return 1 - total_real / total_padded
# lengths = [len(tokenizer(x["text"]).input_ids) for x in dataset]
print(f"padding waste: {padding_waste(lengths, 16):.1%}")
If waste is under 10%, stop. If it is above 25%, keep reading.
2. Cheap win: length-grouped batching
Shuffle, split the data into large "mega-batches" (for example 50 x batch size), sort each by length, then cut it into batches. Lengths inside a batch become similar, while batch order stays random enough for training.
import random
def length_grouped_batches(lengths, batch_size, mega=50, seed=0):
rng = random.Random(seed)
idx = list(range(len(lengths)))
rng.shuffle(idx)
batches = []
for i in range(0, len(idx), batch_size * mega):
mega_batch = sorted(idx[i:i + batch_size * mega], key=lambda j: lengths[j], reverse=True)
batches += [mega_batch[k:k + batch_size] for k in range(0, len(mega_batch), batch_size)]
rng.shuffle(batches)
return batches
Pass the result as batch_sampler to a DataLoader. This usually cuts waste by more than half with no change to the model code. The trade-off is mild: batches are less diverse in length, which can slightly change gradient noise.
3. Sequence packing
Packing concatenates several short examples into one fixed-length row (say 4096 tokens), separated by an end-of-sequence token. Every row is nearly full, so waste approaches zero.
A simple greedy packer:
def pack(examples, max_len, eos_id):
rows, cur, cur_ids = [], [], []
for ex_id, ids in enumerate(examples):
ids = ids[: max_len - 1] + [eos_id]
if len(cur) + len(ids) > max_len:
rows.append((cur, cur_ids)); cur, cur_ids = [], []
cur += ids
cur_ids += [ex_id] * len(ids) # which document each token belongs to
if cur:
rows.append((cur, cur_ids))
return rows
Keep the per-token document id. You need it for the next step.
The trap: cross-contamination
If you just concatenate and use ordinary causal attention, token 5 of document B can attend to document A. For unrelated documents this teaches the model to condition on noise, and it is a common reason for packed runs that look fine in loss but evaluate slightly worse. Fix two things:
- Attention must not cross document boundaries.
- Position ids must restart at zero for each document, otherwise rotary embeddings see positions that never occur at inference.
4. Block-diagonal masking with FlexAttention
PyTorch's FlexAttention lets you express "causal within the same document" as a small function instead of materializing a large mask.
import torch
from torch.nn.attention.flex_attention import flex_attention, create_block_mask
def make_block_mask(doc_ids, device="cuda"):
# doc_ids: LongTensor [B, S] of per-token document ids
def mask_mod(b, h, q_idx, kv_idx):
same_doc = doc_ids[b, q_idx] == doc_ids[b, kv_idx]
return same_doc & (q_idx >= kv_idx)
B, S = doc_ids.shape
return create_block_mask(mask_mod, B, None, S, S, device=device)
flex = torch.compile(flex_attention)
# q, k, v: [B, H, S, D]
out = flex(q, k, v, block_mask=make_block_mask(doc_ids))
Block masks skip fully masked tiles, so compute drops along with the padding. Build the block mask once per batch, not once per layer, and reuse it across all layers.
Per-document position ids are straightforward to compute:
def position_ids(doc_ids):
# doc_ids [B, S] -> positions restarting at 0 for each document
B, S = doc_ids.shape
pos = torch.arange(S, device=doc_ids.device).expand(B, S)
starts = torch.zeros_like(doc_ids)
change = torch.ones_like(doc_ids, dtype=torch.bool)
change[:, 1:] = doc_ids[:, 1:] != doc_ids[:, :-1]
starts = torch.where(change, pos, torch.zeros_like(pos)).cummax(dim=1).values
return pos - starts
5. Fix the loss too
Two loss details matter with packing:
- Do not predict across a boundary. The last token of document A should not be trained to predict the first token of document B. Set the label for the first token of each document to
-100(the ignore index). - Normalize by real tokens. With a mix of packed and unpacked batches, or with prompt masking in instruction tuning, divide the summed loss by the count of non-ignored tokens across the whole accumulated step, not per micro-batch. Otherwise micro-batches with fewer supervised tokens get overweighted.
labels = input_ids.clone()
boundary = torch.ones_like(doc_ids, dtype=torch.bool)
boundary[:, 1:] = doc_ids[:, 1:] != doc_ids[:, :-1]
labels[boundary] = -100 # first token of each doc is not a target
loss_sum = torch.nn.functional.cross_entropy(
logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten(),
ignore_index=-100, reduction="sum")
loss = loss_sum / num_target_tokens_in_accumulated_step
6. Verify that packing did not change quality
Do not trust throughput numbers alone. Run this checklist:
- Equivalence test. Take two short documents. Compute logits for each separately, then packed together with the block mask and per-document positions. Logits should match to within bf16 tolerance. If they do not, your mask or positions are wrong.
- Tokens per second of real tokens, not padded tokens. This is the only honest throughput metric.
- Held-out eval after a short run, packed vs. unpacked, with the same number of supervised tokens seen.
- Long-document handling. Decide explicitly whether to truncate or split documents longer than the row; silent truncation of the answer part of an example is a classic bug.
@torch.no_grad()
def test_packing_equivalence(model, a_ids, b_ids):
la = model(a_ids[None]).logits[0]
lb = model(b_ids[None]).logits[0]
# run the packed path with your block mask and per-doc positions, then:
# torch.testing.assert_close(packed_logits[:len(a_ids)], la, atol=2e-2, rtol=2e-2)
# torch.testing.assert_close(packed_logits[len(a_ids):], lb, atol=2e-2, rtol=2e-2)
Adapt the model call to your architecture's interface: how position ids and masks are passed differs between implementations.
7. When not to pack
- Very small datasets where example order and boundaries matter more than speed.
- Tasks with strong example-level batch statistics, such as contrastive losses that rely on in-batch negatives drawn from different examples.
- Evaluation. Keep eval unpacked so metrics are per example and comparable with previous runs.
Expected results
On datasets with highly variable lengths, expect roughly 1.3x to 2x higher real-token throughput from packing versus naive padding, with length grouping delivering a good fraction of that. Gains scale with your measured waste in step 1; your numbers will vary with sequence length distribution and hardware, so benchmark on your own data.
Summary
- Measure padding waste before optimizing.
- Length-grouped batching is a no-risk first step.
- Packing needs document-aware attention, per-document position ids and boundary-aware labels.
- Validate with an equivalence test and a held-out eval, not just speed.
IntelliSensei helps teams profile and speed up fine-tuning pipelines, from data loading to distributed training. If your training runs are slower or more expensive than they should be, get in touch through our contact page.