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 — Lab: Transfer Learning and Fine-Tuning

Open in Colab

Lab Overview

You will write the small pieces that transfer learning is made of: freezing a network, the preprocessing it expects, learning-rate groups, LoRA’s forward pass, merge and parameter count, and a Vision Transformer’s patches.

ExerciseTopicPoints
1Freezing and counting10
2ImageNet normalisation10
3Learning-rate groups15
4The LoRA forward pass15
5Merging LoRA10
6Counting LoRA’s parameters10
7Patches for a Vision Transformer20
8Tokens and attention scores10
ChallengeA nearest-centroid classifier on features+10

How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Do not change the check cells. No download is needed: the networks are built without pretrained weights.


Exercise 1: Freezing and Counting (10 points)

freeze_all_but(model, prefixes) sets requires_grad = False on every parameter whose name does not start with one of the prefixes, and True on the others. count_trainable(model) returns the number of trainable values.


Exercise 2: ImageNet Normalisation (10 points)

imagenet_normalise(x) takes images (n, 3, H, W) with values in [0,1][0, 1] and subtracts the channel means (0.485,0.456,0.406)(0.485, 0.456, 0.406), then divides by the channel standard deviations (0.229,0.224,0.225)(0.229, 0.224, 0.225).


Exercise 3: Learning-Rate Groups (15 points)

param_groups(model, body_lr, head_lr) returns a list of two dictionaries for torch.optim: the trainable parameters of the head (model.fc) with head_lr, and every other trainable parameter with body_lr. Frozen parameters appear in neither.


Exercise 4: The LoRA Forward Pass (15 points)

A linear layer computes y=xW⊤+by = x W^\top + b for a batch xx of shape (n,din)(n, d_{\text{in}}), with WW of shape (dout,din)(d_{\text{out}}, d_{\text{in}}). With LoRA, lora_forward(x, W, b, A, B, alpha) returns xW⊤+b+αr xA⊤B⊤x W^\top + b + \frac{\alpha}{r}\, x A^\top B^\top, where AA is (r,din)(r, d_{\text{in}}) and BB is (dout,r)(d_{\text{out}}, r). Compute the LoRA term without forming BABA (multiply xx by A⊤A^\top first). Use NumPy.


Exercise 5: Merging LoRA (10 points)

lora_merge(W, A, B, alpha) returns the merged weight W+αrBAW + \frac{\alpha}{r} B A, so that a plain linear layer gives the same outputs as the LoRA layer.


Exercise 6: Counting LoRA’s Parameters (10 points)

lora_params(d_in, d_out, r) is the number of values LoRA trains for one (dout,din)(d_{\text{out}}, d_{\text{in}}) matrix.


Exercise 7: Patches for a Vision Transformer (20 points)

patchify(img, p) takes an image (C, H, W) (NumPy) whose height and width are multiples of p, and returns an array (H/p * W/p, C*p*p): one row per patch, row by row (left to right, then top to bottom), each row the patch flattened in the order (C, p, p).


Exercise 8: Tokens and Attention Scores (10 points)

vit_counts(image_size, patch) returns (tokens, scores): the number of tokens the encoder sees (the patches plus one class token), and the number of attention scores one head computes in one layer (every token with every token).


Challenge: A Nearest-Centroid Classifier on Features (+10 points)

On pretrained features, even the simplest classifier works. centroid_fit(F, y) returns a (classes, d) array with the mean feature vector of each class (classes 0 .. max(y)); centroid_predict(C, F) returns, for each row of F, the class whose centroid is nearest (Euclidean distance).


Lab Report

Submit this notebook with:

  • every check cell showing ✅,

  • one paragraph: Exercise 4 asks you to compute xA⊤x A^\top first instead of forming BABA. For a 4096×40964096 \times 4096 layer, r=8r = 8 and a batch of 32, compare the number of multiplications of the two orders.