Sub topic 7
Tuning the main hyperparameters
This chapter assumes you have already built the pipeline from the earlier chapters: a tokenized dataset with train, validation and test splits, a DistilBERT model with a classification head, a compute_metrics function, and a working Trainer run. It also assumes you know what overfitting is and can read a loss curve.
A hyperparameter is a setting you choose before training. The model does not learn it from data. Fine-tuning has a small set of hyperparameters that matter much more than the rest. You can get most of the available gain by tuning them in a sensible order. You don't need a large search.
What you are tuning
Fine-tuning starts from weights that already encode a lot about language. Your hyperparameters decide how far training moves those weights away from that starting point. If you move them too far or too fast, the model forgets useful structure and becomes unstable. If you move them too little, the model stays close to the pretrained state and never learns your labels.
The table lists the settings that matter, with the TrainingArguments field for each, its default and a common range for encoder models.
| Setting | Field | Default | Typical range |
|---|---|---|---|
| Learning rate | `learning_rate` | 5e-5 | 1e-5 to 5e-5 |
| Batch size | `per_device_train_batch_size` | 8 | 16 to 64 (effective) |
| Epochs | `num_train_epochs` | 3.0 | 2 to 5 |
| Weight decay | `weight_decay` | 0.0 | 0.0 to 0.1 |
| Warmup | `warmup_ratio` | 0.0 | 0.0 to 0.1 |
| Scheduler | `lr_scheduler_type` | `linear` | `linear` or `cosine` |
Treat these ranges as starting points, not rules. They come from common practice with BERT-sized encoders. Larger models usually need smaller learning rates.
Learning rate
The learning rate sets the size of each weight update. It is the most important setting, and it is the first one to tune.
- Too high (for example 1e-3 on a pretrained encoder): the loss spikes or stays flat near the chance level. Accuracy on a balanced two-class task sits near 50%. The pretrained features are overwritten early in training. This is sometimes called catastrophic forgetting.
- Too low (for example 1e-7): the loss falls very slowly. After three epochs the model has barely moved from its starting point.
- About right: the loss drops quickly in the first epoch, then improves more slowly.
Fine-tuning uses much smaller learning rates than training from scratch, because the pretrained weights are already close to a good solution. For DistilBERT, 2e-5 is a reliable start. The default of 5e-5 often works too, but it is less forgiving on small datasets.
Warmup and the scheduler
The optimizer, AdamW, tracks running estimates of gradient statistics. These estimates are unreliable in the first few steps. A large learning rate applied at step one can push the weights somewhere bad before the estimates settle. Warmup raises the learning rate from zero to its target over the first steps. Setting warmup_ratio=0.1 spends the first 10% of training on warmup.
After warmup, the linear scheduler decays the learning rate to zero by the last step. This helps the model settle into a good region at the end of training. It also means that changing the number of epochs changes the whole schedule, not just the stopping point. A run with 3 epochs is therefore not the same as the first 3 epochs of a run with 6.
Batch size and gradient accumulation
The batch size is how many examples contribute to each weight update. Larger batches give smoother gradient estimates and use the GPU better. They also mean fewer updates per epoch. On 18,000 training examples, a batch of 16 gives 1,125 updates per epoch, and a batch of 64 gives about 281.
Memory limits the batch size you can use, and sequence length makes this worse. Doubling max_length roughly doubles the activation memory. Gradient accumulation lets you keep a large effective batch size on limited memory. The trainer runs several small batches, adds up their gradients, and applies one update.
The effective batch size is:
per_device_train_batch_size × gradient_accumulation_steps × number_of_devicesFor example, per_device_train_batch_size=8 with gradient_accumulation_steps=4 on one GPU gives an effective batch size of 32.
When you change the batch size, revisit the learning rate. A larger batch tolerates a somewhat larger learning rate, and a smaller batch usually wants a smaller one. If a run that worked at batch size 16 becomes unstable at batch size 8, lowering the learning rate is the first thing to try.
Epochs
An epoch is one full pass over the training set. Fine-tuning needs few epochs, usually 2 to 5. The model starts from a strong state and adapts fast. Past that point, extra epochs mostly let it memorize the training set.
You don't need to guess the right number in advance. Set a moderate maximum, evaluate every epoch, and keep the best checkpoint. The next chapter covers this in detail. Here, treat num_train_epochs as an upper limit and let validation results decide which epoch to keep.
Remember the linear schedule when you raise this value. Going from 3 to 5 epochs gives the model more time at a higher learning rate in the middle of training. You may see a different result than you expect from "the same run, longer".
Weight decay
Weight decay shrinks the weights slightly at each update. This discourages large weights and acts as a mild regularizer. In Trainer, it is applied to weight matrices but not to biases or LayerNorm parameters.
For fine-tuning, 0.01 is a standard value, and it is what the earlier chapter used. Its effect is usually small. If you have limited time, leave it alone and spend your budget on the learning rate. It matters more when the dataset is small and the model overfits quickly.
A small, fair sweep
You can tune the learning rate with a short loop. Two rules keep the comparison fair.
- Use a fresh model for each run. If you reuse a trained model, each run starts from the previous run's weights, and the comparison means nothing.
- Fix the seed. The seed controls the random initialization of the classification head, the order of the batches and the dropout masks. With a fixed seed, differences between runs come from the setting you changed.
For speed, the sweep below trains on a 2,000-example subset. It reuses checkpoint, train_ds, val_ds, tokenizer and compute_metrics from the earlier chapters. The best settings on a subset are not guaranteed to be the best on the full set. They are good enough to rule out clearly bad values.
from transformers import (
AutoModelForSequenceClassification,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
set_seed,
)
small_train = train_ds.shuffle(seed=0).select(range(2000))
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
def run(lr, batch_size=16, epochs=3, weight_decay=0.01, warmup_ratio=0.1, seed=42):
set_seed(seed)
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
args = TrainingArguments(
output_dir=f"sweep/lr{lr}",
learning_rate=lr,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=32,
num_train_epochs=epochs,
weight_decay=weight_decay,
warmup_ratio=warmup_ratio,
eval_strategy="epoch",
logging_strategy="epoch",
save_strategy="no",
report_to="none",
seed=seed,
)
trainer = Trainer(
model=model,
args=args,
train_dataset=small_train,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
return trainer.evaluate(), trainer.state.log_history
results = {}
for lr in [1e-5, 3e-5, 1e-4, 3e-4]:
metrics, history = run(lr)
results[lr] = metrics["eval_f1"]
print(f"lr={lr:g} val macro-F1={metrics['eval_f1']:.4f}")Setting save_strategy="no" skips checkpoint writing, since the sweep only compares scores. report_to="none" turns off external loggers such as Weights & Biases. logging_strategy="epoch" records training loss once per epoch, so log_history has one training entry and one evaluation entry for each epoch.
Space the learning rates by factors of about 3, as above. Differences of 10% between values rarely matter. Differences of 3x often do. The values at the high end may diverge. A score near the chance level at 3e-4 tells you the upper edge of the useful range, so it is a result and not an error.
Reading the logs
The returned log_history lets you compare training and validation loss per epoch without a plotting library.
metrics, history = run(2e-5)
for entry in history:
if "loss" in entry:
print(f"epoch {entry['epoch']:.0f} train loss {entry['loss']:.4f}")
if "eval_loss" in entry:
print(f"epoch {entry['epoch']:.0f} val loss {entry['eval_loss']:.4f} "
f"val F1 {entry['eval_f1']:.4f}")Healthy training shows both losses falling. If training loss keeps falling while validation loss rises, the model has begun to overfit.
A tuning order
Tune one setting at a time, in order of impact. Changing everything at once makes it impossible to tell which change helped.
The final step matters. You choose every value using the validation set. The test set stays untouched until the end. If you tune against the test set, your reported score is optimistic, because you selected the settings that happen to do well on those particular examples.
Common errors and edge cases
- Comparing single runs. Fine-tuning has run-to-run variance, especially on small datasets. A difference of 0.3 points in F1 between two seeds is usually noise. If two settings are close, repeat each with three seeds and compare the averages.
- Reusing a model across runs. Always create the model inside the function that runs the experiment, as
rundoes above. - Tuning on accuracy when classes are imbalanced. The metric guiding your choices must reflect what you care about. The earlier chapter on metrics explains why macro-F1 is safer here.
- Changing epochs without thinking about the schedule. The learning rate decays to zero over the whole run, so the epoch count changes the whole curve.
- Out-of-memory errors. Lower the per-device batch size, add gradient accumulation to keep the effective size, or reduce
max_length. Do not simply change the learning rate to fix a memory problem. - Loss that becomes
nan. This is usually a learning rate that is too high, sometimes combined with mixed precision. Lower the learning rate and add warmup. - Ignoring the compute budget. Each sweep value costs a full training run. On a large dataset, tune on a subset, as above, and spend the full-size run only on the final configuration.
Summary of the working model
- The learning rate controls how far training moves the pretrained weights. Keep it small, and tune it first.
- Batch size trades update frequency against stability and memory. Use gradient accumulation to reach a larger effective batch size.
- Two to five epochs is typical. Treat the epoch count as a maximum and let validation scores choose the checkpoint.
- Weight decay and warmup are secondary. Reach for them when the model overfits or training is unstable.
- Change one setting at a time, use a fresh model and a fixed seed for each run, and confirm close results with several seeds.
Exercise
You train DistilBERT with learning_rate=1e-3 and see validation accuracy stuck near 50% on a balanced two-class dataset, with training loss that does not fall. A teammate suggests training for 10 more epochs. What would you do instead, and why?
Show answer
Lower the learning rate (for example to 2e-5) and add warmup (for example warmup_ratio=0.1), then rerun with a fresh model. A learning rate of 1e-3 is far too high for a pretrained encoder. It overwrites the pretrained weights, so the loss does not fall and accuracy stays at the chance level. More epochs at the same learning rate would not fix this and would only waste compute.
Exercise
Your GPU can only fit a per-device batch size of 8, but you want an effective batch size of 32 on one GPU. Which TrainingArguments value do you set, and to what? Does the number of weight updates per epoch change compared with a batch size of 8 without accumulation?
Show answer
Set gradientaccumulationsteps=4, because 8 × 4 × 1 device = 32. Yes, the number of updates changes. The trainer applies one update for every 4 small batches, so there are about 4 times fewer updates per epoch than with a plain batch size of 8.
Exercise
In a learning-rate sweep, lr=2e-5 gets a validation macro-F1 of 0.912 and lr=3e-5 gets 0.915, each from one run with the same seed. Can you conclude that 3e-5 is better? What should you do?
Show answer
No. A 0.3-point difference from single runs is within typical seed-to-seed variance for fine-tuning. Repeat each setting with several seeds (for example three) and compare the mean and spread. If the averages are still close, pick either value, or choose the one that was more stable across seeds.