Skip to content
ml-recall

Topic notes

Transfer Learning

Reusing pretrained networks; feature extraction vs fine-tuning, choosing a strategy, freezing layers correctly, distribution shift, self-supervised pretraining, and style transfer.

5-min read AI-checked

Practise 43 questions Take a test

Key ideas

Target data Similar to source Very different
small linear classifier on top features linear classifier on earlier-layer features
large fine-tune the whole network fine-tune (or train), starting from pretrained weights

Formulas

ℓi,j=−log⁡exp⁡(sim(zi,zj)/τ)∑k≠iexp⁡(sim(zi,zk)/τ),sim(u,v)=u⊤v∥u∥ ∥v∥\ell_{i,j} = -\log\frac{\exp(\mathrm{sim}(\mathbf{z}_i, \mathbf{z}_j)/\tau)}{\sum_{k \ne i}\exp(\mathrm{sim}(\mathbf{z}_i, \mathbf{z}_k)/\tau)},\qquad \mathrm{sim}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u}^\top\mathbf{v}}{\lVert\mathbf{u}\rVert\,\lVert\mathbf{v}\rVert}

New head parameters: nfeatures⋅nclasses+nclassesn_{\text{features}} \cdot n_{\text{classes}} + n_{\text{classes}}. Label-shift weight: βi=p(yi)/q(yi)\beta_i = p(y_i)/q(y_i). Gram matrix of a c×h×wc \times h \times w map: c×cc \times c, independent of hh and ww. For unit vectors, ∥u−v∥=2−2cos⁡θ\lVert\mathbf{u} - \mathbf{v}\rVert = \sqrt{2 - 2\cos\theta}.

Worked example

ResNet-18 ends in global average pooling to 512 features. For 5 target classes the new head Linear(512, 5) has 512⋅5+5=2565512 \cdot 5 + 5 = 2565 parameters, the only trainable ones if the backbone is frozen. Unfreezing the last stage (layer4, 8,393,7288{,}393{,}728 parameters) as well makes 8,396,2938{,}396{,}293 of the 11,179,07711{,}179{,}077 parameters trainable.

Contrastive batch with N=8N = 8 images: 16 views; each anchor has 1 positive and 14 negatives, so 15 terms in the denominator. With unit vectors and τ=1\tau = 1, even a perfect encoder (positive similarity 1, negatives −1-1) has loss log⁡(1+14e−2)≈1.06\log(1 + 14e^{-2}) \approx 1.06; with τ=0.1\tau = 0.1 it drops to about 3×10−83 \times 10^{-8}, which is why the temperature is needed.

In code

import torch
import torchvision
from torch import nn
model = torchvision.models.resnet18(weights=None)  # weights="IMAGENET1K_V1" in practice
for p in model.parameters():
    p.requires_grad = False                         # 1) freeze the backbone ...
model.fc = nn.Linear(model.fc.in_features, 5)        # 2) ... then add a new, trainable head
print(sum(p.numel() for p in model.parameters() if p.requires_grad))  # 2565
opt = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=1e-3)
print(model(torch.zeros(2, 3, 224, 224)).shape)     # torch.Size([2, 5])

Common pitfalls

References

  1. Dive into Deep Learning — Sec. 14.2.1 Steps; 14.2.2.1 Reading the Dataset; 14.2.2.2 Defining and Initializing the Model; 14.2.3 Summary
  2. CS231n course notes: Transfer Learning — Transfer Learning (ConvNet as fixed feature extractor; When and how to fine-tune?; Practical advice)
  3. Yosinski et al. (2014), How transferable are features in deep neural networks? — Abstract; Sec. 4.1 Similar Datasets (Random A/B splits)
  4. Howard & Ruder (2018), Universal Language Model Fine-tuning for Text Classification — Sec. 3.2 Target task LM fine-tuning (Discriminative fine-tuning, Slanted triangular learning rates); 3.3 Target task classifier fine-tuning (Gradual unfreezing)
  5. Kumar et al. (2022), Fine-Tuning can Distort Pretrained Features and Underperform Out-of-Distribution — Abstract
  6. Dive into Deep Learning — Sec. 4.7.1 Types of Distribution Shift; 4.7.3.2 Covariate Shift Correction; 4.7.3.3 Label Shift Correction
  7. Chen et al. (2020), A Simple Framework for Contrastive Learning of Visual Representations (SimCLR) — Abstract; Sec. 2.1 The Contrastive Learning Framework; 3 Data Augmentation for Contrastive Representation Learning; 5.2 Contrastive learning benefits (more) from larger batch sizes and longer training
  8. Dive into Deep Learning — Sec. 14.12.1 Method; 14.12.4 Extracting Features; 14.12.5 Defining the Loss Function