The Trainer — when you don't want to write the loop
The HuggingFace Trainer wraps the standard PyTorch training loop with batteries: distributed training, mixed precision, gradient accumulation, evaluation, checkpointing, logging, and a battle-tested set of defaults. For most fine-tuning tasks, it's faster to use Trainer than to roll your own loop.
The three pieces
- The model — usually
AutoModelFor[Task].from_pretrained(...). - The dataset — usually a HuggingFace Dataset, tokenized via
.map(tokenizer, batched=True). - The training arguments — a
TrainingArgumentsobject encoding everything: epochs, batch size, LR, eval strategy, save strategy, FP16/BF16, logging dir.
What you give up vs raw PyTorch
The Trainer is opinionated. If your training loop has unusual structure (alternating two losses, custom gradient surgery, multi-stage curricula), you'll fight it. For "fine-tune model X on dataset Y", it's the right tool. For "train this novel architecture with this novel objective", roll your own loop.
When to use Trainer vs Lightning vs raw PyTorch
- HF Trainer — best for fine-tuning HF models on HF datasets. The integration is tight.
- PyTorch Lightning — best when you want loop boilerplate handled but the model isn't from HF, or you need more flexibility than Trainer gives.
- Raw PyTorch — best for novel architectures, research, or when you want maximum control. The loop you wrote in Track 4 is enough for production.