Skip to content
C.W.K.
Lesson 02 of 08 · published

Data Collators: Padding and Beyond

~22 min · training, collator

Level 0Scout
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

The collator's job

A data collator takes a list of tokenized examples (ragged lengths) and produces a single batch tensor (uniform shape). The standard ones:

  • DataCollatorWithPadding — pads input_ids to the longest in the batch.
  • DataCollatorForLanguageModeling — for MLM (masked) or CLM (causal) pre-training. mlm=True randomly masks tokens.
  • DataCollatorForSeq2Seq — pads encoder + decoder side independently for encoder-decoder models.
  • Older trl shipped DataCollatorForCompletionOnlyLM; it is gone. Today SFTConfig's completion_only_loss (on by default for prompt-completion data) and assistant_only_loss=True (for conversational data) mask the prompt so loss only flows over the assistant response.

Why collators matter for SFT

If you train on chat data without that masking, the model is also learning to predict the user prompt. That's wasted gradient and often degrades chat behavior. Response-only loss is the right default for instruction tuning.

Code

Padding collator (classification)·python
from transformers import DataCollatorWithPadding
collator = DataCollatorWithPadding(tokenizer=tok, padding="longest")  # or "max_length"
Loss on responses only (instruction tuning)·python
from trl import SFTConfig

# Conversational (messages) data: loss flows only over assistant turns
cfg = SFTConfig(
    output_dir="./sft-out",
    assistant_only_loss=True,
)

# Prompt/completion data: completion_only_loss is on by default
cfg_pc = SFTConfig(output_dir="./sft-out", completion_only_loss=True)
MLM collator (BERT-style pre-training)·python
from transformers import DataCollatorForLanguageModeling
collator = DataCollatorForLanguageModeling(
    tokenizer=tok,
    mlm=True,
    mlm_probability=0.15,  # 15% masking, the BERT default
)

External links

Exercise

Take a small instruction-tuning dataset (e.g., HuggingFaceH4/no_robots). Set up SFTTrainer twice: once with loss on the full sequence, once with assistant_only_loss=True. Train each for 100 steps. Compare loss curves and final outputs.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign in — Please sign in to comment.

No comments yet — be the first.