Sub topic 10
Learning rates and schedules for fine-tuning
This chapter assumes you have built the earlier pieces of this tutorial: a frozen ResNet-18 with a new fc head, a run_epoch function, and train_loader and val_loader. You should also know what a learning rate does in gradient descent and how requires_grad controls which parameters train.
Why fine-tuning is sensitive to learning rate
The pretrained backbone already encodes useful features. The new head starts from random weights. These two parts need different treatment:
- The head knows nothing yet, so it can take large steps. A learning rate of
1e-3with AdamW is a reasonable default. - The backbone is already good. Large steps overwrite its features before they can be adapted. This is sometimes called catastrophic forgetting. Learning rates of
1e-4to1e-5are typical for the later layers.
A single global learning rate forces a compromise. It is either too timid for the head or too violent for the backbone. Two tools solve this: parameter groups give each part its own rate, and a schedule changes the rate over time.
Parameter groups: one optimizer, several rates
An optimizer accepts a list of dictionaries. Each dictionary is a parameter group with its own lr. You used this in the two-stage example. The idea extends naturally to a ladder of rates, where deeper (earlier) layers get smaller values. This is called discriminative learning rates.
import torch
# Stage 2: unfreeze the last two residual stages.
for block in (model.layer3, model.layer4):
for param in block.parameters():
param.requires_grad = True
optimizer = torch.optim.AdamW(
[
{"params": model.layer3.parameters(), "lr": 1e-5},
{"params": model.layer4.parameters(), "lr": 1e-4},
{"params": model.fc.parameters(), "lr": 1e-3},
],
weight_decay=1e-2,
)Each step of the ladder is about ten times the previous one. This is a starting point, not a law. Early layers detect edges and textures that transfer to almost any photo. Later layers detect object parts that are more specific to ImageNet. That is why later layers are the ones worth adapting.
Schedules: changing the rate over time
A constant learning rate works, but a schedule usually gives a better final result. High rates early make fast progress. Low rates late let the weights settle into a good minimum. PyTorch schedulers live in torch.optim.lr_scheduler. They multiply each group's rate by a factor, so the ratios between groups are preserved.
| Scheduler | Behavior | Typical use |
|---|---|---|
| `StepLR` | Multiplies the rate by `gamma` every `step_size` epochs | Simple baselines |
| `CosineAnnealingLR` | Decays smoothly along a cosine curve toward a minimum | A solid default for fine-tuning |
| `LinearLR` | Scales the rate linearly between two factors | Warmup |
| `OneCycleLR` | Ramps up, then anneals down within one run | Short runs, stepped per batch |
| `ReduceLROnPlateau` | Cuts the rate when a metric stops improving | When you do not know how long to train |
Warmup followed by cosine decay
Warmup starts with a small rate and ramps up. It protects the pretrained weights while the new head is still producing noisy gradients. The following snippet runs as written. It prints the learning rate at each epoch so you can see the curve.
import torch
from torch import nn
from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR
net = nn.Linear(4, 2)
opt = torch.optim.AdamW(net.parameters(), lr=1e-3)
warmup = LinearLR(opt, start_factor=0.1, total_iters=2)
cosine = CosineAnnealingLR(opt, T_max=8)
sched = SequentialLR(opt, schedulers=[warmup, cosine], milestones=[2])
for epoch in range(10):
print(epoch, f"{opt.param_groups[0]['lr']:.6f}")
opt.step() # a real loop would compute a loss and call backward first
sched.step()The rate rises from 0.0001 to 0.001 over two epochs, then decays along the cosine curve for the remaining eight. T_max is the number of steps the cosine phase lasts, so it must match the number of scheduler steps remaining after warmup.
Per-epoch or per-batch stepping
Call scheduler.step() at the granularity the scheduler was built for:
StepLR,CosineAnnealingLR, andReduceLROnPlateauare normally stepped once per epoch.OneCycleLRis built withsteps_per_epochand must be stepped after every batch.
Always call optimizer.step() before scheduler.step(). The reverse order skips the first value of the schedule, and PyTorch warns you about it.
The next version of run_epoch accepts an optional scheduler and steps it per batch. Combined with OneCycleLR, it gives each parameter group its own peak rate.
def run_epoch(model, loader, criterion, device, optimizer=None, scheduler=None):
training = optimizer is not None
model.train(training)
total_loss, correct, count = 0.0, 0, 0
with torch.set_grad_enabled(training):
for images, labels in loader:
images, labels = images.to(device), labels.to(device)
logits = model(images)
loss = criterion(logits, labels)
if training:
optimizer.zero_grad()
loss.backward()
optimizer.step()
if scheduler is not None:
scheduler.step()
total_loss += loss.item() * images.size(0)
correct += (logits.argmax(dim=1) == labels).sum().item()
count += images.size(0)
return total_loss / count, correct / count
epochs = 10
scheduler = torch.optim.lr_scheduler.OneCycleLR(
optimizer,
max_lr=[1e-5, 1e-4, 1e-3], # one peak per group, same order as the optimizer
steps_per_epoch=len(train_loader),
epochs=epochs,
pct_start=0.3, # 30% of steps ramping up, 70% annealing down
)
for epoch in range(epochs):
train_loss, train_acc = run_epoch(
model, train_loader, criterion, device, optimizer, scheduler
)
val_loss, val_acc = run_epoch(model, val_loader, criterion, device)
print(f"epoch {epoch + 1}: val acc {val_acc:.3f}, val loss {val_loss:.3f}")The scheduler is created once and is tied to the optimizer. If you rebuild the optimizer for a new stage, rebuild the scheduler too.
Frozen layers and BatchNorm
ResNet has BatchNorm layers. In train mode they update running mean and variance statistics, even when their weights have requires_grad=False. A "frozen" backbone therefore still drifts toward your small dataset's statistics. With small batches, those statistics are noisy and can hurt accuracy.
One common fix is to keep frozen BatchNorm layers in eval mode. Call this helper right after model.train(training), because model.train() resets every submodule.
import torch.nn as nn
def freeze_bn_stats(model):
for module in model.modules():
if isinstance(module, nn.BatchNorm2d):
if not any(p.requires_grad for p in module.parameters()):
module.eval()Whether this helps depends on your data. If your images look very different from ImageNet, letting the statistics adapt can help. If your dataset is small, freezing them is usually safer. Try both and compare validation accuracy.
Choosing values without guessing
You do not have to pick rates blindly. Three practical approaches, in order of effort:
- Start from defaults.
1e-3for the head and1e-4for the last stage works for many small datasets. - Run a short range test. Train for a few hundred batches while raising the rate exponentially from
1e-6to1. Plot loss against rate. Choose a value about one order of magnitude below the point where the loss starts to climb. - Sweep a few values. Train for a few epochs at
3e-5,1e-4, and3e-4for the backbone group. Compare validation loss, not training loss.
Change one thing at a time. If you change the rate, the schedule, and the unfreezing depth together, you cannot tell which change helped.
Reading the symptoms
The training curves tell you which direction to adjust. Always judge by validation metrics, since training loss alone can keep falling while the model memorizes.
| Symptom | Likely cause | Remedy |
|---|---|---|
| Loss becomes `nan` or jumps to large values | Rate too high | Lower the rate by 3 to 10 times, add warmup |
| Loss barely moves for several epochs | Rate too low, or parameters missing from the optimizer | Raise the rate, check that the optimizer holds the trainable parameters |
| Validation accuracy drops right after unfreezing | Backbone rate too high | Lower the backbone rate, or unfreeze fewer layers |
| Training accuracy keeps rising, validation stalls or falls | Overfitting | Lower the backbone rate, add augmentation, stop earlier (covered in the next chapters) |
| Validation accuracy is noisy from epoch to epoch | Small validation set or noisy BatchNorm statistics | Use a larger validation set, freeze BatchNorm statistics |
Edge cases to remember
- Weight decay applies per group. In the optimizer above,
weight_decay=1e-2applies to every group. You can set it differently per group by adding a"weight_decay"key to a dictionary. - Schedulers and checkpoints. To resume training, save
scheduler.state_dict()along with the optimizer state. Otherwise the schedule restarts from its beginning. ReduceLROnPlateauneeds a metric. Callscheduler.step(val_loss), notscheduler.step().- Batch size interacts with rate. If you double the batch size, a slightly higher rate is usually acceptable. If memory forces a much smaller batch, lower the rate.
- Epoch counts must agree.
OneCycleLRraises an error if you step it more times thansteps_per_epoch * epochs. Building it with a different number of epochs than you actually train for is a common cause.
Exercise
You freeze the backbone, train the head for 5 epochs, then set requires_grad = True on model.layer4. You keep the original optimizer, which was built with model.fc.parameters() only, and train 5 more epochs at the same rate. Validation accuracy barely changes from the end of stage 1. What is wrong, and how would you fix it with sensible learning rates?
Show answer
The optimizer was created before layer4 was unfrozen and holds only the head's parameters. layer4 gets gradients but is never updated. Create a new AdamW optimizer with two parameter groups, for example layer4 at 1e-4 and fc at 1e-3. If you use a scheduler, rebuild it for the new optimizer as well.
Exercise
You use OneCycleLR with steps_per_epoch=len(train_loader) and epochs=10, but you call scheduler.step() once per epoch inside the epoch loop instead of once per batch. What happens to the learning rate over training?
Show answer
The scheduler advances only 10 steps out of its planned total of 10 * len(train_loader). The rate stays in the early warmup part of the cycle and never reaches its peak or anneals. The model trains at a tiny rate and underfits. The fix is to call scheduler.step() after every optimizer.step(), as in the run_epoch above.