Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 19: Transfer Learning and Fine-Tuning

Open in Colab

If I have seen further, it is by standing on the shoulders of giants.

Isaac Newton, letter to Robert Hooke (1675)

19.1 Why Start From a Trained Network?

Training a large image network from scratch takes a large labelled dataset and a lot of computation: ResNet-50 was trained on the 1.28 million images of ImageNet for days on several GPUs. Most real problems have neither: a hospital may have a few thousand labelled scans, a factory a few hundred photos of defects.

Chapter 17 showed why that need not matter. The layers of an image network form a hierarchy: edges and colours, then textures, parts, objects. The early and middle layers are not specific to ImageNet’s thousand classes; they describe images in general (Yosinski et al., 2014, measured how general each layer is). Transfer learning reuses them: take a network trained on a large source task, keep most of what it learned, and adapt it to the target task with the data you have.

There are two ways to adapt it:

  • Feature extraction: freeze the pretrained network, and train only a new output layer on top of its features.

  • Fine-tuning: also continue training some or all of the pretrained layers, gently, on the new data.

We compare them on a small image task, against a network trained from scratch.

19.2 The Task: 2 000 Photographs

CIFAR-10 has 60 000 colour photographs of 32×32 pixels in 10 classes (planes, cars, birds, cats, deer, dogs, frogs, horses, ships, trucks). To imitate a small real project, we keep only 200 training images per class (2 000 in all) and 100 test images per class (1 000). The data are downloaded once (170 MB) into a cache folder.

training (2000, 3, 32, 32), test (1000, 3, 32, 32)
<Figure size 1300x170 with 10 Axes>

A training loop shared by every experiment. It takes the inputs (images, or features computed from them), a flipped copy of them for augmentation (a horizontal flip keeps the label of every CIFAR-10 class), and trains only the parameters that require a gradient. Frozen batch-normalisation layers stay in evaluation mode, so that their running statistics, learned on ImageNet, are not changed.

19.3 A Baseline: Training From Scratch

A small convolutional network in the style of Chapter 17 (three convolutional layers with batch normalisation, global average pooling), trained for 30 epochs on the 2 000 images at their own size of 32×32:

from scratch: 94986 parameters, test accuracy 0.445 (74 s)

0.445: much better than the 0.100 of guessing, but far from useful. From 2 000 images, a network that starts with random weights cannot learn much about what birds, cats and ships look like.

19.4 Feature Extraction

ResNet-18 (Chapter 18) was trained on ImageNet’s 1.28 million images. torchvision downloads its weights (45 MB). Two details matter when reusing it:

  • The preprocessing must match what the network saw in training: images of a similar size, normalised with ImageNet’s channel means and standard deviations. We enlarge our 32×32 images to 128×128 (224×224 would be slightly better and about three times slower on a CPU).

  • Frozen means evaluation mode: the batch-normalisation layers must use their stored statistics.

Because the frozen layers never change, their outputs can be computed once and cached. We cache the output of the second of ResNet’s four stages, layer2, for the training images, their mirror images and the test images; every experiment below starts from there.

ResNet-18: 11,689,512 parameters; ImageNet top-1 accuracy 69.758%
cached in 99 s: layer2 (128, 16, 16), layer3 (256, 8, 8), pooled features (512,)

Each image is now described by 512 features: the global average of ResNet’s last feature maps. Feature extraction trains a single linear layer on them, 5 130 parameters:

feature extraction: 5130 trainable parameters, test accuracy 0.820

0.820, against 0.445 for the network trained from scratch, with a linear model that trains in seconds. ResNet-18 never saw these classes as such (ImageNet has no single “deer” or “frog” category matching CIFAR’s), and never saw images this blurry; its features still separate them far better than anything 2 000 images can teach a new network.

19.5 Fine-Tuning

Feature extraction keeps all of ResNet’s layers as they are. Fine-tuning lets the last ones adapt to the new data as well. The rules:

  • Start from a trained head (or train the new head first), so that the large random gradients of an untrained head do not wreck the pretrained layers.

  • Use a small learning rate, typically 10 to 100 times smaller than for training from scratch.

  • Unfreeze from the top: the last layers are the most specific to the original task; the first ones are the most general.

We fine-tune the last stage (layer4, 8.4 million parameters), starting from the cached layer3 outputs, then the last two stages from the cached layer2 outputs, with Adam at 10-4 for 5 epochs:

layer4: 137 s
layer3 + layer4: 348 s
layer4 at 1e-2: 196 s

feature extraction (head only)             5,130 trainable parameters   test accuracy 0.820
fine-tune layer4, lr 1e-4              8,398,858 trainable parameters   test accuracy 0.862
fine-tune layer3 + layer4, lr 1e-4    10,498,570 trainable parameters   test accuracy 0.885
fine-tune layer4, lr 1e-2              8,398,858 trainable parameters   test accuracy 0.767

Each stage unfrozen helps: 0.820 with the head alone, 0.862 with layer4, 0.885 with layer3 as well. The last line is the warning: the same fine-tuning of layer4 with a learning rate of 10-2 ends at 0.767, worse than not fine-tuning at all. Large steps overwrite the pretrained weights before the new data can say anything useful about them; with only 2 000 images, what is destroyed cannot be learned back. This is a form of catastrophic forgetting.

Refinements used in practice:

  • Discriminative learning rates: smaller for early layers, larger for later ones and the head (torch.optim accepts a list of parameter groups, each with its own rate; see the implementation notebook).

  • Gradual unfreezing: train the head, then unfreeze one stage at a time.

  • Warm-up and decay (Chapter 16), and early stopping on validation data.

19.6 How Much Data Do You Need?

Transfer pays most when the target data are scarce. The same feature extractor with 10, 50 and 200 training images per class, against the network trained from scratch on the same images:

 10 images per class: pretrained features 0.667, from scratch 0.317
 50 images per class: pretrained features 0.804, from scratch 0.360
200 images per class: pretrained features 0.820, from scratch 0.445

With 10 photos per class, 100 in all, the pretrained features reach 0.667: far more than the network trained from scratch reaches with 200 per class (0.445). From scratch, 10 and 50 per class give 0.317 and 0.360; the features give 0.667 and 0.804. The features are already close to their best with 50 per class: what limits them then is the features themselves, which is when fine-tuning starts to pay.

19.7 Choosing a Strategy

Target data similar to the source (e.g. photos)Target data different (e.g. X-rays, satellite images)
Little data (hundreds to a few thousand)feature extraction; maybe fine-tune the last stagefine-tune more layers, gently; features of early layers
Much data (tens of thousands or more)fine-tune all layersfine-tune all layers, or train from scratch

Three cautions:

  • Domain gap: the further the target is from the source, the less the late layers help. Medical and satellite images often benefit from models pretrained on similar images.

  • Preprocessing must match the source model’s (size, normalisation, colour order); weights.transforms() gives it.

  • Licences and bias: a pretrained model brings its training data’s biases and its licence terms with it (Chapter 12).

19.8 Parameter-Efficient Fine-Tuning: LoRA

Fine-tuning every weight of a model with billions of parameters needs memory for the gradients and optimiser state of all of them, and a full copy of the model for each task. Parameter-efficient fine-tuning (PEFT) trains a small number of new parameters and freezes the rest.

LoRA (Low-Rank Adaptation, Hu et al., 2021) keeps each pretrained weight matrix WW frozen and learns a low-rank update:

W′=W+αr BA,A∈Rr×din,  B∈Rdout×r,  r≪dW' = W + \frac{\alpha}{r}\, B A, \qquad A \in \mathbb{R}^{r \times d_{\text{in}}},\; B \in \mathbb{R}^{d_{\text{out}} \times r},\; r \ll d

BB starts at zero, so training starts exactly from the pretrained model. For a 512×4608512 \times 4608 matrix (a 3×33 \times 3 convolution from 512 to 512 channels, flattened), r=4r = 4 trains 4×(4608+512)=20 4804 \times (4608 + 512) = 20\,480 numbers instead of 2.4 million. After training, BABA can be added into WW: the adapted model is exactly as fast as the original. Different tasks are just different small (A,B)(A, B) pairs on top of one shared model.

We apply LoRA to every convolution of layer4:

LoRA r = 4: 80,906 trainable parameters, test accuracy 0.833 (179 s)
LoRA r = 16: 308,234 trainable parameters, test accuracy 0.840 (158 s)

With rank 4, LoRA trains 80 906 parameters, 1% of layer4’s 8.4 million, and reaches 0.833: most of the way from feature extraction (0.820) to full fine-tuning of the stage (0.862). Rank 16 (308 234 parameters) gives 0.840. LoRA uses a larger learning rate (10-3) than full fine-tuning, because the update starts at zero and cannot overwrite the pretrained weights.

Other PEFT methods:

  • Adapters (Houlsby et al., 2019) insert small bottleneck layers between frozen ones.

  • Prompt and prefix tuning learn a few extra input vectors for a Transformer, leaving every weight frozen.

  • QLoRA (Dettmers et al., 2023) stores the frozen model in 4-bit precision and trains LoRA on top: a 65-billion-parameter language model can be fine-tuned on a single GPU.

LoRA is the standard way to adapt large language models to a task or a domain (Chapter 21).

19.9 Vision Transformers

Chapter 18 introduced the Transformer, built on attention, for sequences of words. The Vision Transformer (ViT, Dosovitskiy et al., 2020) applies it to images with almost no change:

  1. Cut the image into patches (16×16 pixels for a 224×224 image: 196 patches).

  2. Flatten each patch and map it linearly to a vector: a token. (This is a convolution with a 16×16 kernel and stride 16.)

  3. Add a learned position embedding to each token, since attention by itself ignores order, and prepend a learnable class token.

  4. Run a standard Transformer encoder: every patch attends to every other patch, from the first layer on.

  5. Classify from the class token’s final vector.

tiny ViT from scratch: 311,338 parameters, test accuracy 0.425 (822 s)
small CNN from scratch: 94,986 parameters, test accuracy 0.445

The tiny ViT, with three times as many parameters (311 338 against 94 986), scores 0.425, below the small CNN’s 0.445. A convolution builds in two assumptions that hold for images, locality and weight sharing (Chapter 17); a ViT has neither, and must learn from the data that neighbouring patches are related. With 2 000 images, it cannot.

With enough data the balance reverses. Trained on ImageNet alone, the original ViTs did worse than ResNets of a similar size; pretrained on 14 million (ImageNet-21k) or 300 million images, they matched or beat the best convolutional networks, and they transfer very well. Later work (DeiT, Touvron et al., 2021) made ViTs trainable on ImageNet alone with strong augmentation and distillation. In practice, as with CNNs, nobody trains a ViT from scratch for a small task: one fine-tunes a pretrained one, often with LoRA.

19.10 Summary

  • A network trained on a large dataset learns general features; transfer learning reuses them for a smaller task.

  • Feature extraction freezes the network and trains a new head: 0.820 on 2 000 CIFAR-10 images, against 0.445 from scratch.

  • Fine-tuning unfreezes the last stages with a small learning rate (0.862, 0.885); a large rate destroys the pretrained features (0.767).

  • The less data you have, the more transfer helps; the further the domain, the more layers need adapting.

  • LoRA freezes each weight matrix and learns a low-rank update: 1% of the parameters, most of the gain, and no extra cost at inference.

  • A Vision Transformer treats an image as a sequence of patch tokens; it has fewer built-in assumptions than a CNN, so it needs large-scale pretraining, and then transfers very well.

Exercises

  1. Why must a pretrained network’s batch-normalisation layers stay in evaluation mode during feature extraction? What would change if they did not?

  2. You have 300 labelled chest X-rays and a ResNet pretrained on ImageNet. Which strategy would you try first, and which preprocessing would you check?

  3. Fine-tuning with a learning rate of 10-2 gave a worse result than not fine-tuning at all. Explain why, and name two ways to prevent it.

  4. A weight matrix is 1024×10241024 \times 1024. How many parameters does LoRA train with r=8r = 8? What fraction of the matrix is that?

  5. Why is BB initialised to zero in LoRA, and not AA as well?

  6. A ViT takes 224×224 images with 16×16 patches. How many tokens does the encoder see, class token included? How many attention scores does one head compute in one layer?

  7. Explain, in terms of built-in assumptions, why a CNN beats a ViT on 2 000 images but a ViT pretrained on 300 million images beats a CNN.

Further Reading

  • J. Yosinski, J. Clune, Y. Bengio, H. Lipson, “How transferable are features in deep neural networks?”, NeurIPS, 2014.

  • K. He, X. Zhang, S. Ren, J. Sun, “Deep residual learning for image recognition”, CVPR, 2016.

  • J. Howard, S. Ruder, “Universal language model fine-tuning for text classification”, ACL, 2018 (discriminative rates, gradual unfreezing).

  • E. Hu et al., “LoRA: low-rank adaptation of large language models”, ICLR, 2022; T. Dettmers et al., “QLoRA”, NeurIPS, 2023.

  • N. Houlsby et al., “Parameter-efficient transfer learning for NLP”, ICML, 2019.

  • A. Dosovitskiy et al., “An image is worth 16x16 words: Transformers for image recognition at scale”, ICLR, 2021.

  • H. Touvron et al., “Training data-efficient image transformers and distillation through attention” (DeiT), ICML, 2021.