Efficient Sequence Packing without Cross-contamination: Accelerating Large Language Models without Impacting Performance

Mario Michael Krell, Matej Kosec, Sergio P. Perez, Mrinal Iyer, Andrew W Fitzgibbon

TL;DR

Padding tokens can make up to 50% of the tokens processed during language model pretraining, wasting vast amounts of accelerator compute. This paper formalizes sequence packing as a bin-packing problem, presents two ultra-fast algorithms that eliminate almost all padding in seconds, and introduces simple architectural modifications (attention masking, positional resets, and loss unpacking) to ensure mathematical equivalence with standard training. The result: an end-to-end 2x speedup in BERT pretraining with zero loss in downstream task accuracy.

What Problem Does This Paper Address?

Hardware accelerators (GPUs, TPUs, IPUs) thrive on static tensor shapes. Because natural language sequences have variable lengths, common practice sets a uniform maximum length (e.g., 512 tokens) and pads shorter sequences with dummy tokens.

In Wikipedia—the standard pretraining corpus for BERT—samples of full length (512 tokens) represent only 23.5% of the dataset, and 50% of all tokens processed in Phase 2 pretraining are padding. In extreme cases (e.g., GLUE-CoLA at length 128), padding reaches 89%.

Existing workarounds have steep trade-offs:

  • Concatenation without isolation causes cross-contamination, where tokens attend across sequence boundaries, hurting accuracy.
  • Un-padding methods (e.g., Effective Transformer) dynamically skip padding via custom low-level GPU kernels, but cause severe hardware load imbalance across multi-accelerator clusters because devices must wait for the slowest sequence in each batch.
  • Sorted batching requires dynamic recompilation or excessive memory overhead on static-graph accelerators like IPUs.

Methods

The authors tackle packing via a three-part approach:

  1. Histogram-Based Bin Packing Algorithms: Rather than bin-packing millions of individual samples ($O(n \log n)$), the algorithms operate on the discrete sequence length histogram ($s_m$ bins, where $s_m \le 512$):
  2. SPFHP (Shortest-Pack-First Histogram-Packing): A worst-fit heuristic that traverses histogram bins from longest to shortest, placing sequences into the pack with the most remaining space up to a maximum packing depth. It packs millions of sequences in 0.03 seconds ($O(n + s_m^2)$).
  3. NNLSHP (Non-Negative Least Squares Histogram-Packing): Formulates packing as a constrained optimization problem ($wAx = wb, x \ge 0$). Columns of $A$ define valid sequence combinations summing to $s_m$. Off-the-shelf NNLS solvers find integer-rounded repetition counts for each strategy in ~28 seconds.
  4. Model Modifications (packedBERT):
  5. Reset Positional Embeddings: Instead of a linear bias addition, positions reset at sequence boundaries (e.g., [0, 1, 0, 1, 2]) using an embedding lookup.
  6. Block-Diagonal Attention Masking: A simple 2D attention mask prevents attention across sequence boundaries within the same pack without needing custom CUDA/kernel code.
  7. Vectorized Per-Sequence Loss: Unpacks predictions and labels in parallel so the loss is averaged per sequence rather than per pack, preventing short sequences from being over-weighted.
  8. Hyperparameter Heuristics: To account for larger effective batch sizes without dropping hardware throughput, the authors adjust LAMB optimizer decay parameters ($\beta_1 := \beta_1^p, \beta_2 := \beta_2^p$, where $p$ is the packing factor).

Datasets

The authors analyze and benchmark multiple datasets:

  • Pretraining: English Wikipedia dump (October 2020) at sequence lengths 128, 384, and 512.
  • Downstream NLP: SQuAD 1.1 (question answering) and GLUE benchmark tasks (CoLA, SST-2, MRPC, QQP, STS-B, MNLI, QNLI, RTE, WNLI).
  • Cross-Domain Distributions: LibriSpeech (ASR audio sequences and text transcriptions) and QM9 (molecular graph sequences), demonstrating that skewed distributions are universal across domains.

Key Insights and Ideas

  • Bin the histogram, not the data: Because sequence lengths are discrete integers bounded by $s_m$, solving bin packing over the length counts ($s_m \le 512$) instead of individual items ($n \approx 10^7$) reduces runtime from minutes to milliseconds.
  • Packing provides inherent multi-device load balancing: Un-padding causes dynamic runtime variation where distributed workers wait at synchronization barriers for the device with the longest sequence. Packed sequences always fill the full context window, ensuring every accelerator in a cluster finishes at the exact same clock cycle.
  • Ablations prove masking is mandatory: Naively concatenating sequences without attention masks causes training loss and accuracy to degrade severely without recovery. Omitting positional embedding resets caps MLM accuracy below target thresholds (71.8% vs. 72.1%).

Key Results

  • Packing Efficiency: NNLSHP (packing depth 3) achieves 99.7% packing efficiency on Wikipedia (only 0.3% padding remains) with a theoretical packing factor of $p = 2.00$.
  • Wall-Clock Speedup: On a Graphcore IPU-M2000 system, NNLSHP delivers a 1.913x realized computational speedup for Phase 2 BERT pretraining (accounting for a minimal ~4.3% attention masking overhead). Factoring in reduced host-to-device data transfer latency, total pretraining speedup exceeds 2x.
  • Equivalence on Downstream Performance: Fully pretrained BERT models using packing achieve downstream SQuAD 1.1 scores virtually identical to vanilla baselines:
  • BERT-Base: 88.32 F1 / 81.03 EM (vs. 88.5 / 80.8 baseline).
  • BERT-Large: 90.65 F1 / 84.12 EM (vs. 90.9 / 84.1 baseline).

Limitations and Future Work

  • Distribution Dependency: Speedups depend directly on the dataset’s sequence length distribution. For datasets dominated by long sequences (e.g., LibriSpeech audio), packing yields smaller gains (~1.3x vs. 1.6x theoretical max).
  • Solver Scalability for High Depths: NNLSHP’s strategy matrix scales combinatorially with packing depth ($O(s_m^5)$ time, $O(s_m^3)$ space), causing it to run out of memory for depths beyond 3 (though depth 3 already captures 99.7% efficiency).
  • Future Directions: Applying sequence packing to Vision Transformers (ViTs) processing varying image resolutions without resizing, and extending contamination-free packing to models like RoBERTa, T5, and GPT-3.

Summary updated

BibTeX
@inproceedings{krell2022efficient,
  author = {Mario Michael Krell and Matej Kosec and Sergio P. Perez and Mrinal Iyer and Andrew W Fitzgibbon},
  title = {{Efficient Sequence Packing without Cross-contamination: Accelerating Large Language Models without Impacting Performance}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2022},
  url = {https://openreview.net/forum?id=e2M4CNa-UOS},
}

Loading related content...

Figure