Length sorted batching

From wenmin-wu/ds-skills · View interactive version

Length sorted batching is an AI agent skill from the GitHub repository wenmin-wu/ds-skills. Sort texts by length before batching with dynamic padding to minimize wasted padding tokens and speed up transformer inference

How to use this skill

Skill file

Length-Sorted Batching

Overview

When using dynamic padding (padding='longest'), batch padding length equals the longest sequence in the batch. If a 512-token text lands in a batch of 20-token texts, every sample pads to 512. Sorting by length first ensures each batch contains similarly-sized texts, drastically reducing total padding tokens. Typical speedup: 1.5–3x on inference.

Quick Start

from transformers import DataCollatorWithPadding

df['length'] = df['text'].apply(len)
df = df.sort_values('length').reset_index(drop=True)

dataset = Dataset.from_pandas(df)
tokenized = dataset.map(lambda x: tokenizer(x['text'], truncation=True),
                        batched=True)

loader = DataLoader(
    tokenized, batch_size=32, shuffle=False,
    collate_fn=DataCollatorWithPadding(tokenizer, padding='longest')
)

Workflow

  1. Compute text length (character or token count) for each sample
  2. Sort DataFrame by length ascending
  3. Save original index to restore order after inference
  4. Create DataLoader with shuffle=False and padding='longest'
  5. Run inference, then reorder predictions to original order

Key Decisions

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.