Trainer is a high-level Transformers API class that assembles a model, training configuration, batch collator, and datasets into a fine-tuning workflow. It replaces much of the manual PyTorch setup with configured presets, leaving batch size and epoch count as key choices. section 10.2.2
A practical Trainer pipeline connects:
- TrainingArguments for output locations, batch size, epochs, and checkpoint strategy. section 10.2.2
- DataCollatorForLanguageModeling for dynamic batching, padding, and causal-language-model settings such as mlm=False. section 10.2.2
- A model plus training and evaluation datasets, commonly prepared from tokenized text and a train/evaluation split. section 10.2.2
Listing 10.12 Fine-tuning GPT-2 with Hugging Face’s Trainer class
>>> from transformers import Trainer
>>> ft_model = GPT2LMHeadModel.from_pretrained("gpt2") #1
>>> trainer = Trainer(
... ft_model,
... training_args,
... data_collator=collator, #2
... train_dataset=train_dataset, #3
... eval_dataset=eval_dataset)
>>> trainer.train()
The configuration becomes executable by constructing Trainer with GPT-2, training arguments, a collator, and datasets, then calling trainer.train(). section 10.2.2
