Week 10 · Transfer learning and fine-tuning
Compare a frozen encoder with partial and full adaptation.
← Week 9 · Subject contents · Week 11 →
Compare a frozen encoder with partial and full adaptation.
Work through the problem
Transfer learning starts with weights learned on one task. Freezing an encoder restricts the new fit to the head. Partial and full fine-tuning expand the trainable set but can fit noise in small datasets. Use the same pretraining checkpoint, target training rows, and validation rows for all options.
If the encoder produces h and a linear head predicts Wh+b, freezing means only W and b change. When target labels depend on a feature the encoder suppressed, a frozen head may have little to work with. The toy target below changes which input coordinate is predictive.
Run the Python lab
from copy import deepcopy
import torch
from torch import nn
torch.set_num_threads(1)
torch.manual_seed(15)
x = torch.randn(256,2)
encoder = nn.Sequential(nn.Linear(2,8),nn.Tanh(),nn.Linear(8,4),nn.Tanh())
def train(model, rows, labels, steps):
opt = torch.optim.Adam((p for p in model.parameters() if p.requires_grad),lr=.025)
for _ in range(steps):
opt.zero_grad()
nn.functional.binary_cross_entropy_with_logits(model(rows)[:,0],labels.float()).backward()
opt.step()
source = nn.Sequential(encoder,nn.Linear(4,1))
train(source,x,x[:,0]>0,100)
target = x[:,1]>.25
for mode in ["frozen","partial","full"]:
torch.manual_seed(8)
enc = deepcopy(encoder)
for name, layer in enumerate(enc):
layer.requires_grad_(mode=="full" or (mode=="partial" and name>=2))
model = nn.Sequential(enc,nn.Linear(4,1))
train(model,x[:32],target[:32],90)
print(mode,round(((model(x[32:])[:,0]>0)==target[32:]).float().mean().item(),3))
Output from the lab
frozen 0.509
partial 0.629
full 0.987
Practice
- Why report performance on more examples than were used for adaptation?
Check your reasoning
- The small adaptation set tests sample efficiency. A separate larger set makes the comparison less noisy.
← Week 9 · Subject contents · Week 11 →
Further reading · Goodfellow, Bengio, and Courville · Deep Learning