Lesson 16 of 186 min
Pretraining and transfer learning
Start from a network already trained on millions of photos, give it a new last layer for your own kinds, and train only that layer when your photos are few, or all of it, gently, when you have more.
After this lesson you can reuse a pretrained network and fine-tune it on a small dataset.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Prepare photos the same way
Load the image processor that comes with the network. It handles resizing, cropping, and normalization. Use it for training, validation, testing, and new photos from the phone. Here each picture becomes three channels of 224 by 224 numbers.
from io import BytesIO
from zipfile import ZipFile
import torch
from PIL import Image
from huggingface_hub import hf_hub_download
from transformers import AutoImageProcessor, AutoModel
source = "AI-Lab-Makerere/beans"
name = "facebook/dinov2-small"
processor = AutoImageProcessor.from_pretrained(name)kinds = ["healthy", "angular_leaf_spot", "bean_rust"]
def leaf_split(split, per_kind=None):
path = hf_hub_download(source, f"data/{split}.zip", repo_type="dataset")
rows = []
with ZipFile(path) as photos:
for label, kind in enumerate(kinds):
files = sorted(f for f in photos.namelist() if f.endswith(".jpg") and f.split("/")[-2] == kind)
rows.extend((Image.open(BytesIO(photos.read(f))).convert("RGB"), label) for f in files[:per_kind])
return rowstrain = leaf_split("train", per_kind=10)
batch = processor(images=[photo for photo, _ in train], return_tensors="pt")
print(tuple(batch.pixel_values.shape))(30, 3, 224, 224)
Save the frozen numbers
With the network frozen and in evaluation mode, you can extract its features once. Work in batches so you can reuse the same function for larger splits. Store the labels in the same order and save which model and processor made the features. Recompute them after the network changes.
net = AutoModel.from_pretrained(name).eval().requires_grad_(False)
@torch.no_grad()
def encode(rows):
features = []
for start in range(0, len(rows), 16):
photos = [photo for photo, _ in rows[start:start + 16]]
inputs = processor(images=photos, return_tensors="pt")
features.append(net(**inputs).pooler_output)
return torch.cat(features), torch.tensor([label for _, label in rows])features, labels = encode(train)
torch.save({"features": features, "labels": labels, "model": name}, "leaf-features.pt")
print(tuple(features.shape))(30, 384)
Train the new layer first
A randomly initialized layer can send large gradients through the pretrained network. In the lesson's runs with ten photos of each kind, training everything from the start averaged 61% on validation. Training the new layer first, then fine-tuning, averaged 76%. Here is the first stage. The validation set is where you compare what to do next.
torch.manual_seed(0)
head = torch.nn.Linear(net.config.hidden_size, len(kinds))
opt = torch.optim.AdamW(head.parameters(), lr=1e-3)
for _ in range(100):
opt.zero_grad()
torch.nn.functional.cross_entropy(head(features), labels).backward()
opt.step()
print(sum(p.numel() for p in head.parameters()))1155
Try unfreezing one block
Unfreeze the last block first if you want to test a smaller change. On images far from the pretraining photos, frozen features may miss what matters. Compare freezing, partial unfreezing, and full fine-tuning on validation. Recompute the features from images in the training loop so gradients can reach the layers you unfreeze.
net.encoder.layer[-1].requires_grad_(True)
trainable = [p for p in net.parameters() if p.requires_grad]
partial_opt = torch.optim.AdamW([*trainable, *head.parameters()], lr=1e-5)
print(0 < sum(p.numel() for p in trainable) < sum(p.numel() for p in net.parameters()))True
Open the test set once
Once you've fixed the recipe using validation, score the chosen model on the test photos. The dataset provides 128 for that last check. Here the frozen recipe is chosen in advance for the example. Run the cell after choosing your own recipe and report the score with the size of the test set.
net.eval().requires_grad_(False)
test_features, test_labels = encode(leaf_split("test"))
with torch.no_grad():
correct = (head(test_features).argmax(dim=1) == test_labels).sum().item()
print(f"{correct} of {len(test_labels)} right")96 of 128 right
Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The training loop
A training loop runs loss.backward(), then opt.zero_grad(), then opt.step(). Nothing crashes. For 30 epochs, the loss prints 2.33. What is wrong?
2 of 3
You fine-tune all of a pretrained network on 10 photos of each kind, at 0.001, the rate this course usually trains with. It gets 38%, worse than from scratch. What happened?
3 of 3
DINOv2 describes a photo as 384 numbers. You put a new last layer on its end for 5 kinds of leaf, and freeze the rest. How many weights learn?
The ideas in this lesson
- Pretraining
- Train a network first on a big general task, so its hidden layers describe new inputs in useful numbers.
- Transfer learning
- Keep a pretrained network, give it a new last layer for your own kinds, and train on your few examples.
- Freeze or fine-tune
- Freeze it and train the new layer when examples are few; with more, train every weight at a small rate.
It leans on
- A PyTorch class
- Fine-tuning an LLM
Transcript
What the video says, part by part. Press a time to watch from there.
So few photos
Here's a challenge. You want an app that spots sick plant leaves. But you only have a few photos of each kind. So can a network learn from so few photos?
Three ways
Here are the photos. Bean leaves, from fields in Uganda, of three kinds: healthy, and two kinds of disease. You have ten photos of each kind. Here are three ways.
One: train a network from scratch. Two: take a network that was already trained, on over a hundred million photos. Keep it as it is, and only train a new last layer. Three: train all of that network, gently.
Which way scores best on other photos, set aside, that it never learns from?
From scratch
First, from scratch: the course's way, from random starting weights. On the photos set aside, it gets sixty-one percent right. Picking at random would get thirty-three. We picked the ten photos of each kind at random, three times over. Sixty-one percent is the average.
Starting from nothing, thirty photos are too few to learn what a leaf looks like.
A pretrained network
A network doesn't learn much from a few photos. So start from one that's already trained, on a big task. That's called a pretrained network. This one is DINOv2.
It learned from over a hundred million photos, with no labels.
Its hidden layers describe any photo as three hundred and eighty-four numbers. Photos that look alike... get close numbers.
That works for leaves, spots and colors too.
Like a doctor
It's like a doctor who learns about a new illness from a few patients, because they already know medicine. But the network only knows numbers that describe photos.
A new last layer, frozen
A pretrained network already describes photos. So put a new last layer on the end. The network's numbers go in, and three scores come out, one for each kind.
Then freeze the rest. Its twenty-two million weights stay as they are. Only the new layer learns: one weight for each number, for each kind, and three biases. Just over a thousand in all. So, your guess. With ten photos of each kind... eighty-two percent. And it trains in about a second.
Transfer learning
You take a network trained for one job, and reuse it for yours. That's called transfer learning.
Fine-tuning
A pretrained network, with a new last layer. So why not train all of it? That's called fine-tuning. Every weight learns, but gently. Its learning rate is small. And it only starts after the new layer has learned. That way, the new layer's first big slopes don't damage the rest. Does it help? With ten photos of each kind, it gets seventy-six percent. That's below the frozen network in two picks out of three. Thirty photos are too few to move twenty-two million weights safely.
More photos
So with twenty photos of each kind, does fine-tuning win?
Yes, in every pick. Ninety-three percent, versus eighty-three.
And with a hundred photos of each kind, ninety-eight and a half, versus ninety-two.
A big learning rate
Does the learning rate matter? Train all of it at the rate this course usually trains with. Guess what happens.
Thirty-eight percent. That's worse than training from scratch.
For a pretrained network, those steps are too big. They wipe out what it learned from all those photos.
And thirty photos can't teach it again.
So fine-tune a hundred times more gently.
Which one
So which do you choose?
If you only have a few photos, or not much time, freeze it. It trains in a second. And only those thousand or so weights need their slopes and Adam's numbers, not twenty-two million.
If you have more photos, fine-tune it, gently.
The real case
This set of bean leaves was made in Uganda, for an app that farmers could use in the field. And the chatbots you use are made the same way: a pretrained network, fine-tuned to chat.
In code
In code, one line loads DINOv2. A loop tells every one of its weights not to learn. So how many of DINOv2's weights still learn?
None. Then a new layer: DINOv2's numbers in, three scores out.
The optimizer only gets the new layer's weights, at the usual rate, since a new layer starts from nothing. To fine-tune, let every weight learn again, and give the optimizer all of them, at a small rate.
Start from what it knows
So start from a pretrained network, with a new last layer. Freeze it when you only have a few photos. Fine-tune it gently when you have more.
Already knows
Start from a network that already knows photos. Now try it on this lesson's page, and take the quiz. Find out how many photos fine-tuning needs.
You use this lesson in Lab 7: Digits from ten labels a kind, after Autoencoders and latent space.
Facts last checked on .
