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 — Implementation

Open in Colab
  1. What a pretrained network sees: ImageNet predictions on CIFAR-10 photos

  2. Any classifier on top of pretrained features

  3. Discriminative learning rates with parameter groups

  4. LoRA for a linear layer, and merging it back

  5. Saving only what was trained

  6. Inside a Vision Transformer

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.

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?

<Figure size 1400x300 with 6 Axes>

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.

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:

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:

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.

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:

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.