Skip to content

[Feature Request] 10x faster training: Decontaminated Sample Packing #126

Closed

Description

@DreamGenX

Sample packing is a technique that can significantly speed up training by wasting much less time in each batch with padding tokens. It does so by merging several examples into one virtual "packed" example that fits within the specified max_length. Imagine you have max_length 32K, but only 10% of your examples are >30K tokens and the rest is mostly 1K. All of those 1K examples waste a lot of space (31K tokens :)).

It's already possible to use Sample Packing with Unsloth through TRL, just set packing=True in SFTTrainer: https://huggingface.co/docs/trl/v0.4.2/sft_trainer#packing-dataset-constantlengthdataset

The way this works in SFTTrainer is that the examples are concatenated together, interspersed with EOS, forming one large example. This may be fine for pre-training, but you can easily see how it might corrupt fine-tuning where examples are highly related. That's because the model will be able to "see" the tokens from the other examples, thus allowing the model to cheat. Another reason is that popular fine-tuning templates like ChatML use EOS inside as well. At the very least, such packed examples are way out of distribution for actual inference later on.

There is a patch that solves this issue by correctly adjusting the attention mask:

This patch should be compatible with Unsloth, but it was rejected by HF team as it requires patching of flash-attention which is something they don't want to do.

Sample packing can bring order of magnitude speedup, but in order for it to be worth it, it needs to be implemented right.

Given that Unsloth is all about speed, and already uses patching to achieve some of the improvements, it seems like it would fit right in!

Activity

  1. nivibilla commented on Jan 25, 2024

    @nivibilla

    @danielhanchen I'm happy to port the implementation over if you want to include it in unsloth. It would look like a separate training script with the necessary files being included in repo.

  2. nivibilla commented on Jan 25, 2024

    @nivibilla

    Actually on second thought I'll work on it anyway since I also need this pretty bad lol. Since I do a lot of training runs every day it would save me a lot of time.

  3. danielhanchen commented on Jan 25, 2024

    @danielhanchen
    Member

    @DreamGenX Great work on the feature request as discussed on Discord :) I also agree packing can be a valuable addition to the OSS! Also thanks to @nivibilla if you can add it in! But first, there are 2 main issues I see first:

    1. The MeetKai patch only patches the attention mask, which allows uncontaminated packing. However, RoPE is not solved. Although it's not a big issue, the RoPE indicies should be [0,1,2,0,1,2,3] and not [0,1,2,3,4,5,6]. This requires one to output RoPE indicies in the data collator and also fix up the RoPE kernel. It's not that big of an issue - in fact this can help with long context learning, where you make the model learn how to handle long range RoPE indices - in fact I can't remember the study where they artificially shift RoPE indices to make it forcibly learn how to do long context windows.
    2. The MeetKai patch as it stands only works with FA / FA2. I'm afraid to split Unsloth into 2 paths where only newer GPUs get access to decontaminated packing, whilst Colab and Kaggle users (T4) do not have access. A huge issue would be maintenance, since 2 routes - 1 specific Data Collator for Ampere GPUs and no packing support for non Ampere GPUs can be problematic.
    3. If in fact packing gets up upvotes (10 at least), I can work on bringing packing in general to Unsloth, since it signals to us (me + my bro) that packing is a large need.

    But those are my thoughts :) I can work on packing if my bandwidth allows - but also welcome any PRs :)

  4. nivibilla commented on Jan 25, 2024

    @nivibilla

    MeetKai said in the PR that it's okay with positional encoding?
    huggingface/trl#1235 (comment)

    He also said it could be implemented without FA but not sure how to do that.

    And yeah I mean who doesn't want 10x faster training 😅

  5. danielhanchen commented on Jan 26, 2024

    @danielhanchen
    Member

    @nivibilla Oh I wasn't saying RoPE was an issue - in fact I think it's not a bug but a feature, since you "force" the LLM to learn on longer sequences :)

    But on packing, if there's more interest, I will definitely add it to our roadmap :)) I guess I can add for the meantime support for FA2 pathways, and I'll think of a way to port it to Colab / Kaggle users :)

  6. added
    feature request
    help wanted
    on Jan 27, 2024
  7. changed the title [-][Feature Request] Decontaminated Sample Packing[/-] [+][Feature Request] 10x faster training: Decontaminated Sample Packing[/+] on Jan 27, 2024
  8. ehartford commented on Jan 31, 2024

    @ehartford

    yes please sample packing

  9. vgoklani commented on Jan 31, 2024

    @vgoklani

    Sample packing makes obvious sense, but I wonder if contamination is really an issue (?)

    During training, wouldn't the model simply learn to focus on the tokens that are contained within the BOS and EOS tokens and ignore the adjacent tokens from a different sequence?

    Suppose I wanted to take this a step further and check to see if the attention is indeed leaking beyond the BOS/EOS boundaries, what's a good way intelligently checking?

  10. nivibilla commented on Jan 31, 2024

    @nivibilla

    Contamination is definitely an issue. I've tested it on the same dataset that is heavily correlated (aspect based sentiment) and the difference between the packed and non packed is big.

  11. DreamGenX commented on Jan 31, 2024

    @DreamGenX
    Author

    The model might be able to learn to recognize the necessary patterns, such as "system message ~ starts of new example", but EOS is sometimes used inside chat templates (e.g. Bagel and Dolphin use it in their ChatML template).

    In any case, it's definitely OOD with respect to what the model will be exposed to in production.

    But I did not make any measurements / comparisons.

    You could potentially check the weight of the attention on the "improper" tokens. But the model will be very motivated to cheat, especially if you have examples that are related to each other (like different chunks of the same chat-conversation).

  12. vgoklani commented on Jan 31, 2024

    @vgoklani

    OK - then is the strategy as follows:

    1. Make one super long batch (i.e. batch_size == 1) i.e.

      https://github.com/OpenAccess-AI-Collective/axolotl/blob/main/docs/multipack.md

    2. Concatenate sequences, using BOS/EOS tokens, up to the full sequence length (based on memory limits)

    3. Use padding so the total sequence length is divisible by 64

    4. Carefully manage the RoPE embedding via the data collator (as mentioned above by @danielhanchen)

    5. Follow this snippet:

      Will attention_mask be extended to 3D? (concatenate short samples for efficient training) Dao-AILab/flash-attention#432 (comment)

    and use unpad_input_for_concatenated_sequences to manage the attention mask for each of the concatenated sequences.

    1. Run the above through flash attention.
    2. Run through MLP as normal, no changes needed (?)
    3. Rinse and repeat

    Did I miss anything? Thanks!

  13. danielhanchen commented on Feb 1, 2024

    @danielhanchen
    Member

    Ye I think it would be cool as a research paper to quantify the amount of leakage and contamination models will have. The theory was if the datasets are shuffled correctly, randomness will force gradient descent to understand not to attend further than . However, I can see there will be some contamination.

    @vgoklani I think that sounds about right

  14. shimmyshimmer commented on Dec 10, 2025

    @shimmyshimmer
    Member

    Hey everyone, we just released new Unsloth kernels and automatic uncontaminated packing!! It's enabled by default smartly and will make training 3x faster (than old Unsloth with all optimizations turned on) + use much less VRAM like 30% or more.

    Blog + info: https://docs.unsloth.ai/new/3x-faster-training-packing

    And support our tweet if you'd like: https://x.com/UnslothAI/status/1998765021170696664 Thank you!! 🥰

    Image

    CC: @Aprilhuu @DreamGenX @IsNoobgrammer @MilkClouds @O-J1 @WiseFarAI @alangshur @arnavgarg1 @bsleater @corbt @dachenlian @edwardzjl @ehartford @gotzmann @jamartin9 @jiajunly @jorlow @kostum123 @minhtcai @nguyenhuuthuat09 @nivibilla @philmas @ppeigne @rmsetaitanic @sword865 @tiendung @timothelaborie @vgoklani

  15. added
    fixed - pending confirmation
    fixed
    and removed
    help wanted
    fixed - pending confirmation
    on Dec 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestfixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions