In the 🤗 Transformers world, a data collator is simply a callable (function or object) that takes a list of individual samples (dictionaries of tensors) and “collates” them into a single batch. Its main jobs are:
- Batching: stacking your
input_ids, attention_mask, labels, etc., along a new first dimension (the batch dimension).
- Padding/truncation: ensuring that all sequences in the batch have the same length.
- Task-specific transforms: e.g. dynamically masking tokens for masked-language-modeling (MLM), shifting decoder inputs for seq2seq, collating pixel values for vision models, etc.
—
🔧 Built-in Data Collators
-
DataCollatorWithPadding
- Pads inputs (and labels, if present) to the length of the longest sample in the batch.
- Great for most classification or regression tasks.
-
DataCollatorForLanguageModeling
- Extends
DataCollatorWithPadding plus applies random token masking (MLM).
- Useful when you train BERT‐style models from scratch.
-
DataCollatorForWholeWordMask
- Same as above, but ensures that when you mask a token, you mask the entire word.
-
DataCollatorForSeq2Seq
- Pads inputs and decoder inputs/labels appropriately for encoder–decoder models (T5, BART, …).
- You can even pass
label_pad_token_id=-100 so that your loss ignores padding.
There are more specialized collators (e.g. for token classification, vision, audio, multimodal…), and you can always roll your own.
—
🔗 How to hook it up
With PyTorch’s DataLoader
from transformers import DataCollatorWithPadding, AutoTokenizer
from torch.utils.data import DataLoader
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
collator = DataCollatorWithPadding(tokenizer)
loader = DataLoader(
my_dataset, # any torch Dataset returning dicts
batch_size=16,
shuffle=True,
collate_fn=collator # ← here!
)
With 🤗 Trainer
from transformers import Trainer, TrainingArguments
trainer = Trainer(
model=my_model,
args=TrainingArguments(...),
train_dataset=train_ds,
eval_dataset=eval_ds,
data_collator=collator # ← Trainer will call it under the hood
)
—
Writing your own data collator
If you have a custom need (e.g. dynamic buckets, special masking logic), you can subclass or write a simple function:
class MyCollator:
def __init__(self, tokenizer, pad_to_multiple_of: int = None):
self.tokenizer = tokenizer
self.pad_to_multiple_of = pad_to_multiple_of
def __call__(self, features: list[dict]):
# 1. let the HF padding utility do most of the work
batch = self.tokenizer.pad(
features,
padding="longest",
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors="pt",
)
# 2. add any extra logic you need
# batch["labels"] = some_custom_label_logic(batch)
return batch
—
TL;DR
A data collator is the piece that turns a list of single examples into one nicely padded, masked, batched tensor dictionary. It lives as the collate_fn in PyTorch’s DataLoader or the data_collator in 🤗 Trainer, and Hugging Face gives you plenty of ready-made ones for common NLP tasks.