Sub topic 6
Training with the Trainer API
This chapter assumes you have tokenized datasets with truncation, a pretrained encoder with a two-class classification head, and a metric function. It also assumes you know what loss, epochs, and batches are. Here you connect those parts with Trainer, run a fine-tuning job, and read what it does.
What the Trainer does for you
Fine-tuning in plain PyTorch needs a loop. The loop batches data, runs the forward pass, computes the loss, backpropagates, steps the optimizer and learning-rate scheduler, and periodically evaluates and saves. The Trainer class from Hugging Face Transformers implements that loop. It also handles mixed precision, gradient accumulation, logging, checkpointing, and multi-GPU execution.
You give it five things:
| Input | Role |
|---|---|
| `model` | The encoder with its classification head |
| `args` | A `TrainingArguments` object holding every setting |
| `train_dataset` and `eval_dataset` | Tokenized splits |
| `data_collator` | Turns a list of examples into one padded batch |
| `compute_metrics` | Turns logits and labels into a dictionary of numbers |
The Trainer does not tokenize, split, or choose metrics. Those decisions stay in your code.
A complete training script
The script below rebuilds the tokenized IMDB splits from the earlier chapters so that it runs on its own. Everything after the tokenization is the new material. Install transformers, datasets, evaluate, scikit-learn, and accelerate first.
import numpy as np
import evaluate
from datasets import load_dataset
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
checkpoint = "distilbert-base-uncased"
raw = load_dataset("imdb")
split = raw["train"].train_test_split(test_size=0.1, seed=42)
train_ds, val_ds, test_ds = split["train"], split["test"], raw["test"]
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=256)
train_ds = train_ds.map(tokenize, batched=True)
val_ds = val_ds.map(tokenize, batched=True)
test_ds = test_ds.map(tokenize, batched=True)
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
accuracy = evaluate.load("accuracy")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=-1)
return {
**accuracy.compute(predictions=preds, references=labels),
**f1.compute(predictions=preds, 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",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
print(trainer.evaluate(test_ds))On a single consumer GPU this takes roughly 15 to 30 minutes. On a CPU it takes hours, so try a subset first, for example train_ds.select(range(2000)).
What happens inside `train()`
The IMDB training split has 25,000 reviews. After the 10% validation split, 22,500 remain. With a batch size of 16, one epoch is 1,407 optimizer steps, and three epochs are 4,221 steps. The Trainer repeats the same cycle for every step.
Several details of this loop explain behavior you will see in practice:
- Loss. For a model with a classification head, the loss is cross-entropy. The model computes it internally when the batch contains a
labelskey, which is why you do not pass a loss function. - Optimizer. The default is AdamW with the
learning_rateandweight_decayyou set. Weight decay is not applied to biases or LayerNorm weights. - Scheduler. The default is a linear decay from
learning_rateto zero over all training steps. The learning rate is therefore highest early in training and falls as training ends. - Dropped columns. With
remove_unused_columns=True, the default, theTrainerremoves dataset columns that the model'sforwardmethod does not accept. The rawtextcolumn disappears from batches, which is what you want. - Labels. The dataset needs a
labelorlabelscolumn of integer class ids. A string label column causes an error at the first batch.
The arguments that matter most
TrainingArguments has many fields. These are the ones you will touch regularly.
| Argument | Default | Purpose |
|---|---|---|
| `learning_rate` | 5e-5 | Peak step size. For encoders, 2e-5 to 5e-5 is the usual range. |
| `per_device_train_batch_size` | 8 | Examples per GPU per step. Larger batches use more memory. |
| `gradient_accumulation_steps` | 1 | Sum gradients over N batches before updating. Effective batch size is batch size times N times the number of devices. |
| `num_train_epochs` | 3.0 | Full passes over the training data. |
| `weight_decay` | 0.0 | Regularization strength for AdamW. |
| `warmup_ratio` | 0.0 | Fraction of steps used to ramp the learning rate up from zero. |
| `fp16` / `bf16` | False | Mixed precision. It reduces memory use and speeds up GPU training. Use `bf16` on hardware that supports it. |
| `logging_steps` | 500 | How often training loss is logged. |
| `save_total_limit` | None | Maximum number of checkpoints kept on disk. |
Chapter-level guidance on choosing values comes later. For now, treat the values above as a reasonable starting point for a base-size encoder.
Evaluation and checkpoint selection
The settings eval_strategy="epoch" and save_strategy="epoch" make the Trainer evaluate and save once per epoch. The load_best_model_at_end=True setting then needs the two strategies to match, because it can only pick among checkpoints that were saved. If they differ, TrainingArguments raises an error.
The metric_for_best_model="f1" setting names the key your compute_metrics function returns. The Trainer adds the eval_ prefix on its own, so the logged key is eval_f1. By default, a higher value counts as better. For a loss-like metric, also set greater_is_better=False. If you set load_best_model_at_end=True and omit metric_for_best_model, the Trainer picks by validation loss.
At the end of training, trainer.evaluate(test_ds) scores the reloaded best model on the untouched test set. The returned keys start with eval_, so they look like validation results. To label them clearly, pass metric_key_prefix="test":
test_metrics = trainer.evaluate(test_ds, metric_key_prefix="test")
print(test_metrics["test_f1"], test_metrics["test_accuracy"])Use the test set once, after you have finished choosing hyperparameters. If you tune against it, its score stops being an honest estimate.
Reading the training output
During training the Trainer prints a table or log lines. A typical set of numbers looks like this: training loss around 0.25 at the first logged step, validation loss around 0.22 after epoch one, and an eval_f1 of about 0.92 to 0.93. Treat these as rough figures, since the exact values vary by run.
Three things to check:
- Training loss goes down steadily. If it stays flat near 0.69, which is ln 2 for two balanced classes, the model is not learning. Look for a learning rate that is far too small or too large, or labels that do not match the inputs.
- Validation loss follows training loss at first. If validation loss rises while training loss keeps falling, the model is overfitting. The best-checkpoint setting protects you from keeping the worst epoch, but you may also want fewer epochs.
- The metric moves in the right direction. Accuracy and F1 should rise after epoch one. A metric stuck at 0.5 on balanced data means the model predicts one class for everything.
The trainer.state.log_history attribute holds every logged dictionary, so you can plot curves yourself:
history = trainer.state.log_history
eval_rows = [row for row in history if "eval_f1" in row]
for row in eval_rows:
print(row["epoch"], row["eval_loss"], row["eval_f1"])Common errors and fixes
- CUDA out of memory. Lower
per_device_train_batch_size, then raisegradient_accumulation_stepsto keep the effective batch size. Reducingmax_lengthduring tokenization also helps, since attention memory grows with sequence length. Enablingfp16=Trueorbf16=Truecuts activation memory. - "Expected input batchsize to match target batchsize" or tensor-size errors in the collator. You usually padded during tokenization to different lengths, or removed the collator. Tokenize with
truncation=Trueonly, and letDataCollatorWithPaddingpad each batch. KeyError: 'f1'when picking the best model. Themetric_for_best_modelname does not match a key fromcompute_metrics. Print the dictionary your function returns.- Metrics look wrong or missing.
evaluate.load("f1")needsscikit-learn. Also remember thataverage="macro"is required for the binary F1 metric to average over both classes. Without it, F1 is computed for the positive class only. - Training was interrupted. Resume with
trainer.train(resume_from_checkpoint=True). This restores weights, optimizer state, scheduler state, and the step counter from the latest checkpoint inoutput_dir. - Disk fills up. Each checkpoint stores model weights plus optimizer state, which is about three times the model size. Set
save_total_limit=2. Withload_best_model_at_end=True, theTrainerkeeps the best checkpoint in addition to the latest ones.
Reproducibility
Two runs with the same settings give slightly different numbers, because classification heads start from random weights and batches are shuffled. Set seed=42 in TrainingArguments, or call transformers.set_seed(42) before building the model. This fixes the head initialization and the shuffling order. GPU kernels can still add tiny nondeterminism. When comparing two configurations, differences of a few tenths of a point in F1 are often within run-to-run noise. Repeat each run with several seeds before declaring a winner.
Exercise
Your validation set has 2,500 examples, you train on 22,500 examples with per_device_train_batch_size=8, gradient_accumulation_steps=4, and one GPU. What is the effective batch size, and how many optimizer updates happen in one epoch (round up)?
Show answer
The effective batch size is 8 × 4 = 32. One epoch has 22,500 / 32 = 703.125 updates, which rounds up to 704 optimizer updates. The Trainer still runs 2,813 forward and backward passes, because 22,500 / 8 = 2,812.5 rounds up to 2,813, and it updates the weights once every 4 of them.
Exercise
You set eval_strategy="epoch" and save_strategy="steps" with load_best_model_at_end=True. What happens, and how do you fix it?
Show answer
TrainingArguments raises an error, because loading the best model requires the evaluation and save strategies to match so that every evaluated point has a saved checkpoint. Set both to "epoch", or set both to "steps" with the same eval_steps and save_steps (the save interval must be a multiple of the evaluation interval).