Sub topic 8
Choosing a loss and an optimizer
This chapter assumes you can write a PyTorch training loop, know what a gradient step does, and have already replaced and frozen parts of a pretrained ResNet-18 as in the previous chapters. Here you will pick the loss function and optimizer for fine-tuning and learn the mistakes that quietly hurt results.
What the loss and the optimizer each do
The loss turns the model's output and the true label into one number that is small when the prediction is good. The optimizer takes the gradients of that number and updates the weights. They are separate choices. The loss defines what "better" means, and the optimizer defines how the weights move toward it.
The loss: CrossEntropyLoss on raw logits
For single-label classification, where each image belongs to exactly one class, use nn.CrossEntropyLoss. It expects two inputs:
- Logits of shape
(batch, num_classes). These are the raw, unnormalized scores from the final linear layer. - Labels of shape
(batch,), containing integer class indices. They are not one-hot vectors.
Internally it applies log-softmax and then the negative log-likelihood of the correct class. So the model should not end with a softmax layer. If it does, softmax is applied twice. The model still trains, but the loss is squashed, gradients are weaker, and the numbers are harder to interpret.
The following script runs as shown. It checks the built-in loss against a manual computation and shows the double-softmax mistake.
import torch
import torch.nn as nn
logits = torch.tensor([[2.0, 0.5, -1.0], [0.1, 0.2, 3.0]])
labels = torch.tensor([0, 2])
criterion = nn.CrossEntropyLoss()
builtin = criterion(logits, labels)
# Manual version: negative log-probability of the true class, averaged.
log_probs = torch.log_softmax(logits, dim=1)
manual = -log_probs[torch.arange(len(labels)), labels].mean()
# Common mistake: softmax first, then CrossEntropyLoss.
double_softmax = criterion(logits.softmax(dim=1), labels)
print(f"built-in: {builtin.item():.4f}")
print(f"manual: {manual.item():.4f}")
print(f"wrong: {double_softmax.item():.4f}")The first two values match (about 0.175). The third is larger, and it cannot approach zero however confident the model becomes, because the inputs are already limited to the range 0 to 1.
Useful options
CrossEntropyLoss has two options that matter for fine-tuning.
label_smoothing=0.1replaces the hard target (100% on the true class) with a softer one (about 90% on the true class, the rest spread over the others). It discourages overconfident outputs and can reduce overfitting on small, slightly noisy datasets. The cost is that predicted probabilities become less sharp, which matters if you later threshold on confidence.weight=tensor_of_class_weightsmultiplies each sample's loss by the weight of its true class. It is one remedy for imbalanced classes, covered in a later chapter. Leave it unset for now.
If an image can have several labels at once (multi-label classification), the right loss is nn.BCEWithLogitsLoss with a multi-hot target, not CrossEntropyLoss. Everything else in this chapter still applies.
The optimizer: what to pass in
An optimizer only updates the parameters you give it. Three rules follow from that.
- Pass only the parameters you intend to train. In stage 1 (frozen backbone), that is
model.fc.parameters(). Passingmodel.parameters()also works, because frozen parameters have no gradient and are skipped. But a list that does not match your intent hides bugs. - Rebuild the optimizer after you change
requires_grad. Parameters you unfreeze later are not in an optimizer created earlier, so they would receive gradients and never move. Silent no-ops like this are the most common freezing bug. - Use parameter groups for different learning rates. Each group is a dict with its own
paramsand, optionally, its ownlr.
The next script builds both stages on a ResNet-18 and prints how many parameters each group holds. It uses weights=None, so nothing is downloaded. The mechanics are identical with pretrained weights.
import torch.nn as nn
from torch.optim import AdamW
from torchvision import models
def make_optimizer(model, head_lr=1e-3, backbone_lr=1e-4, weight_decay=1e-2):
head = list(model.fc.parameters())
head_ids = {id(p) for p in head}
backbone = [
p for p in model.parameters()
if p.requires_grad and id(p) not in head_ids
]
groups = [{"params": head, "lr": head_lr}]
if backbone:
groups.append({"params": backbone, "lr": backbone_lr})
return AdamW(groups, weight_decay=weight_decay)
def describe(optimizer):
for i, group in enumerate(optimizer.param_groups):
n = sum(p.numel() for p in group["params"])
print(f"group {i}: lr={group['lr']}, parameters={n:,}")
model = models.resnet18(weights=None)
for p in model.parameters():
p.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, 5) # new head, trainable
print("Stage 1: head only")
describe(make_optimizer(model))
for p in model.layer4.parameters():
p.requires_grad = True
print("Stage 2: head + layer4")
describe(make_optimizer(model))Stage 1 shows one group with 2,565 parameters (512 × 5 weights plus 5 biases). Stage 2 adds a second group with the roughly 8.4 million parameters of layer4, at a learning rate ten times lower. Backbone layers already hold useful features, so they should move in small steps. The new head starts random and needs larger ones.
Choosing between AdamW and SGD
Both work well for fine-tuning. The practical differences are below.
| Row | AdamW | SGD with momentum |
|---|---|---|
| Typical starting learning rate | 1e-3 for a new head, 1e-4 to 1e-5 for pretrained layers | 1e-2 to 1e-1 for a new head, 1e-3 to 1e-2 for pretrained layers |
| Sensitivity to learning rate | Forgiving. Adapts step size per parameter. | Less forgiving. Needs more tuning. |
| Extra memory | Two state tensors per parameter | One state tensor per parameter |
| Typical weight decay | 1e-2 | 1e-4 to 5e-4 |
| Good default when | The dataset is small and you want a fast start | You have time to tune and want the best final accuracy on larger data |
Start with AdamW. Its learning-rate scale is more predictable, so your first run is less likely to fail for tuning reasons. If you later want to squeeze out accuracy, try SGD:
import torch
optimizer = torch.optim.SGD(
model.fc.parameters(),
lr=1e-2,
momentum=0.9,
nesterov=True,
weight_decay=1e-4,
)Weight decay and what it does here
Weight decay shrinks weights slightly at each step. It is a mild regularizer, and it matters more when you unfreeze many pretrained parameters, since there are more weights that could overfit. Values around 1e-2 for AdamW and 1e-4 for SGD are reasonable starting points. Do not tune it before you have fixed the learning rate. It is a second-order effect.
Common errors
- Softmax before the loss. Covered above. Fix: return logits from the model and apply softmax only at inference time.
- One-hot labels.
CrossEntropyLossaccepts class-probability targets of shape(batch, num_classes)in recent PyTorch versions, but integer indices are whatImageFolderproduces. Do not convert them unless you want soft targets, such as from mixup. - Stale optimizer. Unfreezing layers without creating a new optimizer. Check
describe(optimizer)after any change. - Forgetting
zero_grad(). Gradients accumulate across steps by default. Calloptimizer.zero_grad()beforeloss.backward()on every step, as in the loop from the previous chapter. - Learning rate too high for pretrained layers. Training accuracy drops during stage 2 instead of rising. The large updates are overwriting pretrained features. Lower the backbone learning rate by a factor of 3 to 10.
- Frozen BatchNorm layers still changing. Setting
requires_grad = Falsestops the weights from training. But inmodel.train()mode, BatchNorm layers still update their running mean and variance from your small dataset. If your batch size is small (roughly under 16), consider putting the frozen backbone's BatchNorm layers in eval mode during stage 1.
A decision checklist
- Single label per image:
CrossEntropyLoss. Multiple labels per image:BCEWithLogitsLoss. - Add
label_smoothing=0.1only if you see overfitting or have noisy labels. - Start with
AdamW,lr=1e-3for the new head,weight_decay=1e-2. - When unfreezing, build a new optimizer with a backbone group at about one tenth of the head's learning rate.
- Print the parameter groups once to confirm what the optimizer will update.
Exercise
A colleague unfreezes model.layer4 after stage 1 by setting requires_grad = True on its parameters, then continues the same loop with the original optimizer, which was built from model.fc.parameters(). Validation accuracy does not change from stage 1. What went wrong, and how do you fix it?
Show answer
The optimizer was created before the unfreeze and only contains the head's parameters. The layer4 parameters receive gradients (and cost compute) but are never updated. Fix it by creating a new optimizer after changing requires_grad, with layer4 and the head as separate parameter groups, for example AdamW([{"params": model.layer4.parameters(), "lr": 1e-4}, {"params": model.fc.parameters(), "lr": 1e-3}], weight_decay=1e-2).
Exercise
Your model's last layer is nn.Sequential(nn.Linear(512, 5), nn.Softmax(dim=1)) and you train with CrossEntropyLoss. Training runs without errors, but the loss plateaus at a high value and the training curve looks sluggish. Why, and what do you change?
Show answer
CrossEntropyLoss already applies log-softmax, so the model's softmax is applied twice. The inputs to the loss are limited to the range 0 to 1, which caps how low the loss can go and weakens gradients. Remove the Softmax layer so the model outputs raw logits. Apply softmax only when you need probabilities at inference time.
Exercise
You compare two runs. Run A uses CrossEntropyLoss() and ends with validation loss 0.31 and accuracy 91.2%. Run B uses CrossEntropyLoss(label_smoothing=0.1) and ends with validation loss 0.62 and accuracy 91.8%. Which run is better, and why is the loss comparison misleading?
Show answer
Run B is slightly better on accuracy, which is the metric that measures what you care about. Label smoothing changes the targets, so even a perfect-confidence prediction cannot reach a loss near zero. The higher loss in run B comes from the changed loss definition, not from worse predictions. Compare accuracy and per-class results across the two runs, not raw loss values.