Uncontaminated Sample Packing #3525
                
     Open
            
            
          
      
        
          +1,377
        
        
          −215
        
        
          
        
      
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
This PR adds sample packing support. It uses TRL's SFTConfig
packing=Trueandpadding_free=Trueargs to pack the sequences, and we computepacked_seq_lengthsmetadata and thread it through the model forward pass. This metadata is used to create block causal masks for SDPA and xformers attention, and is passed to the flash attention varlen API which handles the block causal masking itself under the hood (we need to do this ourselves because of our custom forward pass, whereas TRL handles the sequence length metadata internally in their trainer).I added a few unit tests. I also wrote a quick bash script for smoke testing some common model architectures: gist, which runs.
Below is a comparison of short
unsloth/qwen2.5-0.5btraining runs. The losses don't match because we're seeing more / different samples on each step. But the scale and trend match, which is the important bit.Commands:
No sample packing:
Sample packing:
Note that we use
--per_device_train_batch_size 1in the latter case since we are packing multiple examples into a single[1, max_seq_length]tensor.The benefit of this approach is that we're able to discard a lot of zero padding, and therefore get higher token/s training throughput. The below plot shows that we're able to get through our dataset ~20% faster. These gains depend on the dataset and configured
--max_seq_length; if we increase this we generally get better packing efficiency => higher throughput.I manually tested on SDPA and flash attention, but I still need to test xformers attention since I couldn't get it to build for blackwell.
TODO