Chapter 19: Transfer Learning and Fine-Tuning — Implementation
What a pretrained network sees: ImageNet predictions on CIFAR-10 photos
Any classifier on top of pretrained features
Discriminative learning rates with parameter groups
LoRA for a linear layer, and merging it back
Saving only what was trained
Inside a Vision Transformer
import copy
import math
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import matplotlib.pyplot as plt
from torchvision.models import resnet18, ResNet18_Weights, vit_b_16
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
torch.set_num_threads(4)
root = Path.home() / '.cache' / 'ai-book-data'
train_set = torchvision.datasets.CIFAR10(root, train=True, download=True)
test_set = torchvision.datasets.CIFAR10(root, train=False, download=True)
rng = np.random.default_rng(1)
def subset(ds, n):
idx = np.concatenate([rng.choice(np.where(np.array(ds.targets) == c)[0], n // 10, replace=False) for c in range(10)])
return torch.tensor(ds.data[idx]).permute(0, 3, 1, 2).float() / 255, torch.tensor(np.array(ds.targets)[idx])
Xtr, ytr = subset(train_set, 1000)
Xte, yte = subset(test_set, 500)
classes = train_set.classes
weights = ResNet18_Weights.IMAGENET1K_V1
resnet = resnet18(weights=weights, progress=False).eval()
print(f'{len(Xtr)} training and {len(Xte)} test images; ResNet-18 loaded')1000 training and 500 test images; ResNet-18 loaded
1. What a Pretrained Network Sees¶
Every set of torchvision weights carries its own preprocessing, weights.transforms(): resize, crop, convert to floats, normalise with the source data’s statistics. Using anything else silently degrades the features.
preprocess = weights.transforms()
print(preprocess)ImageClassification(
crop_size=[224]
resize_size=[256]
mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]
interpolation=InterpolationMode.BILINEAR
)
The network still has its ImageNet head: 1 000 classes. What does it say about CIFAR-10 photos it was never trained on?
imagenet = weights.meta['categories']
fig, axes = plt.subplots(1, 6, figsize=(14, 3.0))
with torch.no_grad():
for ax, i in zip(axes, [0, 75, 125, 225, 325, 475]):
p = resnet(preprocess(Xte[i]).unsqueeze(0)).softmax(1)[0]
top = p.topk(3)
ax.imshow(Xte[i].permute(1, 2, 0)); ax.axis('off')
ax.set_title(f'{classes[yte[i]]}\n' + '\n'.join(f'{imagenet[k][:16]} {v:.2f}' for v, k in zip(top.values, top.indices)), fontsize=8)
plt.tight_layout(); plt.show()
On 32×32 thumbnails enlarged to 224, the ImageNet head is mostly wrong: the plane becomes a langur (a monkey), the car a cassette player; only the truck gets a sensible “moving van”. Its 1 000 classes, and these blurry images, are far from what it was trained for. Yet the 512 features just before those classes are what we reuse, and the next section shows how well they still separate CIFAR’s classes.
2. Any Classifier on Pretrained Features¶
Once features are extracted, the network is out of the picture: any classifier from Part II can sit on top.
extractor = copy.deepcopy(resnet); extractor.fc = nn.Identity()
def features(X, batch=100):
with torch.no_grad():
return torch.cat([extractor(preprocess(X[i:i + batch])) for i in range(0, len(X), batch)]).numpy()
t0 = time.time(); F_tr, F_te = features(Xtr), features(Xte)
print(f'features {F_tr.shape} in {time.time() - t0:.0f} s')
for name, clf in [('logistic regression', LogisticRegression(max_iter=3000, C=0.5)), ('5 nearest neighbours', KNeighborsClassifier(5))]:
print(f'{name:<22} test accuracy {clf.fit(F_tr, ytr.numpy()).score(F_te, yte.numpy()):.3f}')features (1000, 512) in 87 s
logistic regression test accuracy 0.782
5 nearest neighbours test accuracy 0.668
A logistic regression on the features reaches 0.782 with 100 images per class. Even a nearest-neighbour classifier, which has no notion of what matters in an image, gets 0.668: in the feature space, images of the same class tend to be close to each other.
3. Discriminative Learning Rates¶
torch.optim takes a list of parameter groups, each with its own options. Fine-tuning usually gives the pretrained layers a small rate and the new head a larger one, and unfreezes the layers from the top down. Here, the last stage (layer4) at 10-4 and the new head at 10-3, with warm-up and cosine decay (Chapter 16), trained on 64×64 inputs to keep it fast:
mean, std = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1), torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
small = lambda x: (F.interpolate(x, size=64, mode='bilinear', align_corners=False) - mean) / std
model = copy.deepcopy(resnet); model.fc = nn.Linear(512, 10)
for name, p in model.named_parameters():
p.requires_grad = name.startswith(('layer4', 'fc'))
groups = [{'params': model.layer4.parameters(), 'lr': 1e-4}, {'params': model.fc.parameters(), 'lr': 1e-3}]
opt = torch.optim.AdamW(groups, weight_decay=0.01)
epochs, per = 4, math.ceil(len(Xtr) / 64)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda t: min(1, (t + 1) / per) * 0.5 * (1 + math.cos(math.pi * t / (epochs * per))))
print('rates at the start:', [g['lr'] for g in opt.param_groups])
g = torch.Generator().manual_seed(0); t0 = time.time()
for ep in range(epochs):
model.train()
for m in model.modules():
if isinstance(m, nn.BatchNorm2d) and not next(m.parameters()).requires_grad: m.eval()
for idx in torch.randperm(len(Xtr), generator=g).split(64):
xb = small(Xtr[idx]); xb = torch.where(torch.rand(len(idx), 1, 1, 1, generator=g) < .5, xb.flip(-1), xb)
opt.zero_grad(); F.cross_entropy(model(xb), ytr[idx]).backward(); opt.step(); sched.step()
model.eval()
with torch.no_grad(): acc = float((model(small(Xte)).argmax(1) == yte).float().mean())
print(f'epoch {ep + 1}: rates {[round(g["lr"], 6) for g in opt.param_groups]}, test accuracy {acc:.3f}')
print(f'{time.time() - t0:.0f} s')rates at the start: [6.25e-06, 6.25e-05]
epoch 1: rates [8.5e-05, 0.000854], test accuracy 0.440
epoch 2: rates [5e-05, 0.0005], test accuracy 0.576
epoch 3: rates [1.5e-05, 0.000146], test accuracy 0.610
epoch 4: rates [0.0, 0.0], test accuracy 0.608
53 s
4. LoRA for a Linear Layer¶
The theory chapter applied LoRA to convolutions. For Transformers it is applied to the linear layers of attention and of the feed-forward blocks. A minimal version, and the merge that removes its cost at inference:
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r=8, alpha=16):
super().__init__()
self.base = base
for p in base.parameters(): p.requires_grad = False
self.A = nn.Parameter(torch.randn(r, base.in_features) / math.sqrt(base.in_features))
self.B = nn.Parameter(torch.zeros(base.out_features, r))
self.scale = alpha / r
def forward(self, x):
return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale # never forms the full d_out x d_in update
def merged(self):
out = copy.deepcopy(self.base)
with torch.no_grad(): out.weight += self.scale * self.B @ self.A
return out
torch.manual_seed(0)
base = nn.Linear(768, 768)
lora = LoRALinear(base, r=8)
x = torch.randn(4, 768)
print('at the start, LoRA changes nothing:', torch.allclose(lora(x), base(x)))
with torch.no_grad(): lora.B.normal_(0, 0.02) # pretend it has been trained
print('merged layer gives the same outputs:', torch.allclose(lora(x), lora.merged()(x), atol=1e-5))
full, small_n = sum(p.numel() for p in base.parameters()), sum(p.numel() for p in [lora.A, lora.B])
print(f'trainable: {small_n:,} of {full:,} ({100 * small_n / full:.1f}%)')at the start, LoRA changes nothing: True
merged layer gives the same outputs: True
trainable: 12,288 of 590,592 (2.1%)
In practice, the peft library wraps any Hugging Face model in a few lines (LoraConfig(r=8, target_modules=[...])), but the mechanism is exactly this.
5. Saving Only What Was Trained¶
A fine-tuned copy of a large model per task is expensive to store. With frozen layers, only the trainable parameters need saving, on top of the shared base model. Fine-tuning a whole stage still saves most of the network (ResNet’s layer4 holds three quarters of its weights); a LoRA adapter is tiny.
import io
def size_mb(state):
buf = io.BytesIO(); torch.save(state, buf); return buf.tell() / 1e6
trainable_state = {k: v for k, v in model.state_dict().items() if k.startswith(('layer4', 'fc'))}
print(f'whole fine-tuned model: {size_mb(model.state_dict()):.1f} MB; layer4 + head only: {size_mb(trainable_state):.1f} MB')
print(f'a LoRA adapter for the 768 x 768 layer: {size_mb({"A": lora.A, "B": lora.B}) * 1000:.0f} kB')whole fine-tuned model: 44.8 MB; layer4 + head only: 33.6 MB
a LoRA adapter for the 768 x 768 layer: 51 kB
6. Inside a Vision Transformer¶
torchvision’s ViT-B/16 (built here without downloading its weights) shows the pieces of Section 19.9 at full size:
vit = vit_b_16(weights=None).eval()
print('patch embedding:', vit.conv_proj)
x = torch.zeros(1, 3, 224, 224)
tokens = vit.conv_proj(x).flatten(2).transpose(1, 2)
print('tokens from one image:', tuple(tokens.shape), '(196 patches of 16x16, each a 768-dimensional vector)')
print('class token:', tuple(vit.class_token.shape), ' position embedding:', tuple(vit.encoder.pos_embedding.shape))
print('encoder layers:', len(vit.encoder.layers), ' heads per layer:', vit.encoder.layers[0].self_attention.num_heads)
print(f'parameters: {sum(p.numel() for p in vit.parameters()):,} (ResNet-18: {sum(p.numel() for p in resnet.parameters()):,})')
print('attention scores per head and layer:', 197 * 197)patch embedding: Conv2d(3, 768, kernel_size=(16, 16), stride=(16, 16))
tokens from one image: (1, 196, 768) (196 patches of 16x16, each a 768-dimensional vector)
class token: (1, 1, 768) position embedding: (1, 197, 768)
encoder layers: 12 heads per layer: 12
parameters: 86,567,656 (ResNet-18: 11,689,512)
attention scores per head and layer: 38809
Each of the 12 layers lets all 197 tokens attend to each other: 38 809 scores per head, per layer. The cost grows with the square of the number of patches, which is why ViTs use large patches, and why their pretrained versions (on ImageNet-21k or larger) are what practitioners fine-tune.
Summary¶
weights.transforms()is the preprocessing a pretrained model expects.Pretrained features make even simple classifiers strong.
Parameter groups give each part of the network its own learning rate.
LoRA adds a trainable low-rank path to a frozen layer and can be merged into it afterwards.
Saving only the trained parameters makes one adapter per task cheap.
A ViT is a patch embedding, a class token, position embeddings and a Transformer encoder.