Sub topic 7
Freezing the backbone and unfreezing later layers
This chapter assumes you can write a PyTorch training loop and know what requires_grad means. It also assumes you have a ResNet-18 with a new fc head and a run_epoch function like the ones in the earlier chapters. Here you decide which parameters get trained, and when.
Why freeze at all
A pretrained backbone holds features learned from about a million ImageNet images. Early layers detect edges and color blobs. Middle layers detect textures and parts. Late layers combine these into object-level patterns. Your new head, in contrast, starts with random weights.
If you train everything at once, the random head produces large, meaningless gradients in the first steps. Those gradients flow back into the backbone and can damage the good features before the head has learned anything. Freezing the backbone avoids this. It also has practical benefits:
- Fewer parameters get gradients and optimizer state, so each step uses less memory and time.
- A small dataset has fewer parameters to overfit.
- Training is more stable, so the first results arrive quickly.
The standard recipe has two stages. First, train only the head with the backbone frozen. Then unfreeze the last backbone stage or two and continue with a smaller learning rate.
How freezing works in PyTorch
Freezing means setting requires_grad = False on a parameter. Autograd then does not compute a gradient for it, and the optimizer has nothing to update. The parameter keeps its value.
Order matters here. A freshly constructed layer such as nn.Linear has requires_grad=True by default. So you freeze first, then replace the head. The new head is created after the loop and stays trainable.
import torch.nn as nn
from torchvision import models
def count_params(model):
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
return trainable, total
num_classes = 5 # replace with len(train_ds.classes)
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for param in model.parameters():
param.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, num_classes)
trainable, total = count_params(model)
print(f"trainable: {trainable:,} of {total:,}")With five classes this prints trainable: 2,565 of 11,179,077. The head is 512 × 5 weights plus 5 biases. Printing this count is the quickest check that you froze what you meant to freeze. If the trainable count equals the total, the freeze did nothing. If it is zero, you froze the head too, and the optimizer will raise an error about an empty parameter list.
Look at the structure before choosing what to unfreeze
Unfreezing is done by module name, so you need to know the names. Print the top-level children:
for name, child in model.named_children():
trainable = sum(p.numel() for p in child.parameters() if p.requires_grad)
total = sum(p.numel() for p in child.parameters())
print(f"{name:8s} {trainable:>10,} / {total:>10,}")ResNet-18 has conv1, bn1, relu, maxpool, layer1 to layer4, avgpool and fc. The layer4 stage holds 8,393,728 parameters, about 75% of the whole model, even though it is only one stage. That is why unfreezing just layer4 is already a major change. Other architectures use different names, such as features in VGG or blocks in some ViT implementations. Always print them first.
The BatchNorm trap
Setting requires_grad=False does not make a layer fully frozen. BatchNorm layers keep running estimates of the mean and variance as buffers, not parameters. In train mode, every forward pass updates those buffers from the current batch, whether or not the layer's weights are frozen.
Your run_epoch calls model.train(True), which switches every BatchNorm layer to train mode. During stage 1, the "frozen" backbone therefore drifts away from its ImageNet statistics. With small batches or a small dataset, those statistics are noisy. The result is a backbone that no longer matches its weights, and accuracy that is lower than it should be.
The fix is to put frozen BatchNorm layers back in eval mode after each call to model.train():
import torch.nn as nn
def set_train_mode(model, training=True):
"""Train mode for the model, but keep fully frozen BatchNorm layers in eval mode."""
model.train(training)
if training:
for module in model.modules():
if isinstance(module, nn.BatchNorm2d):
if not any(p.requires_grad for p in module.parameters()):
module.eval()In run_epoch, replace model.train(training) with set_train_mode(model, training). Once you unfreeze layer4, its BatchNorm layers have trainable parameters, so they return to train mode and adapt to your data. Layers 1 to 3 stay in eval mode.
Stage 1: train the head only
Give the optimizer only the parameters that need gradients. Passing model.fc.parameters(), as in the earlier chapter, works. A more general form filters by requires_grad, so it stays correct if you change what is frozen:
import torch
head_params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.AdamW(head_params, lr=1e-3)Train for a few epochs until validation accuracy stops improving. Because the backbone is fixed, you can use a fairly high learning rate such as 1e-3. Five epochs is typical for a small dataset. Stage 1 often gets you most of the final accuracy.
A side effect of freezing: with the backbone frozen and no augmentation, the backbone outputs for a given image never change. You could cache them and train the head on cached features in seconds. Random augmentation breaks that shortcut, since each epoch sees different crops, so this chapter does not use it.
Stage 2: unfreeze later layers
Once the head has converged, unfreeze the last stage:
for param in model.layer4.parameters():
param.requires_grad = True
print(count_params(model)) # (8396293, 11179077)The trainable count is now 8,396,293: the 8,393,728 from layer4 plus the 2,565 from the head.
You must build a new optimizer. The old one holds only the head parameters, so it would silently ignore layer4. Use parameter groups so that each part has its own learning rate:
optimizer = torch.optim.AdamW(
[
{"params": model.layer4.parameters(), "lr": 1e-4},
{"params": model.fc.parameters(), "lr": 1e-3},
],
weight_decay=1e-2,
)Creating a new optimizer discards the old AdamW moment estimates for the head. That is acceptable. The estimates rebuild within a few dozen steps.
Why a lower learning rate for the backbone
The head's weights are random-to-roughly-fitted, and the backbone's weights are already good. A step that is appropriate for the head can be far too large for pretrained weights. Using 10 times smaller for layer4 is a common starting point. If validation accuracy drops right after unfreezing, the backbone rate is too high, so try 3e-5 or 1e-5.
How deep to unfreeze
Earlier layers hold generic features that transfer to almost any image task. Later layers hold more task-specific features. How far down to go depends on how different your images are from ImageNet and how much data you have.
| Situation | Suggested approach |
|---|---|
| Few images (hundreds), natural photos | Head only, or head plus `layer4` |
| Moderate data (thousands), natural photos | Head, then `layer4`, possibly `layer3` |
| Large data, or images unlike ImageNet (medical, satellite, microscopy) | Unfreeze more or all layers, with a low backbone rate |
Move one stage at a time and compare validation accuracy. More unfrozen layers is not always better. On small datasets, unfreezing too much typically raises training accuracy while validation accuracy stays flat or falls.
Common errors
- Optimizer not rebuilt after unfreezing. The newly unfrozen parameters get gradients but are never updated. Training looks identical to stage 1.
- Freezing after replacing the head. If you loop over
model.parameters()after assigningmodel.fc, the head is frozen too and nothing learns. - Frozen BatchNorm in train mode. Described above. The symptom is validation accuracy that is lower than expected, or that fluctuates between epochs.
- Same learning rate for all groups. A rate suited to the head can wreck the backbone. Always use separate groups.
- Setting
requires_gradinside the loop. Changing it between steps is legal, but it makes experiments hard to reproduce. Change it at stage boundaries only. - Passing frozen parameters to the optimizer. This is harmless for AdamW because parameters without gradients are skipped. With weight decay, though, check your optimizer version's behavior, because some implementations decay parameters whose gradient is
Nonedifferently. Filtering byrequires_gradavoids the question.
Gradual unfreezing as an extension
A stronger variant of the two-stage recipe unfreezes one stage per phase, from the top down: fc, then layer4, then layer3. Each phase uses a lower rate for deeper layers, for example 1e-3, 1e-4, 1e-5. This is sometimes called discriminative learning rates. It costs more experiments, so try it only if the two-stage result is not good enough and you have enough data to support it.
Exercise
You freeze all parameters of a ResNet-18, replace model.fc, train for five epochs, then run for p in model.layer4.parameters(): p.requires_grad = True and train five more epochs with the same optimizer object. Validation accuracy does not change from stage 1. What is wrong, and what should you do? Also name one reason the BatchNorm layers in layer1 to layer3 can still change during stage 1 if you use model.train().
Show answer
The optimizer was created when only the head required gradients, so it contains only the head parameters and never updates layer4. Create a new optimizer after unfreezing, ideally with separate parameter groups such as 1e-4 for layer4 and 1e-3 for fc. BatchNorm layers keep running mean and variance buffers that are updated in every forward pass while the module is in train mode, regardless of requires_grad. To prevent that, put frozen BatchNorm modules in eval mode after calling model.train().