Sub topic 7
Tuning the Main Hyperparameters
This chapter assumes Python, PyTorch tensors, train/validation/test splits, loss, and overfitting. You should also know the basic structure of a Hugging Face Trainer run.
Hyperparameters are settings chosen before training. They control how quickly the model learns, how much data it processes at once, and how long training continues. Good settings depend on the dataset, model, hardware, and task. Start with a simple baseline, then change one setting at a time.
Learning rate
The learning rate controls the size of each update to the model's weights.
- A learning rate that is too high can make validation loss jump or fail to decrease.
- A learning rate that is too low can make training extremely slow.
- Fine-tuning usually needs a smaller learning rate than training a model from scratch.
For transformer encoders, values between 1e-5 and 5e-5 are common starting points. The right value depends on the model and dataset.
A useful first comparison is 1e-5, 2e-5, and 5e-5. If the training loss barely changes, try a larger value. If the validation metrics become unstable, try a smaller value.
Batch size and effective batch size
The batch size is the number of examples processed before one optimizer update. Larger batches often produce smoother updates, but they require more memory.
The per-device batch size applies separately on each GPU or CPU process. Gradient accumulation processes several smaller batches before updating the weights. This gives an effective batch size of:
effective batch size = per-device batch size × number of devices × accumulation steps
For example, a batch size of 8 with two accumulation steps has an effective batch size of 16 on one device.
from transformers import TrainingArguments
args = TrainingArguments(
output_dir="imdb-distilbert",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
gradient_accumulation_steps=1,
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",
)If you run out of memory, reduce per_device_train_batch_size. Use gradient accumulation when you want a larger effective batch without storing all examples at once.
Epochs and weight decay
An epoch is one complete pass through the training set. More epochs give the model more chances to learn the task, but they also increase the risk of memorizing the training examples.
Weight decay is a regularization method. It gently discourages very large weights and can reduce overfitting. Values such as 0.01 are common for transformer fine-tuning.
A typical baseline uses two to four epochs and a small weight decay. Do not choose the final number of epochs from training loss alone. Compare validation results after each epoch.
A practical tuning process
Begin with a baseline:
- Use the pretrained checkpoint and the default tokenizer.
- Choose a moderate batch size that fits memory.
- Start with a learning rate of
2e-5. - Train for three epochs with weight decay of
0.01. - Evaluate after every epoch.
- Repeat with a small set of learning rates or batch sizes.
Change one or two related settings per experiment. Keep the validation split and random seed fixed, so differences are easier to interpret.
Reading training behavior
| Observation | Likely cause | First change to try |
|---|---|---|
| Training and validation loss both decrease slowly | Learning rate may be too low | Increase the learning rate |
| Training loss decreases, validation loss rises | Overfitting | Reduce epochs or increase weight decay |
| Both losses are unstable | Learning rate may be too high | Lower the learning rate |
| Training stops because of memory use | Batch is too large | Reduce batch size and use accumulation |
These signals are clues, not proofs. Check several runs and inspect validation accuracy, precision, recall, or macro-F1 alongside loss.
Exercise
A run has falling training loss, but validation F1 improves after epoch 1 and then declines. What should you try first?
Show answer
Keep the checkpoint from epoch 1, and try fewer epochs or stronger regularization such as a slightly larger weight decay.