Skip to content

[Feature Request] train_completions and packing=True #109

Closed

Description

@akjindal53244

Hi unsloth team,

I am wondering how to enable packing = True when I need to only train on output tokens for a `<input, output>' text pair eg: '<question, answer>'. This is a general use-case for instruction fine-tuning problems where fine-tuning is performed on output token only while keeping input/instruction fixed. In this case, supporting packing greatly improves fine-tuning speed.

P.S.: This functionality is supported in axolotl :)

Activity

  1. danielhanchen commented on Jan 20, 2024

    @danielhanchen
    Member

    @akjindal53244 Ye it seems like Huggingface's SFTrainer only supports DataCollatorForCompletionOnlyLM for packing = False. I'll ask Younes from HF about this :) A solution would be to write a custom data collator which can solve this issue

  2. added
    feature request
    on Jan 27, 2024
  3. eabdullin commented on May 24, 2024

    @eabdullin

    @akjindal53244 You could create your own DataCollator. Here I created one, but for other purpose. I needed to ignore code outputs, but in your case, you have to be able to determine the end of sequence and response template when Packing enabled.

    # we don't want train on the code ouputs, so let's ignore them
    class DataCollatorForCompletionAndIgnoredCodeOutputs(DataCollatorForCompletionOnlyLM):
        def __init__(self, output_start_template: str, output_end_template: str, **kwargs,):
            super().__init__(**kwargs)
            self.output_start_template_token_ids = self.tokenizer.encode(output_start_template, add_special_tokens=False)
            self.output_end_template_token_ids = self.tokenizer.encode(output_end_template, add_special_tokens=False)
    
        def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]:
            batch = super().torch_call(examples)
            for i in range(len(examples)):
                response_token_ids_start_idx = None
                start_ix = None
                for idx in range(len(batch["labels"][i])):
                    if batch["labels"][i][idx : idx + len(self.output_start_template_token_ids)].tolist() == self.output_start_template_token_ids:
                        start_ix = idx
                    if start_ix is not None and start_ix != idx and batch["labels"][i][idx : idx + len(self.output_end_template_token_ids)].tolist() == self.output_end_template_token_ids:
                        batch["labels"][i, start_ix+len(self.output_start_template_token_ids):idx] = self.ignore_index
                        start_ix = None
            return batch
    
    
    data_collator = DataCollatorForCompletionAndIgnoredCodeOutputs(
        output_start_template = '```output',
        output_end_template = '```',
        response_template = '\nAssistant:\n',
        tokenizer=tokenizer
    )
    
  4. danielhanchen commented on May 24, 2024

    @danielhanchen
    Member

    @eabdullin Would you be contribute this into Unsloth? :) Super appreciate it :)

  5. gardner commented on Oct 6, 2024

    @gardner

    It looks like this has been implemented as train_on_responses_only() from unsloth.chat_templates.

  6. danielhanchen commented on Oct 9, 2024

    @danielhanchen
    Member

    @gardner Yep apologies forgot to tell you guys - it should also function with packing = True I think - I haven't tested, but it should

  7. added
    fixed - pending confirmation
    on Oct 9, 2024
  8. changed the title [-]How to enable training on competition only along with packing = True[/-] [+][Feature Request] `train_completions` and `packing=True`[/+] on Oct 9, 2024
  9. 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: @akjindal53244 @eabdullin @gardner

  10. added a commit that references this issue on Mar 12, 2026
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 - pending confirmation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions