Chapter 19 — Lab: Transfer Learning and Fine-Tuning
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.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Freezing and counting | 10 |
| 2 | ImageNet normalisation | 10 |
| 3 | Learning-rate groups | 15 |
| 4 | The LoRA forward pass | 15 |
| 5 | Merging LoRA | 10 |
| 6 | Counting LoRA’s parameters | 10 |
| 7 | Patches for a Vision Transformer | 20 |
| 8 | Tokens and attention scores | 10 |
| Challenge | A 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.
import math
import numpy as np
import torch
import torch.nn as nn
from torchvision.models import resnet18
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
rng = np.random.default_rng(0)
print('Setup complete')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.
def freeze_all_but(model, prefixes):
# TODO
raise NotImplementedError
def count_trainable(model):
# TODO
raise NotImplementedErrornet = resnet18(weights=None); net.fc = nn.Linear(512, 10)
freeze_all_but(net, ['fc'])
check('only the new head: 5 130 values', lambda: count_trainable(net) == 5130)
freeze_all_but(net, ['layer4', 'fc'])
check('layer4 and the head: 8 398 858 values', lambda: count_trainable(net) == 8398858)
check('the first convolution stays frozen', lambda: net.conv1.weight.requires_grad is False)Exercise 2: ImageNet Normalisation (10 points)¶
imagenet_normalise(x) takes images (n, 3, H, W) with values in and subtracts the channel means , then divides by the channel standard deviations .
def imagenet_normalise(x):
# TODO
raise NotImplementedErrorx = torch.rand(2, 3, 8, 8)
check('the shape is kept', lambda: imagenet_normalise(x).shape == x.shape)
check('a pixel equal to the means becomes 0', lambda: torch.allclose(imagenet_normalise(torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)), torch.zeros(1, 3, 1, 1), atol=1e-6))
check('each channel uses its own statistics', lambda: torch.allclose(imagenet_normalise(torch.ones(1, 3, 1, 1)).flatten(), torch.tensor([(1 - .485) / .229, (1 - .456) / .224, (1 - .406) / .225]), atol=1e-5))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.
def param_groups(model, body_lr, head_lr):
# TODO
raise NotImplementedErrornet = resnet18(weights=None); net.fc = nn.Linear(512, 10)
freeze_all_but(net, ['layer4', 'fc'])
groups = param_groups(net, 1e-4, 1e-3)
check('two groups with the two rates', lambda: [g['lr'] for g in groups] == [1e-4, 1e-3])
check('the head group holds fc\'s weight and bias', lambda: sum(p.numel() for p in groups[1]['params']) == 5130)
check('the body group holds layer4 only (frozen layers left out)', lambda: sum(p.numel() for p in groups[0]['params']) == 8398858 - 5130)
check('torch.optim accepts them', lambda: torch.optim.AdamW(groups) is not None)Exercise 4: The LoRA Forward Pass (15 points)¶
A linear layer computes for a batch of shape , with of shape . With LoRA, lora_forward(x, W, b, A, B, alpha) returns , where is and is . Compute the LoRA term without forming (multiply by first). Use NumPy.
def lora_forward(x, W, b, A, B, alpha):
# TODO
raise NotImplementedErrord_in, d_out, r = 20, 12, 4
W, b = rng.normal(size=(d_out, d_in)), rng.normal(size=d_out)
A, B = rng.normal(size=(r, d_in)), np.zeros((d_out, r))
xb = rng.normal(size=(5, d_in))
check('with B = 0, LoRA changes nothing', lambda: np.allclose(lora_forward(xb, W, b, A, B, 8), xb @ W.T + b))
B2 = rng.normal(size=(d_out, r))
check('the scaled low-rank term is added', lambda: np.allclose(lora_forward(xb, W, b, A, B2, 8), xb @ (W + 2 * B2 @ A).T + b))Exercise 5: Merging LoRA (10 points)¶
lora_merge(W, A, B, alpha) returns the merged weight , so that a plain linear layer gives the same outputs as the LoRA layer.
def lora_merge(W, A, B, alpha):
# TODO
raise NotImplementedErrorWm = lora_merge(W, A, B2, 8)
check('the merged layer gives the same outputs', lambda: np.allclose(xb @ Wm.T + b, lora_forward(xb, W, b, A, B2, 8)))
check('the original W is not modified', lambda: not np.allclose(Wm, W))Exercise 6: Counting LoRA’s Parameters (10 points)¶
lora_params(d_in, d_out, r) is the number of values LoRA trains for one matrix.
def lora_params(d_in, d_out, r):
# TODO
raise NotImplementedErrorcheck('a 1024 x 1024 matrix with r = 8: 16 384', lambda: lora_params(1024, 1024, 8) == 16384)
check('a flattened 3x3 convolution 512 -> 512 with r = 4: 20 480', lambda: lora_params(512 * 9, 512, 4) == 20480)
check('a tiny fraction of the matrix', lambda: lora_params(4096, 4096, 16) / (4096 * 4096) < 0.01)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).
def patchify(img, p):
# TODO
raise NotImplementedErrorimg = np.arange(2 * 4 * 4).reshape(2, 4, 4).astype(float)
P = patchify(img, 2)
check('4 patches of 2 x 2 x 2 = 8 values', lambda: P.shape == (4, 8))
check('the first patch: top-left corner of both channels', lambda: P[0].tolist() == [0, 1, 4, 5, 16, 17, 20, 21])
check('the second patch is to the right of the first', lambda: P[1].tolist() == [2, 3, 6, 7, 18, 19, 22, 23])
big = rng.normal(size=(3, 32, 32))
conv = nn.Conv2d(3, 5, 4, stride=4, bias=False)
check('a patch embedding = patchify then one matrix product', lambda: np.allclose(patchify(big, 4) @ conv.weight.detach().numpy().reshape(5, -1).T,
conv(torch.tensor(big, dtype=torch.float32)[None])[0].flatten(1).T.detach().numpy(), atol=1e-4))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).
def vit_counts(image_size, patch):
# TODO
raise NotImplementedErrorcheck('ViT-B/16 at 224: 197 tokens, 38 809 scores', lambda: vit_counts(224, 16) == (197, 38809))
check('the tiny ViT of the chapter: 32 px, patches of 4', lambda: vit_counts(32, 4) == (65, 4225))
check('halving the patch size multiplies the scores by about 16', lambda: 15 < vit_counts(224, 8)[1] / vit_counts(224, 16)[1] < 17)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).
def centroid_fit(F, y):
# TODO
raise NotImplementedError
def centroid_predict(C, F):
# TODO
raise NotImplementedErrorFa = np.vstack([rng.normal(0, 1, (50, 4)), rng.normal(5, 1, (50, 4))]); ya = np.repeat([0, 1], 50)
Cc = centroid_fit(Fa, ya)
check('two centroids near 0 and 5', lambda: Cc.shape == (2, 4) and abs(Cc[0].mean()) < .5 and abs(Cc[1].mean() - 5) < .5)
check('predicts the nearest centroid', lambda: (centroid_predict(Cc, np.array([[0.2] * 4, [4.6] * 4, [2.4] * 4])) == [0, 1, 0]).all())Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: Exercise 4 asks you to compute first instead of forming . For a layer, and a batch of 32, compare the number of multiplications of the two orders.