Fine-Tuning: Learning Rate, Warm-up and Early Stopping
Fine-tuning continues training a pretrained model on your task, usually with every weight free to change. It is the most accurate way to adapt a model when you have a few thousand labels or more, and the easiest one to get wrong: the same code that gives a strong model with one learning rate gives a broken one with a learning rate ten times larger. This lesson is the recipe that makes fine-tuning reliable: a small learning rate, a short warm-up, a decaying schedule, and early stopping on a validation set.
Why fine-tuning needs its own settings
Training from scratch starts at a random point and has to travel far; fine-tuning starts at a good point and should only move a little. Three consequences:
- A small learning rate. Large steps throw away what pretraining learned. Typical peaks with AdamW: to for full fine-tuning of BERT-size and larger transformers, to for a new head or for LoRA, about with SGD for CNNs (ten times below the from-scratch rate).
- A warm-up. The new head is random, so the first gradients are large and point in arbitrary directions, and Adam's second-moment estimate is based on only a few steps. A linear ramp from 0 to the peak over the first 5 to 10 % of the steps keeps those first updates small.
- Few epochs and early stopping. A pretrained model fits a small data set in 2 to 5 epochs and starts overfitting soon after. The validation loss, not a fixed epoch count, decides when to stop.
The schedule
With total steps, warm-up steps and peak , the two common fine-tuning schedules are
Linear warm-up with linear decay is the BERT recipe (get_linear_schedule_with_warmup in Transformers); warm-up with cosine decay is the common choice for vision and LLM fine-tuning. The schedules themselves are derived in Learning-Rate Schedules and Warm-Up. In the lab, pick schedule 3 (warm-up + cosine) and move the warm-up and sliders. The loss curve is the lab's illustrative toy formula, not a real training run: it only shows that a larger rate settles at a higher floor.
Early stopping evaluates the validation loss after every epoch (or every few hundred steps), remembers the weights with the lowest value, and stops after patience evaluations without an improvement; the remembered weights are the result (Early Stopping and Checkpointing).
From scratch: a learning-rate sweep with early stopping
The pretrained digit MLP of the earlier lessons (one hidden layer of 64 units, trained on one half of the digits) is fine-tuned in full on the other half, shifted one pixel to the right (a moved camera). The labelled data is split three ways: 200 images to train, 100 to validate, 599 to test. Each run uses Adam in mini-batches of 50 with 20 warm-up steps and cosine decay over at most 300 epochs, early stopping with patience 30 on the validation loss, and restores the best epoch. The learning rate is chosen by the validation loss; the test set is used once, for the chosen rate. The last column measures how far fine-tuning moved the pretrained first layer, .
import math
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, y_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
source = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, y_src)
W0, b0 = source.coefs_[0], source.intercepts_[0]
X_new = np.roll(X_tgt.reshape(-1, 8, 8), 1, axis=2).reshape(-1, 64) # target: shifted 1 pixel right
rng = np.random.default_rng(0)
per_class = [rng.permutation(np.where(y_tgt == c)[0]) for c in range(10)]
tr = np.concatenate([p[:20] for p in per_class]) # 200 train
va = np.concatenate([p[20:30] for p in per_class]) # 100 validation
te = np.setdiff1d(np.arange(len(y_tgt)), np.concatenate([tr, va])) # 599 test
head0 = rng.normal(0, 0.1, (64, 10)) # the same new head for every run
def logits(P, A):
h = np.maximum(0, A @ P[0] + P[1])
return h, h @ P[2] + P[3]
def loss(P, idx):
z = logits(P, X_new[idx])[1]; z = z - z.max(1, keepdims=True)
return float(np.mean(np.log(np.exp(z).sum(1)) - z[np.arange(len(idx)), y_tgt[idx]]))
def accuracy(P, idx):
return float((logits(P, X_new[idx])[1].argmax(1) == y_tgt[idx]).mean())
def lr_at(t, peak, T, warmup=20): # linear warm-up, then cosine decay
if t < warmup:
return peak * (t + 1) / warmup
return peak * 0.5 * (1 + math.cos(math.pi * (t - warmup) / (T - warmup)))
def fine_tune(peak, max_epochs=300, patience=30, batch=50):
order = np.random.default_rng(1)
P = [W0.copy(), b0.copy(), head0.copy(), np.zeros(10)]
m, v, t = [0] * 4, [0] * 4, 0
T = max_epochs * len(tr) // batch
best, best_epoch, best_P, wait = np.inf, 0, None, 0
for epoch in range(1, max_epochs + 1):
for idx in np.array_split(order.permutation(tr), len(tr) // batch):
A, yy = X_new[idx], y_tgt[idx]
h, z = logits(P, A)
p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(yy)), yy] -= 1; g /= len(yy)
gh = g @ P[2].T * (h > 0)
G = [A.T @ gh, gh.sum(0), h.T @ g, g.sum(0)]
eta = lr_at(t, peak, T); t += 1
for i in range(4): # Adam
m[i] = 0.9 * m[i] + 0.1 * G[i]; v[i] = 0.999 * v[i] + 0.001 * G[i] ** 2
P[i] = P[i] - eta * (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.999 ** t)) + 1e-8)
val = loss(P, va)
if val < best: # early stopping on the validation loss
best, best_epoch, best_P, wait = val, epoch, [q.copy() for q in P], 0
else:
wait += 1
if wait >= patience:
break
return best_P, best_epoch, epoch, best
print("peak lr | best epoch | stopped | val loss | val acc | moved W")
runs = {}
for peak in [1e-4, 1e-3, 1e-2, 1e-1]:
P, best_epoch, stopped, val = fine_tune(peak)
runs[peak] = (val, P)
drift = np.linalg.norm(P[0] - W0) / np.linalg.norm(W0)
print(f"{peak:7.0e} | {best_epoch:10d} | {stopped:7d} | {val:8.3f} | {accuracy(P, va):7.2f} | {drift:7.2f}")
chosen = min(runs, key=lambda k: runs[k][0])
print(f"chosen by validation loss: {chosen:.0e} -> test accuracy {accuracy(runs[chosen][1], te):.3f} (599 images, used once)")peak lr | best epoch | stopped | val loss | val acc | moved W
1e-04 | 300 | 300 | 1.311 | 0.81 | 0.12
1e-03 | 300 | 300 | 0.286 | 0.93 | 0.54
1e-02 | 71 | 101 | 0.247 | 0.93 | 0.85
1e-01 | 8 | 38 | 0.405 | 0.89 | 1.60
chosen by validation loss: 1e-02 -> test accuracy 0.915 (599 images, used once)
Four regimes in four rows:
- : too small. The validation loss is still falling at the last of the 300 epochs (1.311, accuracy 0.81). The run never converged; it moved the first layer by only 0.12 of its size.
- : slow but fine. Also uses all 300 epochs, and reaches a validation loss of 0.286.
- : best. The lowest validation loss (0.247) at epoch 71; early stopping ends the run at epoch 101, 30 epochs later, and restores epoch 71.
- : too large. The best epoch is the 8th, after which the validation loss only gets worse, and the result (0.405) is clearly behind. By then the first layer has moved by 1.60 times its own size: little of the pretrained layer is left.
The validation loss chooses , and the test set, used once, gives 0.915 on 599 images. Note that the two good rates have the same validation accuracy (0.93, on 100 images where one image is 0.01): the loss separates runs that accuracy cannot, which is why early stopping and model selection usually watch the loss.
With Transformers: the BERT recipe
The same recipe on the small pretrained BERT used throughout the course (google/bert_uncased_L-2_H-128_A-2, 4.4 million parameters) for movie-review sentiment. The rotten_tomatoes data comes with its own splits: a fixed random 1,000 training sentences from train, 300 from validation and 500 from test. AdamW with weight decay 0.01, get_linear_schedule_with_warmup with 10 % warm-up, at most 4 epochs, early stopping with patience 2 on the validation loss and the best epoch's weights restored with state_dict. Four peak learning rates, a factor of 10 apart:
import copy
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, get_linear_schedule_with_warmup
from transformers.utils import logging
logging.set_verbosity_error() # hide the "classifier newly initialised" load report
name = "google/bert_uncased_L-2_H-128_A-2"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(1000))
val = ds["validation"].shuffle(seed=0).select(range(300))
test = ds["test"].shuffle(seed=0).select(range(500))
tok = AutoTokenizer.from_pretrained(name)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_tr, X_va, X_te = enc(train), enc(val), enc(test)
y_tr, y_va, y_te = (torch.tensor(d["label"]) for d in (train, val, test))
def evaluate(model, X, y):
model.eval()
with torch.no_grad():
out = model(input_ids=X["input_ids"], attention_mask=X["attention_mask"], labels=y)
return out.loss.item(), (out.logits.argmax(1) == y).float().mean().item()
def fine_tune(lr, warmup_frac=0.1, epochs=4, patience=2):
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
steps = epochs * -(-len(y_tr) // 32) # batches per epoch, rounded up
sched = get_linear_schedule_with_warmup(opt, int(warmup_frac * steps), steps)
g = torch.Generator().manual_seed(0)
best, best_state, best_epoch, wait, first_losses = float("inf"), None, 0, 0, []
for epoch in range(1, epochs + 1):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(32):
loss = model(input_ids=X_tr["input_ids"][idx], attention_mask=X_tr["attention_mask"][idx], labels=y_tr[idx]).loss
opt.zero_grad(); loss.backward(); opt.step(); sched.step()
first_losses.append(loss.item())
val_loss, _ = evaluate(model, X_va, y_va)
if val_loss < best:
best, best_state, best_epoch, wait = val_loss, copy.deepcopy(model.state_dict()), epoch, 0
else:
wait += 1
if wait >= patience:
break
model.load_state_dict(best_state) # restore the best epoch
return model, best_epoch, epoch, best, max(first_losses[:10])
print("peak lr | best epoch | stopped | val loss | val acc")
results = {}
for lr in [1e-5, 1e-4, 1e-3, 1e-2]:
model, best_epoch, stopped, val_loss, _ = fine_tune(lr)
results[lr] = (val_loss, model)
print(f"{lr:7.0e} | {best_epoch:10d} | {stopped:7d} | {val_loss:8.3f} | {evaluate(model, X_va, y_va)[1]:.3f}")
chosen = min(results, key=lambda k: results[k][0])
print(f"chosen by validation loss: {chosen:.0e} -> test accuracy {evaluate(results[chosen][1], X_te, y_te)[1]:.3f} (500 sentences)")peak lr | best epoch | stopped | val loss | val acc
1e-05 | 4 | 4 | 0.686 | 0.583
1e-04 | 4 | 4 | 0.637 | 0.677
1e-03 | 2 | 4 | 0.573 | 0.720
1e-02 | 4 | 4 | 0.693 | 0.510
chosen by validation loss: 1e-03 -> test accuracy 0.704 (500 sentences)
The sweep has the same shape as the NumPy one. barely moves the model in 128 steps (validation loss 0.686, close to , the loss of a coin flip). breaks it: the validation loss is 0.693 and the accuracy 0.510, a model that predicts one class for almost everything. In between, is chosen (validation loss 0.573, best at epoch 2, so early stopping stops at epoch 4 and restores epoch 2), and its test accuracy is 0.704 on 500 sentences.
The winner is higher than the "" default for full fine-tuning. That default is for BERT-base and larger models trained for thousands of steps; a 2-layer model trained for 128 steps needs larger steps. This is why the recipe says to sweep the rate rather than trust one number.
Does the warm-up matter? The same run at with and without it, printing the largest training loss of the first 10 steps and the final scores:
import copy
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, get_linear_schedule_with_warmup
from transformers.utils import logging
logging.set_verbosity_error()
name = "google/bert_uncased_L-2_H-128_A-2"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(1000))
val = ds["validation"].shuffle(seed=0).select(range(300))
test = ds["test"].shuffle(seed=0).select(range(500))
tok = AutoTokenizer.from_pretrained(name)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_tr, X_va, X_te = enc(train), enc(val), enc(test)
y_tr, y_va, y_te = (torch.tensor(d["label"]) for d in (train, val, test))
def evaluate(model, X, y):
model.eval()
with torch.no_grad():
out = model(input_ids=X["input_ids"], attention_mask=X["attention_mask"], labels=y)
return out.loss.item(), (out.logits.argmax(1) == y).float().mean().item()
def fine_tune(lr, warmup_frac, epochs=4, patience=2):
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
steps = epochs * -(-len(y_tr) // 32)
sched = get_linear_schedule_with_warmup(opt, int(warmup_frac * steps), steps)
g = torch.Generator().manual_seed(0)
best, best_state, wait, first_losses = float("inf"), None, 0, []
for epoch in range(1, epochs + 1):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(32):
loss = model(input_ids=X_tr["input_ids"][idx], attention_mask=X_tr["attention_mask"][idx], labels=y_tr[idx]).loss
opt.zero_grad(); loss.backward(); opt.step(); sched.step()
first_losses.append(loss.item())
val_loss, _ = evaluate(model, X_va, y_va)
if val_loss < best:
best, best_state, wait = val_loss, copy.deepcopy(model.state_dict()), 0
else:
wait += 1
if wait >= patience:
break
model.load_state_dict(best_state)
return model, best, max(first_losses[:10])
for warmup in [0.1, 0.0]:
model, val_loss, early = fine_tune(1e-3, warmup)
print(f"warm-up {warmup:.0%}: largest loss in the first 10 steps {early:.3f} | best val loss {val_loss:.3f}"
f" | test accuracy {evaluate(model, X_te, y_te)[1]:.3f}")warm-up 10%: largest loss in the first 10 steps 0.726 | best val loss 0.573 | test accuracy 0.704
warm-up 0%: largest loss in the first 10 steps 0.714 | best val loss 0.608 | test accuracy 0.688
For this small model the warm-up hardly changes the first steps (largest early loss 0.726 with it, 0.714 without) and helps the end result a little (validation loss 0.573 against 0.608, test accuracy 0.704 against 0.688, a difference of 8 test sentences, within the noise of one seed). Warm-up matters most for large models, large batches and large learning rates, where the first unguarded steps can send the loss to a spike it never recovers from. It costs almost nothing, so the default is to keep it.
The recipe, in order
- Hold out a validation set before anything else (from your training data if the data set has no validation split). Never tune on the test set.
- Start from the defaults: AdamW, weight decay 0.01, peak rate (transformers, full fine-tuning) or (head only, LoRA), 5 to 10 % linear warm-up, linear or cosine decay, 3 to 5 epochs, batch size 16 to 64.
- Sweep the peak learning rate over a factor-of-3 or factor-of-10 grid around the default, with everything else fixed. It is the hyperparameter that matters most.
- Early-stop on the validation loss (or the validation metric you care about), keep the best checkpoint.
- Check more than one seed for the final candidates: fine-tuning results on small data vary by a point or more between seeds.
- Evaluate the chosen model once on the test set.
Pitfalls
- The from-scratch learning rate. with Adam is a fine default from scratch and can wreck a large pretrained transformer; broke even this small one.
- Warm-up counted in epochs on a tiny data set. "10 % warm-up" means 10 % of the steps. With 30 steps per epoch and a warm-up of "1 epoch" in a 3-epoch run, a third of training is warm-up.
- Scheduler stepped per epoch when it was built for steps.
get_linear_schedule_with_warmupexpectssched.step()after every optimiser step; stepping it once per epoch leaves the rate in warm-up for the whole run. - Early stopping on the training loss. It always goes down; only a held-out set says when the model starts to overfit.
- Not restoring the best checkpoint. Stopping after
patiencebad epochs leaves the modelpatienceepochs past its best. Keep a copy of the best state (or save checkpoints) and restore it. - Reading one run as the truth. With 300 validation and 500 test sentences, a difference of 0.01 is 3 to 5 sentences. Compare learning rates that differ by a factor of 10, not by 20 %.
Practice
- A run has 2,000 training examples, batch size 32, 4 epochs, 6 % warm-up. How many warm-up steps is that?
- In the BERT sweep, why compare learning rates by the validation loss and not by the test accuracy, even though the test accuracy is what you report?
- Your fine-tuned model's validation loss keeps falling for all 4 epochs. What would you try?
Answers
- steps per epoch, 252 in total; 6 % of 252 is about 15 steps.
- Choosing on the test set makes its score optimistic: the test set would have been used to make a decision. The validation set exists to take that role.
- More epochs (it has not started to overfit), a slightly larger learning rate, or both; keep early stopping on so that the extra epochs cost nothing if they do not help.
Test yourself
Which peak learning rate is a sensible first try for full fine-tuning of a BERT-size transformer with AdamW?
- 1e-1
- 1e-2
- 2e-5
- 1e-8
What does the warm-up protect against at the start of fine-tuning?
- Overfitting at the end of training
- Large, noisy first updates from a random head and from Adam's unreliable early second-moment estimates
- Running out of memory
- A validation set that is too small
Early stopping with patience 2 stops after epoch 5. Which weights should the final model have?
- Those after epoch 5
- Those of the epoch with the best validation loss, here epoch 3
- The pretrained weights
- An average of all epochs