Simple Algorithm
Machine Learning · Convergence · 26 min

Transfer Learning & Fine-Tuning

Reusing features across tasks, and when it fails.

Pretrained features transfer remarkably often, and fail in ways that theory can partly predict. This lesson proves the classic bound for learning across domains and shows why making features look the same in both domains is not enough, explains why full fine-tuning can damage good features out of distribution, analyzes low-rank adaptation, and derives the gradient of meta-learning.

What you’ll learn

  • State and prove the bound ϵT(h)≤ϵS(h)+12dHΔH(DS,DT)+λ\epsilon_T(h)\le\epsilon_S(h)+\frac12d_{\mathcal H\Delta\mathcal H}(\mathcal D_S,\mathcal D_T)+\lambda, and prove that invariant representations force a large joint error when the label distributions differ.
  • Explain the layer-transfer experiments of Yosinski et al. and the analysis of fine-tuning versus linear probing under distribution shift.
  • Count the parameters of LoRA and adapters, and explain the design choices that make them work.
  • Derive the MAML meta-gradient with its second-order term, and relate multi-task and meta-learning to learning an inductive bias.

What transfers: the experimental picture

Yosinski, Clune, Bengio & Lipson (2014) designed the cleanest test of what transfers. They split ImageNet's 1,000 classes into two halves A and B of 500 classes each (about 645,000 images apiece) and trained a base network on each. Then, for each depth nn, they copied the first nn layers of a base network into a new one and trained the rest on task B, with the copied layers either frozen or fine-tuned. Copying from base B into B ("BnB") isolates optimization effects; copying from A into B ("AnB") adds the effect of the task change.

Two distinct effects emerged. Frozen BnB networks lost accuracy when cut in the middle layers: neurons there are co-adapted, and retraining the upper layers alone could not recover the joint solution, an optimization difficulty. Frozen AnB networks lost more as nn grew, because higher layers are specialized to their original task. With fine-tuning, transferred initializations beat training from scratch, and the generalization boost lingered even after extensive fine-tuning. On a split into man-made and natural classes, transfer was weaker, yet still better than random features.

Transfer is not uniformly positive. Kornblith, Shlens & Le (2019) compared 16 architectures on 12 image datasets and found ImageNet accuracy strongly correlated with transfer accuracy, whether the networks served as fixed feature extractors or were fine-tuned. But common regularizers that slightly improve ImageNet accuracy made the penultimate-layer features much worse for transfer, and on two small fine-grained datasets ImageNet pretraining gave minimal benefit. He, Girshick & Dollár (2019) trained object detectors on COCO from random initialization and matched ImageNet-pretrained ones, given more iterations: pretraining sped up convergence but did not necessarily improve final accuracy. When transfer actively hurts the target task, it is called negative transfer.

Check your understanding

In Yosinski et al.'s experiments, a network trained on task B is cut after a middle layer; the lower layers are frozen and the upper layers are retrained on the same task B. Accuracy drops. Why?

  1. The upper layers overfit, because task B has too few examples
  2. Features of middle layers are specific to a different task
  3. Neurons on the two sides of the cut were co-adapted, and retraining one side alone cannot recover the joint solution
  4. Freezing layers always lowers accuracy
Show the answer

C. Neurons on the two sides of the cut were co-adapted, and retraining one side alone cannot recover the joint solution

Nothing about the task changed, so specialization cannot explain the drop. It is an optimization effect: the original solution relied on interactions across the cut that gradient descent on the upper layers alone fails to rediscover. Fine-tuning the copied layers as well removes the drop.

A theory of learning across domains

Ben-David, Blitzer, Crammer, Kulesza, Pereira & Vaughan (2010) asked when a classifier trained on a source distribution DS\mathcal D_S works on a target DT\mathcal D_T. Write ϵD(h,h′)=Pr⁡x∼D[h(x)≠h′(x)]\epsilon_{\mathcal D}(h,h')=\Pr_{\mathbf x\sim\mathcal D}[h(\mathbf x)\ne h'(\mathbf x)] for the disagreement of two binary classifiers, ϵS(h)\epsilon_S(h) and ϵT(h)\epsilon_T(h) for the errors against each domain's labeling function, and define for a class H\mathcal H

dHΔH(DS,DT)=2sup⁡h,h′∈H∣ϵS(h,h′)−ϵT(h,h′)∣,λ=min⁡h∈H[ϵS(h)+ϵT(h)].d_{\mathcal H\Delta\mathcal H}(\mathcal D_S,\mathcal D_T)=2\sup_{h,h'\in\mathcal H}\big\lvert\epsilon_S(h,h')-\epsilon_T(h,h')\big\rvert,\qquad\lambda=\min_{h\in\mathcal H}\big[\epsilon_S(h)+\epsilon_T(h)\big].

The divergence asks how differently the two domains make pairs of classifiers disagree; λ\lambda is the joint error of the best single hypothesis, attained by some h⋆h^\star.

DerivationProof
  1. ϵT(h)≤ϵT(h⋆)+ϵT(h,h⋆)\epsilon_T(h)\le\epsilon_T(h^\star)+\epsilon_T(h,h^\star)

    Disagreement satisfies the triangle inequality, so go through the ideal hypothesis h⋆h^\star:

  2. ϵT(h,h⋆)≤ϵS(h,h⋆)+∣ϵT(h,h⋆)−ϵS(h,h⋆)∣≤ϵS(h,h⋆)+12dHΔH\epsilon_T(h,h^\star)\le\epsilon_S(h,h^\star)+\big\lvert\epsilon_T(h,h^\star)-\epsilon_S(h,h^\star)\big\rvert\le\epsilon_S(h,h^\star)+\tfrac12d_{\mathcal H\Delta\mathcal H}

    Measure the disagreement of hh and h⋆h^\star on the source instead. The pair (h,h⋆)(h,h^\star) is one of those in the supremum, so switching domains costs at most half the divergence:

  3. ϵT(h)≤ϵS(h)+12dHΔH(DS,DT)+λ\epsilon_T(h)\le\epsilon_S(h)+\tfrac12d_{\mathcal H\Delta\mathcal H}(\mathcal D_S,\mathcal D_T)+\lambda

    A second triangle inequality, now on the source, gives ϵS(h,h⋆)≤ϵS(h)+ϵS(h⋆)\epsilon_S(h,h^\star)\le\epsilon_S(h)+\epsilon_S(h^\star). Substituting both bounds, the two errors of h⋆h^\star add up to ϵS(h⋆)+ϵT(h⋆)=λ\epsilon_S(h^\star)+\epsilon_T(h^\star)=\lambda:

With source error 0.05, dHΔH=0.4d_{\mathcal H\Delta\mathcal H}=0.4 and λ=0.03\lambda=0.03, the bound guarantees target error at most 0.05+0.2+0.03=0.280.05+0.2+0.03=0.28; the divergence term dominates. That suggests learning features z=g(x)\mathbf z=g(\mathbf x) whose source and target distributions match, while keeping the source error small. Ganin et al. (2016) do this by domain-adversarial training: a domain classifier tries to tell the domains apart from z\mathbf z, and its gradient is reversed before it reaches the feature extractor. But the bound has a third term, and matching features can inflate it.

DerivationInvariant features are not enough (Zhao, Tachet des Combes, Zhang & Gordon, 2019)
  1. Binary labels, features Z=g(X)Z=g(X), predictions Y^=h(Z)\hat Y=h(Z). Let dJSd_{\mathrm{JS}} be the Jensen–Shannon distance, the square root of the Jensen–Shannon divergence in bits, a metric bounded by 1. Two facts: processing cannot increase it, dJS(Y^S,Y^T)≤dJS(ZS,ZT)d_{\mathrm{JS}}(\hat Y_S,\hat Y_T)\le d_{\mathrm{JS}}(Z_S,Z_T); and a classifier with error ϵ\epsilon has dJS(Y,Y^)≤ϵd_{\mathrm{JS}}(Y,\hat Y)\le\sqrt\epsilon.

  2. dJS(YS,YT)≤ϵS+dJS(ZS,ZT)+ϵTd_{\mathrm{JS}}(Y_S,Y_T)\le\sqrt{\epsilon_S}+d_{\mathrm{JS}}(Z_S,Z_T)+\sqrt{\epsilon_T}

    The triangle inequality through the predicted labels then links the label distributions of the two domains to the feature distributions and the two errors:

  3. ϵS(h∘g)+ϵT(h∘g) ≥ 12(dJS(YS,YT)−dJS(ZS,ZT))2\epsilon_S(h\circ g)+\epsilon_T(h\circ g)\ \ge\ \tfrac12\big(d_{\mathrm{JS}}(Y_S,Y_T)-d_{\mathrm{JS}}(Z_S,Z_T)\big)^2

    If dJS(YS,YT)≥dJS(ZS,ZT)d_{\mathrm{JS}}(Y_S,Y_T)\ge d_{\mathrm{JS}}(Z_S,Z_T), rearrange and use (a+b)2≤2(a+b)(\sqrt a+\sqrt b)^2\le2(a+b):

  4. With perfectly invariant features the right side is 12DJS(YS,YT)\frac12D_{\mathrm{JS}}(Y_S,Y_T). If 50% of source examples but 10% of target examples are positive, that is about 0.0730.073: no predictor on top of such features can have joint error below 7.3%. When the label proportions differ, aligning the feature distributions misaligns the classes.

Fine-tuning, probing and low-rank adaptation

Fine-tuning every layer usually wins in distribution. Kumar, Raghunathan, Jones, Ma & Liang (2022) found that it can lose out of distribution: on 10 distribution-shift benchmarks, full fine-tuning averaged about 2% higher accuracy than a linear probe in distribution but about 7% lower out of distribution. Their explanation fits in a two-layer linear model.

DerivationWhy fine-tuning distorts features (a two-layer linear model)
  1. ∇BL=∑i=1n(v⊤Bxi−yi) v xi⊤\nabla_BL=\sum_{i=1}^n\big(\mathbf v^\top B\mathbf x_i-y_i\big)\,\mathbf v\,\mathbf x_i^\top

    Let f(x)=v⊤Bxf(\mathbf x)=\mathbf v^\top B\mathbf x with pretrained features B0∈Rk×dB_0\in\R^{k\times d} and a new head v\mathbf v. Fine-tune both by gradient descent on the squared loss L=12∑i(v⊤Bxi−yi)2L=\frac12\sum_i(\mathbf v^\top B\mathbf x_i-y_i)^2, over training inputs that span a subspace S=span⁡{x1,…,xn}S=\operatorname{span}\{\mathbf x_1,\dots,\mathbf x_n\} smaller than Rd\R^d. The gradient with respect to BB is a sum of outer products with the training inputs:

  2. (Bt−B0) u=0for all u⊥S(B_t-B_0)\,\mathbf u=\mathbf 0\qquad\text{for all }\mathbf u\perp S

    Every row of every update lies in SS, so the features change only on SS: for any direction u⊥S\mathbf u\perp S, Btu=B0uB_t\mathbf u=B_0\mathbf u at every step.

  3. An out-of-distribution input has a component x⊥\mathbf x_\perp outside SS. Its features B0x⊥B_0\mathbf x_\perp are the old ones, but they are now read by a head vt\mathbf v_t that was co-trained with the changed features on SS, so the two halves of the prediction no longer fit together. Starting from a random head makes this worse: while the head is still wrong the residuals are large, so BB moves a lot on SS. Kumar et al. prove that in this setting fine-tuning from a fixed or random head has high out-of-distribution error, while a linear probe keeps B0B_0 intact.

  4. LP-FT: first fit the head with the features frozen, then fine-tune everything. The head starts near its optimum, the residuals v⊤Bxi−yi\mathbf v^\top B\mathbf x_i-y_i are small, and the features barely move. Empirically LP-FT beat full fine-tuning by about 1% in distribution and 10% out of distribution on their benchmarks.

Parameter-efficient fine-tuning changes few parameters by design. Adapters (Houlsby et al., 2019) insert small bottleneck layers into each block of a frozen network, initialized near the identity so training starts from the pretrained function; on the GLUE benchmark they came within 0.4% of full fine-tuning (80.0 against 80.4) while adding 3.6% parameters per task. LoRA (Hu et al., 2022) keeps a pretrained weight matrix W0∈Rd×kW_0\in\R^{d\times k} fixed and trains only a low-rank correction to it:

W=W0+BA,B∈Rd×r,A∈Rr×k,r≪min⁡(d,k).W=W_0+BA,\qquad B\in\R^{d\times r},\quad A\in\R^{r\times k},\quad r\ll\min(d,k).

AA is initialized randomly and BB at zero, so at the first step the adapted network computes the same function as the pretrained one. Once training ends, BABA can be merged into W0W_0, leaving inference as cheap as before. Against full fine-tuning of GPT-3 (175 billion parameters) with Adam, Hu et al. cut the trainable parameters by a factor of about 10,000 and the GPU memory by a factor of 3, with quality on par or better on their benchmarks.

Predict before you look

LoRA with rank r=4r=4 adapts a 1,024×1,0241{,}024\times1{,}024 weight matrix. What percentage of that matrix's parameter count does it train?

Show the answer

0.78 %

r(d+k)=4×2,048=8,192r(d+k)=4\times2{,}048=8{,}192 parameters against dk=1,048,576dk=1{,}048{,}576: about 0.78%0.78\%. Every output change BAxBA\mathbf x is a combination of the 4 columns of BB, so the correction can push the layer's outputs only within a 4-dimensional subspace.

Why would such tiny updates suffice? Aghajanyan, Gupta & Zettlemoyer (2021) measured the intrinsic dimension of fine-tuning: optimizing only 200 parameters, randomly projected into the full parameter space, brought a pretrained RoBERTa model to 90% of its full fine-tuning performance on the MRPC paraphrase task, and larger pretrained models tended to have lower intrinsic dimension. Pretraining seems to leave models where a low-dimensional adjustment is enough.

Many tasks: multi-task learning and meta-learning

Caruana (1997) trained related tasks together with shared hidden layers, and argued that what is learned for each task acts as an inductive bias for the others. Meta-learning pushes the idea further: learn, from many tasks, a starting point from which a new task can be learned from very few examples. Model-agnostic meta-learning (MAML; Finn, Abbeel & Levine, 2017) does this by differentiating through the adaptation itself.

DerivationThe MAML meta-gradient
  1. θi′=θ−α ∇Litr(θ)\boldsymbol\theta_i'=\boldsymbol\theta-\alpha\,\nabla L_i^{\mathrm{tr}}(\boldsymbol\theta)

    For each task ii, one inner gradient step on its training loss adapts the shared initialization θ\boldsymbol\theta with inner step size α\alpha:

  2. min⁡θ ∑iLival(θi′(θ))\min_{\boldsymbol\theta}\ \sum_iL_i^{\mathrm{val}}\big(\boldsymbol\theta_i'(\boldsymbol\theta)\big)

    The meta-objective scores each adapted model on held-out data from its task, and is minimized over the initialization:

  3. ∇θLival(θi′)=(I−α ∇2Litr(θ)) ∇Lival(θi′)\nabla_{\boldsymbol\theta}L_i^{\mathrm{val}}(\boldsymbol\theta_i')=\big(I-\alpha\,\nabla^2L_i^{\mathrm{tr}}(\boldsymbol\theta)\big)\,\nabla L_i^{\mathrm{val}}(\boldsymbol\theta_i')

    By the chain rule, the Jacobian of the inner step is I−α∇2LitrI-\alpha\nabla^2L_i^{\mathrm{tr}}, so the meta-gradient involves the Hessian of the training loss, applied to a vector:

  4. The Hessian–vector product costs about one extra backward pass. First-order MAML drops it and uses ∇Lival(θi′)\nabla L_i^{\mathrm{val}}(\boldsymbol\theta_i') alone, which often works almost as well.

Does MAML learn to adapt quickly, or does it learn good features? Raghu, Raghu, Bengio & Vinyals (2020) found feature reuse dominant: restricting the inner loop to the final layer (their ANIL algorithm) matched MAML on standard few-shot image classification and reinforcement-learning benchmarks, and test performance was determined by the quality of the learned features. Meta-learning, on this evidence, is largely representation learning across tasks.

Check your understanding

Why does the exact MAML gradient contain a Hessian, and what does first-order MAML do about it?

  1. The meta-loss is evaluated at parameters that themselves depend on θ\boldsymbol\theta through a gradient step, whose Jacobian is I−α∇2LtrI-\alpha\nabla^2L^{\mathrm{tr}}; first-order MAML replaces it by the identity
  2. MAML uses Newton's method in the inner loop; first-order MAML switches to gradient descent
  3. The Hessian comes from the validation loss; first-order MAML removes the validation set
  4. The Hessian regularizes the meta-objective; first-order MAML replaces it by weight decay
Show the answer

A. The meta-loss is evaluated at parameters that themselves depend on θ\boldsymbol\theta through a gradient step, whose Jacobian is I−α∇2LtrI-\alpha\nabla^2L^{\mathrm{tr}}; first-order MAML replaces it by the identity

θ′=θ−α∇Ltr(θ)\boldsymbol\theta'=\boldsymbol\theta-\alpha\nabla L^{\mathrm{tr}}(\boldsymbol\theta), so ∂θ′/∂θ=I−α∇2Ltr(θ)\partial\boldsymbol\theta'/\partial\boldsymbol\theta=I-\alpha\nabla^2L^{\mathrm{tr}}(\boldsymbol\theta). Dropping the second term saves a Hessian–vector product per task and keeps the gradient evaluated at the adapted parameters.

Key takeaways

  • Lower layers transfer broadly and higher layers are task-specific; cutting co-adapted middle layers hurts optimization; fine-tuned transferred weights give a lasting generalization boost, but transfer can also be neutral or negative.
  • ϵT(h)≤ϵS(h)+12dHΔH+λ\epsilon_T(h)\le\epsilon_S(h)+\frac12d_{\mathcal H\Delta\mathcal H}+\lambda follows from two triangle inequalities. When label proportions differ, perfectly invariant features force ϵS+ϵT≥12DJS(YS,YT)\epsilon_S+\epsilon_T\ge\frac12D_{\mathrm{JS}}(Y_S,Y_T).
  • Fine-tuning changes features only on the span of the training inputs, which can distort them out of distribution; probing the head first (LP-FT) limits the damage. LoRA trains a rank-rr correction with r(d+k)r(d+k) parameters, initialized at zero so that training starts from the pretrained function.
  • MAML's meta-gradient is (I−α∇2Ltr)∇Lval(θ′)(I-\alpha\nabla^2L^{\mathrm{tr}})\nabla L^{\mathrm{val}}(\boldsymbol\theta'); first-order variants drop the Hessian, and much of MAML's success comes from reusable features.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the bound ϵT(h)≤ϵS(h)+12dHΔH+λ\epsilon_T(h)\le\epsilon_S(h)+\frac12d_{\mathcal H\Delta\mathcal H}+\lambda, what does λ\lambda measure, and why can't adaptation fix it?

  1. The VC dimension of H\mathcal H; it is fixed by the architecture
  2. The divergence between the unlabeled input distributions
  3. The source error of the trained classifier
  4. The joint error of the best single hypothesis on both domains; if it is large, no h∈Hh\in\mathcal H works on both, and unlabeled target data cannot reveal that
Show the answer

D. The joint error of the best single hypothesis on both domains; if it is large, no h∈Hh\in\mathcal H works on both, and unlabeled target data cannot reveal that

λ=min⁡h[ϵS(h)+ϵT(h)]\lambda=\min_h[\epsilon_S(h)+\epsilon_T(h)] involves target labels, which unsupervised adaptation never sees. It is why invariant features can fail: aligning distributions can raise λ\lambda in feature space.

Question 2

According to Kumar et al. (2022), why does training the head first (LP-FT) protect out-of-distribution accuracy better than fine-tuning all layers with a randomly initialized head?

  1. It uses a larger learning rate for the features
  2. It freezes the features permanently
  3. With a near-optimal head the residuals are small, so the features move little, and pretrained features of directions unseen in training stay consistent with the head
  4. It trains on out-of-distribution data during the probing stage
Show the answer

C. With a near-optimal head the residuals are small, so the features move little, and pretrained features of directions unseen in training stay consistent with the head

Feature updates are proportional to the residuals and confined to the span of the training inputs. A random head produces large residuals and distorts the features on that span, mismatching them with the untouched directions; a probed head avoids most of that distortion.

Question 3

In LoRA, the update is BABA with B∈Rd×rB\in\R^{d\times r} initialized to zero and AA initialized randomly. Why zero for BB?

  1. So that BA=0BA=0 at the start and the adapted network initially computes the pretrained function
  2. To make the update full-rank
  3. So that AA receives no gradient
  4. To keep the number of trainable parameters small
Show the answer

A. So that BA=0BA=0 at the start and the adapted network initially computes the pretrained function

With B=0B=0 the adapted layer computes exactly W0xW_0\mathbf x initially. The gradient with respect to BB is nonzero (it involves AxA\mathbf x), so training moves away from the pretrained function smoothly.

Question 4

In a binary task, 50% of source examples are positive but only 10% of target examples. You learn features whose distribution is identical in both domains. What does Zhao et al.'s bound imply?

  1. Target error equals source error
  2. The sum of source and target errors of any classifier on those features is at least about 0.07
  3. Target error can be made zero by training longer
  4. Nothing, because the bound applies only to linear classifiers
Show the answer

B. The sum of source and target errors of any classifier on those features is at least about 0.07

With dJS(ZS,ZT)=0d_{\mathrm{JS}}(Z_S,Z_T)=0 the bound gives ϵS+ϵT≥12DJS(YS,YT)\epsilon_S+\epsilon_T\ge\frac12D_{\mathrm{JS}}(Y_S,Y_T), about 12×0.147≈0.073\frac12\times0.147\approx0.073 for label rates of 0.5 and 0.1. Identical feature distributions cannot carry different label proportions without errors.

Further reading

  • S. Ben-David, J. Blitzer, K. Crammer, A. Kulesza, F. Pereira & J. W. Vaughan, "A theory of learning from different domains," Machine Learning 79(1–2), 151–175 (2010).
  • J. Yosinski, J. Clune, Y. Bengio & H. Lipson, "How transferable are features in deep neural networks?," NeurIPS (2014).
  • A. Kumar, A. Raghunathan, R. Jones, T. Ma & P. Liang, "Fine-tuning can distort pretrained features and underperform out-of-distribution," ICLR (2022).
  • E. J. Hu, Y. Shen, P. Wallis, Z. Allen-Zhu, Y. Li, S. Wang, L. Wang & W. Chen, "LoRA: low-rank adaptation of large language models," ICLR (2022).
  • C. Finn, P. Abbeel & S. Levine, "Model-agnostic meta-learning for fast adaptation of deep networks," ICML (2017).