Sub topic 8
Spotting overfitting and picking a checkpoint
Prerequisites: assume you can split a dataset, fine-tune a transformer with the Trainer API, and compute validation metrics. This chapter focuses on deciding when training has gone too far and which saved model to keep.
What overfitting looks like
Overfitting happens when a model learns details that help on the training examples but do not generalize to new text. A model can keep improving its training score while its validation score gets worse.
During fine-tuning, compare training and validation results after each epoch:
- Training loss usually decreases as the model fits the training data.
- Validation loss should decrease while the model learns useful patterns.
- Validation loss that starts rising is a common sign of overfitting.
- A validation accuracy or F1 score that stops improving also signals that more training may not help.
The first rise in validation loss is not always a problem. Metrics can vary between epochs, especially with a small validation set. Look for a sustained pattern rather than reacting to one unusual value.
Read the learning curves
A learning curve is a plot of a result against training steps or epochs. Plot both training and validation loss when diagnosing a run.
import matplotlib.pyplot as plt
epochs = [1, 2, 3, 4, 5]
train_loss = [0.48, 0.29, 0.16, 0.08, 0.04]
val_loss = [0.44, 0.31, 0.27, 0.30, 0.36]
best_epoch = min(range(len(val_loss)), key=val_loss.__getitem__) + 1
print(f"Lowest validation loss: epoch {best_epoch}")
plt.plot(epochs, train_loss, marker="o", label="training loss")
plt.plot(epochs, val_loss, marker="o", label="validation loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.tight_layout()
plt.savefig("learning_curves.png")In this example, validation loss is lowest at epoch 3. Epochs 4 and 5 make the training loss smaller, but they make validation loss larger. The checkpoint from epoch 3 is likely to generalize better.
A widening gap between training and validation loss is another warning sign. It can result from too many epochs, a learning rate that is too high, a very small dataset, or a model that has too much capacity for the task.
Save and restore the best checkpoint
Trainer can save a checkpoint after each epoch and restore the checkpoint with the best validation metric. Choose a metric that matches the task. For balanced labels, accuracy may be sufficient. For imbalanced labels, macro-F1 is often a better choice.
from transformers import TrainingArguments
args = TrainingArguments(
output_dir="imdb-distilbert",
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
greater_is_better=True,
num_train_epochs=5,
)The metric name must match a key returned by computemetrics. If the key is f1, use metricforbestmodel="f1". Set greaterisbetter to False when selecting a loss, because lower loss is better.
Keep the test set separate until the end. Use the validation set to select epochs and hyperparameters. Use the untouched test set once for the final estimate. Repeatedly checking the test result turns it into another validation set and can make the reported score optimistic.
Reduce overfitting
Useful responses include:
- Stop after the best validation result instead of using the final epoch.
- Train for fewer epochs.
- Lower the learning rate when updates are unstable.
- Increase weight decay to discourage overly complex parameter values.
- Add more labeled examples or use a larger validation set.
- Use early stopping when validation performance has not improved for several evaluations.
Early stopping is a training policy, not a replacement for a held-out test set. It still needs a validation metric and a clear patience value, such as waiting two evaluations before stopping.
Exercise
Training loss falls for five epochs, but validation macro-F1 peaks at epoch 2 and declines afterward. Which checkpoint should you use, and why?
Show answer
Use the epoch 2 checkpoint because it has the best validation macro-F1, which measures generalization on the metric chosen for this imbalanced classification task.