Sub topic 8
Spotting overfitting and picking a checkpoint
This chapter assumes you have run the Trainer example from the earlier chapters. You need the trainer, train_ds, val_ds, test_ds, tokenizer, compute_metrics, and checkpoint objects from that code. You should also be comfortable reading a loss curve and know why a validation set is kept separate from a test set.
What overfitting looks like in fine-tuning
A pretrained encoder has tens of millions of parameters, and a labeled classification set often has only a few thousand examples. The model has enough capacity to memorize the training set. Overfitting means the model keeps getting better on training data while getting no better, or worse, on data it has not seen.
The signal is a gap between two curves:
- Training loss keeps falling, often toward zero.
- Validation loss falls at first, flattens, then rises.
The point where validation loss bottoms out is the point where more training stops helping. Later epochs fit quirks of the training examples, such as a particular phrase that happened to co-occur with one label.
In this picture, the checkpoint saved at the end of epoch 2 is the one you want. The model at epoch 5 is the one a default training run would hand you.
Reading the curves from a Trainer run
The Trainer records everything it logs in trainer.state.log_history, a list of dictionaries. Training rows contain a loss key. Evaluation rows contain eval_loss and one eval_ key per metric. This code puts both on one per-epoch table.
import numpy as np
import pandas as pd
history = pd.DataFrame(trainer.state.log_history)
# Training loss is logged every `logging_steps` (default 500), not once per epoch.
# Average the logged values within each epoch so the two curves are comparable.
train_rows = history.dropna(subset=["loss"])
train_per_epoch = train_rows.groupby(np.ceil(train_rows["epoch"]))["loss"].mean()
eval_rows = history.dropna(subset=["eval_loss"]).set_index("epoch")
eval_rows = eval_rows[["eval_loss", "eval_accuracy", "eval_f1"]]
eval_rows.index = eval_rows.index.astype(float)
table = eval_rows.join(train_per_epoch.rename("train_loss"))
print(table.round(4))Check these things when you read the table:
- Direction of validation loss. A rise for two or more consecutive evaluations is a reliable sign. A single bump can be noise.
- Direction of validation metric. Loss and F1 can disagree. A classifier can become overconfident on its wrong answers, which raises cross-entropy loss, while its argmax predictions stay the same or improve. If loss rises but F1 is still climbing, you are not yet in serious trouble.
- Size of the gap. A training loss of 0.02 against a validation loss of 0.40 means the model has memorized the training data, even if validation accuracy still looks fine.
| Observation | Likely meaning | First thing to try |
|---|---|---|
| Train loss falls, validation loss rises | Overfitting | Fewer epochs, pick an earlier checkpoint |
| Both losses high and flat | Underfitting or learning rate too low | Raise the learning rate, train longer |
| Validation loss jumps up and down | Learning rate too high, or a tiny validation set | Lower the learning rate, enlarge the validation set |
| Validation metric far above test metric | Validation set leaked into training, or you tuned on it too long | Re-check splits, report test once |
| Loss rises, F1 still rises | Overconfidence, not yet damaging accuracy | Select on F1, keep watching |
What causes it and what helps
Overfitting in fine-tuning usually comes from one of four things: a small training set, too many epochs, a learning rate that is too high, or a model that is large for the task. The remedies follow from the causes.
- Fewer epochs. For BERT-style encoders, two to four epochs is the usual range. Three epochs is a sensible default, and most of the benefit often arrives in the first one or two.
- Lower learning rate. Values from 1e-5 to 5e-5 are typical. A rate that is too high can also damage the pretrained weights early in training, which is a different failure from overfitting.
- Weight decay. The
weight_decay=0.01already in the earlier arguments adds mild regularization. It will not rescue a run that trains for too long. - More or better data. Adding labeled examples reduces overfitting more than any setting. So does removing near-duplicates, which let the model memorize by repetition.
- A smaller or frozen model. A smaller checkpoint, or LoRA (covered later), limits how much the model can change.
Truncation does not cause overfitting directly, but it can change what the model has to learn. If max_length=256 cuts off the sentence that carries the label, the model learns from the remaining words. That makes it rely on spurious cues.
Picking a checkpoint automatically
A checkpoint is a saved copy of the model at a point during training. With save_strategy="epoch", the Trainer writes one at the end of each epoch. Three arguments turn those saves into model selection:
load_best_model_at_end=Truereloads the best checkpoint when training finishes, sotrainer.modelends up as the best model, not the last one.metric_for_best_model="f1"names the metric that defines "best". The Trainer accepts it with or without theeval_prefix. The name must match a key yourcompute_metricsreturns, or beloss.greater_is_bettertells the Trainer which direction is good. It defaults toTruefor metrics andFalsewhen the metric islossor ends inloss. Set it explicitly so the intent is visible.
Two rules cause most of the errors here. The evaluation and save strategies must be the same (both "epoch", or both "steps" with matching eval_steps and save_steps). Otherwise load_best_model_at_end raises an error at the start of training. And the metric you choose must be computed on the validation set, never on the test set.
Stopping early
Training for a fixed number of epochs wastes time once the model has peaked. EarlyStoppingCallback stops the run when the chosen metric has not improved for a set number of evaluations. It requires load_best_model_at_end=True, a metric_for_best_model, and matching evaluation and save strategies.
from transformers import (
AutoModelForSequenceClassification,
DataCollatorWithPadding,
EarlyStoppingCallback,
Trainer,
TrainingArguments,
)
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
# Start from fresh pretrained weights so this run is independent of the last one.
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
args = TrainingArguments(
output_dir="imdb-distilbert-es",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=6, # an upper bound; early stopping may end the run sooner
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
save_total_limit=2, # keep the best checkpoint plus the most recent one
load_best_model_at_end=True,
metric_for_best_model="f1",
greater_is_better=True,
seed=42,
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
callbacks=[EarlyStoppingCallback(early_stopping_patience=2)],
)
trainer.train()
print("Best checkpoint:", trainer.state.best_model_checkpoint)
print("Best validation F1:", trainer.state.best_metric)
print(trainer.evaluate(test_ds))With early_stopping_patience=2, training stops after two consecutive evaluations that fail to beat the best score. Because evaluation happens once per epoch, the model will have trained two epochs past its peak when the run ends. load_best_model_at_end then restores the best weights, so those extra epochs cost time but do not affect the result.
trainer.state.best_model_checkpoint holds the path of the winning checkpoint folder, and trainer.state.best_metric holds its validation score. Record both. They tell you which epoch you chose, and they appear in your experiment notes.
Gotchas
- The learning rate schedule assumes the full run. The default schedule decays the learning rate linearly to zero over
num_train_epochs. If you set 6 epochs and stop after 3, the rate was still high when the run ended. A run set to 3 epochs from the start does not behave the same way. If a run stops early, rerun with the epoch count you found, so the schedule decays properly. - Disk use. Each checkpoint contains the model weights and the optimizer state, which is a few times the size of the weights alone.
save_total_limit=2caps this. The Trainer protects the best checkpoint when it deletes old ones, so settingsave_total_limit=1still keeps the best model plus the latest one. - Noisy selection. On a validation set of a few hundred examples, F1 differences of one point between epochs are within noise. Picking the maximum then mostly picks luck. Use a larger validation set, or prefer the simpler (earlier) checkpoint when scores are within noise.
- Seed variance. Two runs with different seeds can peak at different epochs and differ by a point or more. Fix
seedfor comparisons. For an important decision, run several seeds and compare the averages. - Selection metric versus goal. If you care about the minority class, select on macro-F1 or recall for that class, not accuracy. The chosen checkpoint depends on the metric you name.
- Mid-epoch evaluation. For a large dataset, one epoch can be long, and the peak can fall inside it. Use
eval_strategy="steps"with matchingeval_stepsandsave_steps, and seteval_stepsto a fraction of an epoch.
Putting it together
- Train with evaluation and saving on the same schedule.
- Plot or print train and validation loss per epoch.
- Let
load_best_model_at_endrestore the best validation checkpoint, using a metric that matches your goal. - Add early stopping to save time on long runs.
- Evaluate once on the test set and report that number.
Exercise
A run with num_train_epochs=5 logs these validation results. Training loss is 0.41, 0.22, 0.11, 0.05, 0.02 for epochs 1 to 5.
Epoch 1: evalloss 0.30, F1 0.88
Epoch 2: evalloss 0.27, F1 0.91
Epoch 3: evalloss 0.31, F1 0.92
Epoch 4: evalloss 0.37, F1 0.91
Epoch 5: evalloss 0.44, F1 0.90
(a) Which checkpoint does `loadbestmodelatend=True load with metricforbestmodel="f1", and which with metricforbestmodel="loss"? (b) With earlystopping_patience=2` and F1 as the metric, after which epoch would training stop? (c) Is the model overfitting by epoch 5?
Show answer
(a) With F1 it loads the epoch 3 checkpoint (0.92). With loss it loads epoch 2 (0.27, the lowest, and greater_is_better defaults to False for loss). (b) F1 peaks at epoch 3. Epochs 4 and 5 both fail to beat it, so two evaluations pass without improvement and training stops after epoch 5 (the whole run, here). Patience counts evaluations, so the stop happens two epochs after the peak. (c) Yes. Training loss keeps falling to 0.02 while validation loss has risen from 0.27 to 0.44 since epoch 2, and F1 has dropped from 0.92 to 0.90. The two selection metrics disagree by one epoch because loss reacts to overconfidence earlier than F1 does. Which to prefer depends on what you care about, and with differences this small a larger validation set would help decide.