Sub topic 6
Training with the Trainer API
This chapter assumes that you know Python functions and dictionaries, understand training and validation sets, and have a basic idea of loss and overfitting. It also assumes that you have tokenized datasets, a tokenizer, and a sequence-classification model ready to use.
The Hugging Face Trainer API is a high-level training loop. It handles batches, gradient updates, evaluation, checkpoint saving, and logging. You provide the model, datasets, training settings, and optional metric function.
The parts of a Trainer
A Trainer usually needs these objects:
| Part | Purpose |
|---|---|
| `model` | Produces class scores and training loss |
| `TrainingArguments` | Controls the training process |
| `train_dataset` | Supplies examples used for updates |
| `eval_dataset` | Supplies examples used for validation |
| `data_collator` | Pads each batch to its longest sequence |
| `compute_metrics` | Converts predictions into useful metrics |
Your tokenized datasets should contain input_ids, attention_mask, and a label column. The model uses the label values to calculate its loss. Do not use the test set during training or checkpoint selection.
Configure the training loop
The following example assumes that model, tokenizer, train_ds, and val_ds already exist.
import numpy as np
import evaluate
from transformers import (
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
accuracy = evaluate.load("accuracy")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return {
**accuracy.compute(
predictions=predictions,
references=labels,
),
**f1.compute(
predictions=predictions,
references=labels,
average="macro",
),
}
args = TrainingArguments(
output_dir="imdb-distilbert",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=3,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
report_to="none",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer=tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
test_results = trainer.evaluate(test_ds)
print(test_results)compute_metrics receives the model's raw logits and the correct labels. A logit is an unnormalized score for a class. argmax selects the class with the highest score.
The data collator performs dynamic padding. Instead of padding every example to one global maximum length, it pads each batch only as much as needed. This reduces unnecessary computation.
Understand evaluation and checkpoints
With eval_strategy="epoch", Trainer evaluates the validation set after each epoch. An epoch is one complete pass through the training dataset. With save_strategy="epoch", it also saves a checkpoint after each epoch.
load_best_model_at_end=True reloads the checkpoint with the best selected metric after training finishes. In this example, the selected metric is macro-F1. This is safer than automatically using the final epoch, because validation performance may decline after the model begins to overfit.
The test evaluation happens only after the best validation checkpoint has been selected. Its result estimates performance on unseen data.
Common errors
- Setting
metric_for_best_modelto a metric thatcompute_metricsdoes not return. - Omitting the
labelcolumn, which prevents the model from calculating loss. - Evaluating only training data, which can hide overfitting.
- Using a fixed padding length for every example when dynamic padding would use less memory.
- Choosing accuracy for a highly imbalanced dataset without checking per-class performance.
Exercise
Why should the validation set choose the best checkpoint while the test set is evaluated only once at the end?
Show answer
The validation set supports training decisions. The test set should remain an independent estimate of how the selected model performs on unseen data.