Skip to content
Back to skills

Length Sorted Batching

ASecurity

Sort texts by length before batching with dynamic padding to minimize wasted padding tokens and speed up transformer inference

  • 61 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added September 12, 2026
datapython

Security analysis

A100/100

Scanned September 12, 2026

npx -y skills add wenmin-wu/ds-skills --skill length-sorted-batching --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Length Sorted Batching?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Length Sorted Batching
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/wenmin-wu-length-sorted-batching/badge)](https://www.skillsdirectory.com/skills/wenmin-wu-length-sorted-batching)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: nlp-length-sorted-batching
description: Sort texts by length before batching with dynamic padding to minimize wasted padding tokens and speed up transformer inference
---

# 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

```python
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

- **Character vs token length**: character length is faster to compute and correlates well enough
- **Inference only**: for training, use bucket sampling instead (preserves randomness within length ranges)
- **Restore order**: always save the original index — predictions must align with input rows
- **Batch size**: larger batches amplify the benefit; small batches (4-8) see less improvement

## References

- [all-minilm-l6-v2 tuning_model_add](https://www.kaggle.com/code/yuiwai/all-minilm-l6-v2-tuning-model-add)
- [LECR Inference P](https://www.kaggle.com/code/ragnar123/lecr-inference-p)

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.