Skip to content

Module 22

Anurag Prasad edited this page Nov 9, 2026 · 9 revisions

Module 22 — Transfer Learning, Domain Adaptation and Foundation Models

⬅️ 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


Overview and learning goals

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.

Beginner: the big picture

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
Loading

Core concepts and derivations

Source and target domains and tasks

A domain is $(\mathcal{X},p(\mathbf{x}))$; a task is $(\mathcal{Y},p(y\mid\mathbf{x}))$. Settings: same domain/new task (ImageNet → medical classes), new domain/same task (domain adaptation: synthetic → real), sequential tasks (continual learning). Covariate shift: $p_S(\mathbf{x})\ne p_T(\mathbf{x})$ but $p(y\mid\mathbf{x})$ shared; label shift: $p(y)$ changes; concept shift: $p(y\mid\mathbf{x})$ changes.

Feature extraction versus fine-tuning

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 $10\times$–$100\times$ smaller than from-scratch) and discriminative learning rates — lower for earlier layers (ULMFiT, Howard & Ruder 2018) — with warm-up and weight decay. Keep BatchNorm statistics in eval mode if the target batch is tiny. Kornblith et al. (2019) found better ImageNet models usually transfer better.

Domain adaptation theory and domain-adversarial training

Ben-David et al. bound. For hypothesis $h\in\mathcal{H}$,

$$\varepsilon_T(h)\ \le\ \varepsilon_S(h)+\frac12\,d_{\mathcal{H}\Delta\mathcal{H}}(p_S,p_T)+\lambda^\star,$$

where $\varepsilon$ is the error, $d_{\mathcal{H}\Delta\mathcal{H}}$ measures how well a classifier can discriminate source from target inputs, and $\lambda^\star$ is the error of the best joint hypothesis. Target error is small if source error is small, the domains look alike in feature space, and a good joint classifier exists. DANN (Ganin et al. 2016) learns features that are predictive for the task but indistinguishable by a domain classifier using a gradient-reversal layer: forward identity, backward $-\lambda\nabla$, a minimax like GANs (Module 19). Other approaches: MMD/CORAL matching, self-training with pseudo-labels, test-time adaptation.

Catastrophic forgetting and regularisation-based remedies

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 $F_i$ (how important parameter $i$ was for task A):

$$L(\theta)=L_B(\theta)+\frac\lambda2\sum_iF_i\bigl(\theta_i-\theta^\star_{A,i}\bigr)^2 .$$

Alternatives: replay/rehearsal buffers, distillation of the old model (LwF), parameter isolation (progressive nets, adapters per task), and mixing in pretraining-like data.

Adapters and parameter-efficient fine-tuning

Adapters (Houlsby et al. 2019) insert small bottleneck MLPs ($d\to r\to d$ with a residual) in each layer and train only them. Prefix/prompt tuning learn continuous vectors prepended to the input or keys/values; BitFit trains only biases. Benefits: one frozen backbone shared by many tasks, tiny per-task storage, less forgetting.

LoRA and quantised variants

For a frozen weight $W_0\in\mathbb{R}^{d\times k}$, LoRA (Hu et al. 2022) learns a low-rank update:

$$W=W_0+\frac\alpha r\,BA,\qquad B\in\mathbb{R}^{d\times r},\ A\in\mathbb{R}^{r\times k},\ r\ll\min(d,k),$$

with $B$ initialised to 0 (so training starts exactly at the pretrained model) and $A$ Gaussian. Trainable parameters: $r(d+k)$ instead of $dk$. After training, $BA$ can be merged into $W_0$ — zero inference overhead. The justification is the low intrinsic rank of fine-tuning updates (Module 01). QLoRA (Dettmers et al. 2023) backpropagates through a 4-bit-quantised frozen base into LoRA adapters, making 65B-scale fine-tuning feasible on a single large GPU.

Foundation models, few-shot learning and in-context learning

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.

Worked example

LoRA parameters. Square $4096\times4096$ projection ($d=k=4096$), rank $r=8$: LoRA trains $8\cdot(4096+4096)=65{,}536$ parameters versus $16{,}777{,}216$ for the full matrix — $0.39\%$. Applied to the four attention projections in each of 32 layers: $4\cdot32\cdot65{,}536\approx8.4$M trainable parameters (~0.1% of a 7B model).

Domain bound intuition. Source error $5\%$, domain discrepancy term $0.10$, $\lambda^\star=0.02$: target error $\le0.05+0.10+0.02=17\%$. Shrinking the discrepancy (better alignment) tightens the guarantee.

Learning rates. Pretrained backbone fine-tuned at $2\times10^{-5}$, new head at $10^{-3}$ (50× larger): the head is random and must move far; the backbone must not.

Implementation

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

Advanced topics

  • 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.

Pitfalls and best practices

  • 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.

Conceptual questions and answers

Q1. When should you freeze the backbone?

Show answer

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?

Show answer

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.

Show answer

$\varepsilon_T\le\varepsilon_S+\frac12d_{\mathcal{H}\Delta\mathcal{H}}+\lambda^\star$: source error, domain divergence (distinguishability), and the best joint error — small on all three implies good transfer.

Q4. How does gradient reversal align domains?

Show answer

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?

Show answer

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$?

Show answer

So $BA=0$ initially and the adapted model equals the pretrained model at step 0, giving stable training and a good starting point.

Q7. What are the advantages of LoRA over full fine-tuning?

Show answer

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?

Show answer

Compare against a from-scratch (or randomly initialised) baseline trained with equal tuning; if transfer is worse, the source features are harming the target.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally