LLM Learning Roadmap
✨ Awesome-Anything
🖼️ Digital Image Processing
🍃 LLM Components
🌱 LLM Pre-training
☘️ LLM Post-Training
🍀 LLM Popular Models
🪴 LLM Applications
🌿 LLM Optimization
🌾 LLM Compression
🌵 LLM Hands-on Practice
🌴 LLM Must-read Papers
🌳 LLM Q&A
🐝 VLM Image Encoders
📝 MISC.
6.5 Packing for Efficient Training
6.5 Packing for Efficient Training
Why
In traditional model training, a fixed-length input sequence is typically used. However, the lengths of text segments in real-world data vary greatly. If short texts are directly padded to a fixed length using
[PAD] tokens, it results in a large amount of wasted computation.How
Packing refers to concatenating multiple short sequences into one long sequence, allowing each batch of tokens to be closer to the maximum length limit and maximizing token utilization. In practice, packing can be done by filling up to the longest sentence in a batch or to the model's maximum input length.
6.5.1 Pre-training Phase
Most packing during pretraining is simply concatenation, where texts from different sources are separated by special tokens, such as the special token
[SEP].Of course, if a long text is accidentally split mid-way, it could cause issues during the pre-training stage. In fact, we can tolerate some longer texts being split during initial pretraining (not during continued pretraining on long texts), but if this splitting is too aggressive, how can we solve it?
A good approach is to pack short and long texts separately. Short and long texts can each have their own packing processes, with pack sizes matching their original
max length (e.g., 4k for short texts, 128k for long ones). Then, repack the packed short texts again to longer ones, i.e., 128k.6.5.2 Supervised Fine-tuning Phase
An Efficient Method Without Packing
The efficiency here is mainly applied to multi-turn dialogue scenarios, which usually do not need packing because we naturally put all-turn dialogue together to prevent computation waste. But we need to make sure the loss is calculated correctly.
Since causal language modeling (CLM) uses a triangle attention mask, the structure ensures that each token can only attend to itself and the tokens before it. Therefore, when predicting a response token, the model can access all prior information up to that token, but anything after it remains inaccessible.
Based on this mechanism, we can precompute logits for all responses in a dialogue at once, and when calculating loss, retain only the response portion of the logits—ignoring the user prompt portion—to compute loss correctly and more efficiently.
Let’s look at how Llama Factory improves efficiency
Thanks to current transformers supporting the 4D mask mechanism, the latest implementations now differentiate attention masks. This allows marking of different document types or sequences and proper handling of padding regions (usually 0) with their own identifiers.
What is a 4D mask?
Standard attention masks are given in 2D tensors, shaped
[batch_size, sequence_length]. Inside the LLM model, 2D tensors are expanded into 4D tensors, shaped as [batch_size, heads, sequence_length, sequence_length].If we can pass our own mask, this format would allow for more fine-grained attention strategies. For example, in causal decoding, it uses a lower triangular matrix with ones like the left one of below.

To get a separate mask for two different sequences, we need to custom our own mask. The so-called 4D Mask supports custom attention mask inputs.
For example, let's say we have a prefix with
The Last Of, and by applying beam search, we have 3 beams with token like You, Me, and Us. The standard approach would make them in a batch of 3 samples, with the shape of (3, 4):With 4D Mask, we would have just one batch shaped
(1, 6):Then the custom 4D mask would have a shape of
(1, 1, 6, 6):And the
positions_ids would beIn this way, you can observe that we can generate whatever 4D masks we want, like non-sequential tokens (like the example above) or multiple sequences in a single input (like packing multiple short texts).
For more details, refer to the original implementation about 4D Mask on GitHub or the author’s post.
<ins/>
- Example code (Running on Colab recommended)
you may see results like
Prev
6.4 PagedAttention
Next
6.6 PEFT
Loading...