Fine-Tuning & Transfer
Reusing pretrained networks: linear probes, fine-tuning and parameter-efficient methods.
Pretraining is expensive and done once; adaptation is cheap and done for every task. This lesson is about the second half: freezing versus fine-tuning, which layers carry over, how to set learning rates so fine-tuning does not wreck what pretraining built, when transfer fails, and the parameter-efficient methods (adapters, prefix and prompt tuning, LoRA) that let one frozen model serve thousands of tasks.
What you’ll learn
- Write a pretrained network as a feature extractor plus a head, and compare linear probing, full fine-tuning and linear probing followed by fine-tuning.
- Summarize what the layer-transfer experiments show about general and specific layers, and choose learning rates for fine-tuning.
- Recognize when transfer fails: a large domain gap, negative transfer and forgetting.
- Count the trainable parameters of adapters, prefix tuning, prompt tuning and LoRA, and show that a LoRA update can be merged into the weights at no inference cost.
- Explain zero-shot transfer with image–text models and what makes a model a foundation model.
Freeze, fine-tune, or both
Write a network trained on a large source task as a feature extractor followed by a head, , and keep the extractor's pretrained weights . For a new target task with labeled data , replace the head and choose how much to train:
- Linear probe: freeze and fit a linear head on the features. With a cross-entropy loss this is multinomial logistic regression: a convex problem with a global optimum, cheap enough to run on features computed once.
- Full fine-tuning: train and together, starting from . The features themselves adapt to the task; usually the most accurate option on data like the target's.
- LP-FT: first a linear probe, then full fine-tuning from that head (Kumar, Raghunathan, Jones, Ma & Liang, 2022). A randomly initialized head produces large, essentially random gradients at the start of fine-tuning, and those flow into the pretrained features and distort them. Starting from a fitted head keeps the early updates small. On their distribution-shift benchmarks, LP-FT beat full fine-tuning both on the target distribution and, by a wider margin, on shifted test sets.
import torch
import torchvision
num_classes = 10
model = torchvision.models.resnet50(weights="IMAGENET1K_V2") # pretrained extractor
model.fc = torch.nn.Linear(model.fc.in_features, num_classes) # new head
# Linear probe: only the head trains
for name, p in model.named_parameters():
p.requires_grad = name.startswith("fc.")
# Full fine-tuning: everything trains, the pretrained layers with a much smaller rate
for p in model.parameters():
p.requires_grad = True
backbone = [p for n, p in model.named_parameters() if not n.startswith("fc.")]
opt = torch.optim.AdamW([{"params": backbone, "lr": 1e-5},
{"params": model.fc.parameters(), "lr": 1e-3}], weight_decay=0.01)Parameter groups give each part of the network its own learning rate. In a probe, also keep batch-normalization layers in evaluation mode so their running statistics stay those of pretraining.
Think first A linear probe can be solved to its global optimum, full fine-tuning cannot. Why is fine-tuning usually still better on the target task?
Because the probe's optimum is the best linear readout of fixed features, and the features were shaped by the source task. Fine-tuning can move the features toward what the target task needs: the nonconvex problem has a better attainable solution even though no optimizer is guaranteed to find the best one. When the target data are scarce or the test data drift away from them, that extra freedom can backfire, which is when probing or LP-FT wins.
What transfers, and how to fine-tune
Yosinski, Clune, Bengio & Lipson (2014) measured transferability layer by layer. They split ImageNet's classes into two halves, trained a network on each, copied the first layers of one into a network for the other task and trained the rest, frozen or fine-tuned. First-layer features (oriented edges, color blobs) worked for either task: they are general. Transferability fell with depth as features became specific to their task, and fell further when the two tasks were less alike. Cutting in the middle of a network also hurt for a second reason, co-adaptation: neighboring layers learn to work together, and retraining the upper ones alone cannot recover the joint solution. Transferred and then fine-tuned networks generalized better than networks trained from scratch on the target task, and the boost lingered even after long fine-tuning.
Two later studies sharpened the picture. Across 16 architectures and 12 image datasets, networks that were more accurate on ImageNet usually transferred better, but some regularizers that raise ImageNet accuracy made the penultimate features worse for transfer (Kornblith, Shlens & Le, 2019). And object detectors trained from random initialization on COCO caught up with ImageNet-pretrained ones given enough training: pretraining sped up convergence more than it raised final accuracy on a large target dataset (He, Girshick & Dollár, 2019).
You fine-tune a pretrained vision transformer on 2,000 labeled images, using the peak learning rate from its pretraining and a randomly initialized head. Validation accuracy ends up close to that of training from scratch. What is the most likely explanation?
- 2,000 images are too few for transfer to help at all
- The large learning rate, together with large early gradients from the random head, moved the pretrained weights far from their starting point and destroyed much of what pretraining learned
- Vision transformers cannot be fine-tuned; they only support linear probes
- The head was too small to use the pretrained features
Show the answer
B. The large learning rate, together with large early gradients from the random head, moved the pretrained weights far from their starting point and destroyed much of what pretraining learned
Fine-tuning works by staying near a good starting point. A pretraining-sized learning rate plus the random head's large initial gradients overwrites the features before the head is useful. Use a much smaller rate for the backbone, warm up, and consider fitting the head first (LP-FT).
When transfer fails
Transfer helps when the source and target share structure, and its value shrinks with the domain gap. Raghu, Zhang, Kleinberg & Bengio (2019) studied ImageNet pretraining for medical images (retinal photographs and chest X-rays): it gave little gain in final accuracy, small lightweight networks trained from scratch did about as well as large pretrained ones, and the consistent benefit was faster convergence, with genuine feature reuse mostly in the lowest layers.
Sometimes transfer hurts. Wang, Dai, Póczos & Carbonell (2019) made negative transfer precise for a given algorithm : compare the target risk when also uses the source data with the risk when it uses the target data alone,
The third failure is the reverse direction: a network fine-tuned on a new task can lose abilities it had, such as accuracy on the original task or robustness to shifted inputs. That is catastrophic forgetting, and it is also a reason parameter-efficient methods, which leave the pretrained weights untouched, became popular for very large models.
Parameter-efficient fine-tuning
Full fine-tuning stores a complete copy of the model per task. Parameter-efficient fine-tuning freezes the pretrained weights and trains a small add-on instead:
- Adapters (Houlsby et al., 2019) insert a bottleneck module inside each transformer layer, with , , initialized near the identity map. Adding 3.6% of the parameters per task, they came within 0.4 points of full fine-tuning on the GLUE benchmark (a score of 80.0 against 80.4).
- Prefix tuning (Li & Liang, 2021) prepends trainable vectors to the keys and values of attention at every layer. Training about 0.1% of the parameters, it matched fine-tuning on generation tasks with full data and did better with little data.
- Prompt tuning (Lester, Al-Rfou & Constant, 2021) trains only a few "soft prompt" embeddings prepended to the input. It lagged fine-tuning for small models, but the gap closed as models grew past billions of parameters.
- LoRA (Hu et al., 2022) adds a trainable low-rank update to a frozen weight matrix : with initialized to zero and random, so training starts exactly at the pretrained model.
Per adapted matrix LoRA trains numbers instead of . An adapter with biases trains ; a prefix of vectors trains per layer (keys and values); a soft prompt of tokens trains in total.
At inference the update is linear in the input, so it can be folded into the weights once, after which the layer is an ordinary matrix multiplication with no extra latency:
Switching tasks means subtracting one product and adding another. Adapters and prefixes, by contrast, add layers or tokens that stay in the forward pass.
| Method (example: layers, ) | Trainable parameters | Extra inference cost |
|---|---|---|
| Full fine-tuning | all billion (non-embedding) | none, but a full copy per task |
| Adapters, , two per layer | million | two small MLPs per layer |
| Prefix tuning, | million | 10 extra keys and values per layer |
| Prompt tuning, | 20 extra input tokens | |
| LoRA on , | million | none once merged |
That LoRA configuration trains about million parameters on a model with about billion. What percentage of the model's parameters is that?
Show the answer
0.065 %
, roughly one parameter in 1,500. Hu et al. reported a reduction of about 10,000 times for GPT-3 with 175 billion parameters, where the ratio is even more extreme.
Zero-shot transfer and foundation models
Some models transfer with no training at all. CLIP (Radford et al., 2021) embeds images and text in one space, so a classifier for any label set can be written in words: embed prompts such as "a photo of a dog." and "a photo of a cat." and assign each image to the label whose text embedding is closest. This zero-shot classifier matched a supervised ResNet-50 on ImageNet without using any of its training images. Large language models adapt in a similar spirit through in-context learning: examples in the prompt, not weight updates, specify the task (Brown et al., 2020).
Bommasani et al. (2021) coined foundation models for networks trained on broad data at scale and adapted to a wide range of tasks by fine-tuning, parameter-efficient methods, prompting or zero-shot use. The term names the pattern of this whole lesson, and its risk: every defect of the base model is inherited by everything adapted from it.
Key takeaways
- Reuse a pretrained network as features plus a head: a linear probe trains only the head (a convex problem), full fine-tuning adapts everything, and LP-FT fits the head first so the features are distorted less.
- Early layers are general and late layers specific; fine-tune with much smaller learning rates than in pretraining, smaller still for lower layers, possibly with a pull back toward the pretrained weights.
- Transfer fades with the domain gap, can turn negative when source and target distributions diverge, and fine-tuning can make a model forget what it knew.
- Adapters ( per module), prefixes ( per layer), soft prompts ( in total) and LoRA ( per matrix) adapt a frozen model with a tiny fraction of its parameters; LoRA's update merges into the weights at no inference cost.
- Image–text models classify zero-shot from label names, and foundation models are adapted to many tasks by fine-tuning, parameter-efficient methods or prompting.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does LP-FT (linear probe first, then full fine-tuning) often beat full fine-tuning from a randomly initialized head, especially on shifted test data?
- It trains for longer in total
- The probe step changes the pretrained features in a useful direction before fine-tuning
- It uses a larger learning rate during fine-tuning
- With a fitted head, the early fine-tuning gradients are small, so the pretrained features are distorted less
Show the answer
D. With a fitted head, the early fine-tuning gradients are small, so the pretrained features are distorted less
A random head makes the loss large and its gradients flow back into the features, changing them in ways that fit the target training data but no longer match inputs outside it. Fitting the head first keeps the features close to their pretrained values while still allowing them to adapt.
In layer-by-layer transfer experiments on image networks, which layers transfer best to a different task?
- The first layers, whose edge and color detectors are general
- The last hidden layer, because it is the most abstract
- The middle layers, because they are the least co-adapted
- All layers transfer equally well when the tasks share an input format
Show the answer
A. The first layers, whose edge and color detectors are general
Yosinski et al. found first-layer features useful for either half of ImageNet, while transferability fell with depth as features became specific to their training task. Middle layers additionally suffered from co-adaptation when the network was cut there.
Why does LoRA add no inference latency, while adapters do?
- LoRA uses lower numerical precision at inference
- LoRA's update is a linear map in parallel with , so can be precomputed into one matrix; an adapter is an extra nonlinear module in the forward pass
- LoRA removes the attention layers it adapts
- LoRA's matrices are discarded after training
Show the answer
B. LoRA's update is a linear map in parallel with , so can be precomputed into one matrix; an adapter is an extra nonlinear module in the forward pass
. Merging gives an ordinary weight matrix of the original shape. An adapter's bottleneck contains a nonlinearity and sits in series with the layer, so it cannot be folded away.
Training with extra source data makes your target-task error higher than training on the target data alone, using the same algorithm. What is this called, and what is its usual root cause?
- Catastrophic forgetting, caused by a learning rate that is too large
- Overfitting, caused by too little source data
- Negative transfer, mainly caused by divergence between the source and target distributions
- Underfitting, caused by a model that is too small for both tasks
Show the answer
C. Negative transfer, mainly caused by divergence between the source and target distributions
Wang et al. define the negative transfer gap as the difference between the two target errors, for a fixed algorithm, and trace it mainly to source–target divergence, with the amount of labeled target data as a second factor. Filtering out dissimilar source data reduced it.
Go deeper
- Low-Rank Adaptation in Depth · Intrinsic dimension, LoRA’s design choices and fine-tuning quantized models.
- Catastrophic Forgetting & Continual Learning · Why new training erases old skills, loss of plasticity, and what regularization and replay do about it.
- Model Merging & Task Arithmetic · Adding and subtracting fine-tuned weights to combine or remove skills.
Further reading
- J. Yosinski, J. Clune, Y. Bengio & H. Lipson, "How transferable are features in deep neural networks?," NeurIPS (2014).
- N. Houlsby et al., "Parameter-efficient transfer learning for NLP," ICML (2019).
- E. J. Hu et al., "LoRA: low-rank adaptation of large language models," ICLR (2022).
- A. Kumar, A. Raghunathan, R. Jones, T. Ma & P. Liang, "Fine-tuning can distort pretrained features and underperform out-of-distribution," ICLR (2022).