Repository navigation
Module 22
⬅️ Module 21 · 🗺️ Curriculum · 🏠 Home · Module 23 ➡️
Level: Intermediate · Prerequisites: Modules 10, 11, 14 · Time: about 6–7 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Training from scratch needs vast data and compute. Transfer learning reuses knowledge from a source task/domain (large pretraining) to improve a target task with little data. Today it is the default workflow: pretrain a foundation model once, then adapt cheaply. This module covers feature extraction and fine-tuning, domain adaptation theory, catastrophic forgetting, and parameter-efficient methods (adapters, LoRA, prompt tuning).
After this module you should be able to:
- choose between feature extraction, full fine-tuning and parameter-efficient tuning;
- state the domain-adaptation generalisation bound and explain domain-adversarial training;
- explain catastrophic forgetting and EWC; write the LoRA update and count its parameters;
- plan an adaptation experiment with the right learning rates, baselines and evaluation.
A person who can ride a bicycle learns a motorbike faster. Pretrained networks have learned general features (edges and textures in vision; syntax and facts in language) that are useful for many tasks. You can (i) freeze the pretrained network and train only a new output layer (cheap, safe with tiny data), or (ii) fine-tune some or all layers with a small learning rate (more accurate when data suffice).
flowchart TD
S["Start: pretrained model"] --> Q1{"Target data size?"}
Q1 -- "Tiny" --> FE["Feature extraction: freeze backbone, train linear head"]
Q1 -- "Medium" --> Q2{"Domain close to source?"}
Q1 -- "Large" --> FT["Full fine-tuning (small LR)"]
Q2 -- "Yes" --> PEFT["Fine-tune top layers or LoRA/adapters"]
Q2 -- "No" --> FT
FE --> EV["Evaluate on held-out target data"]
PEFT --> EV
FT --> EV
A domain is
Yosinski et al. (2014) showed early layers are general and later layers task-specific, and that transfer helps even from distant tasks. Practical recipe: (1) train a new head on frozen features; (2) unfreeze progressively; (3) use a small learning rate (often
Ben-David et al. bound. For hypothesis
where
Sequential fine-tuning can overwrite earlier skills (McCloskey & Cohen 1989). EWC (Kirkpatrick et al. 2017) adds a quadratic penalty weighted by the diagonal Fisher information
Alternatives: replay/rehearsal buffers, distillation of the old model (LwF), parameter isolation (progressive nets, adapters per task), and mixing in pretraining-like data.
Adapters (Houlsby et al. 2019) insert small bottleneck MLPs (
For a frozen weight
with
Foundation models (Bommasani et al. 2021) are broadly pretrained and adapted to many tasks. Few-shot learning also includes metric/prototype-based methods and meta-learning (MAML). Large language models additionally perform in-context learning: examples in the prompt, with no weight update (Module 23). Rule of thumb: prompt first, then retrieval/prompt tuning, then LoRA, then full fine-tuning, as data and budget grow.
LoRA parameters. Square
Domain bound intuition. Source error
Learning rates. Pretrained backbone fine-tuned at
import torch, torch.nn as nn, torch.nn.functional as F
class LoRALinear(nn.Module):
def __init__(s, base: nn.Linear, r=8, alpha=16):
super().__init__(); s.base, s.scale = base, alpha / r
for p in s.base.parameters(): p.requires_grad = False # freeze W0
s.A = nn.Parameter(torch.randn(r, base.in_features) * 0.01)
s.B = nn.Parameter(torch.zeros(base.out_features, r)) # zero init -> starts at W0
def forward(s, x): return s.base(x) + s.scale * F.linear(F.linear(x, s.A), s.B)
# Discriminative learning rates
opt = torch.optim.AdamW([{"params": backbone.parameters(), "lr": 2e-5},
{"params": head.parameters(), "lr": 1e-3}], weight_decay=0.01)
# Gradient reversal layer (DANN)
class GradReverse(torch.autograd.Function):
@staticmethod
def forward(ctx, x, lam): ctx.lam = lam; return x.view_as(x)
@staticmethod
def backward(ctx, g): return -ctx.lam * g, None-
Model merging / task arithmetic: weight-space averaging (model soups) and task vectors
$\tau=\theta_{ft}-\theta_{pre}$ . - Meta-learning (MAML, Reptile), continual learning benchmarks, test-time training.
- Negative transfer: when source features harm the target; detect with from-scratch baselines.
- Robust fine-tuning (WiSE-FT interpolation, LP-FT: linear probe then fine-tune) preserves out-of-distribution robustness (Kumar et al. 2022).
- Instruction tuning and alignment are adaptation stages for language models (Module 23).
- Scaling of adaptation: data quality dominates; small curated sets can match larger noisy ones.
- Contamination: target test data overlapping with pretraining data.
- Using a high learning rate and destroying pretrained features.
- Forgetting the pretraining preprocessing (normalisation constants, tokenizer, image size).
- Comparing against a weak from-scratch baseline or tuning only the adapted model.
- Unfreezing BatchNorm with tiny batches.
- Evaluating only on target data; also check retained source capabilities if relevant.
Q1. When should you freeze the backbone?
With very little target data or a domain close to the source, where fine-tuning would overfit; train a linear head (probing) first.
Q2. Why use a smaller learning rate for pretrained layers?
Pretrained weights are already good; large updates destroy features, while the randomly initialised head needs larger steps.
Q3. State the domain-adaptation bound and interpret its terms.
Q4. How does gradient reversal align domains?
The domain classifier minimises its loss, but the reversed gradient makes the feature extractor maximise it, pushing features toward domain-indistinguishability while remaining useful for the task.
Q5. What is catastrophic forgetting and how does EWC reduce it?
New-task training overwrites weights important for the old task. EWC penalises changes to parameters with high Fisher information.
Q6. Why does LoRA initialise $B=0$?
So
Q7. What are the advantages of LoRA over full fine-tuning?
Orders of magnitude fewer trainable parameters and optimiser states, small per-task checkpoints, mergeable weights, and less forgetting; at some cost in capacity for very different tasks.
Q8. How do you detect negative transfer?
Compare against a from-scratch (or randomly initialised) baseline trained with equal tuning; if transfer is worse, the source features are harming the target.
- Pan, S. J., & Yang, Q. (2010). A survey on transfer learning. IEEE TKDE, 22(10).
- Yosinski, J., Clune, J., Bengio, Y., & Lipson, H. (2014). How transferable are features in deep neural networks? NeurIPS.
- Ben-David, S., et al. (2010). A theory of learning from different domains. Machine Learning, 79.
- Ganin, Y., et al. (2016). Domain-adversarial training of neural networks. JMLR, 17. arXiv:1505.07818.
- Howard, J., & Ruder, S. (2018). Universal language model fine-tuning for text classification. ACL. arXiv:1801.06146.
- Kirkpatrick, J., et al. (2017). Overcoming catastrophic forgetting in neural networks. PNAS, 114(13). arXiv:1612.00796.
- Houlsby, N., et al. (2019). Parameter-efficient transfer learning for NLP. ICML. arXiv:1902.00751.
- Hu, E. J., et al. (2022). LoRA: low-rank adaptation of large language models. ICLR. arXiv:2106.09685.
- Dettmers, T., et al. (2023). QLoRA: efficient finetuning of quantized LLMs. NeurIPS. arXiv:2305.14314.
- Kornblith, S., Shlens, J., & Le, Q. V. (2019). Do better ImageNet models transfer better? CVPR.
- Kumar, A., et al. (2022). Fine-tuning can distort pretrained features and underperform out-of-distribution. ICLR. arXiv:2202.10054.
- Bommasani, R., et al. (2021). On the opportunities and risks of foundation models. arXiv:2108.07258.
- Finn, C., Abbeel, P., & Levine, S. (2017). Model-agnostic meta-learning. ICML.
⬅️ Module 21 · 🗺️ Curriculum · 🏠 Home · Module 23 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24