Frozen and Partial Fine-Tuning
Feature extraction freezes the whole backbone and trains only a head; full fine-tuning trains everything. Between the two lies a dial: freeze the lower layers, train the upper ones. Partial fine-tuning chooses how far down the training reaches. It costs less memory and compute than full fine-tuning, overfits less on small data, and keeps the general-purpose lower layers intact, while still letting the model adapt the layers that are most specific to the old task.
Which layers to unfreeze
The layers of a pretrained network go from general to specific. In an image model the first layers detect edges and colours, the last ones whole objects of the training classes; in a language model the lower layers encode word pieces and syntax, the upper ones task-specific meaning. That gives a rule of thumb with two cases:
- Same kind of input, new task (photos to other photos, English reviews to English support tickets): the lower layers are already right. Unfreeze from the top.
- New kind of input (photos to X-rays, a camera that moved, a new language or jargon): the lower layers see a changed input, so they need to adapt too. Unfreeze deeper, or everything.
The more labels you have, the further down you can afford to train without overfitting.
Definitions
Split the parameters into a frozen part and a trained part, . Partial fine-tuning minimises the target loss over only, starting from the pretrained values:
Gradients are still computed through the frozen layers above the trained ones, but not for them, and nothing below the lowest trained layer needs a backward pass at all. That is where the savings come from: no gradients and no optimiser state for , and a shorter backward pass.
Two refinements soften the hard frozen/trained boundary:
- Layer-wise learning rates (discriminative fine-tuning): layer of gets with a decay between about 0.3 and 0.95, so the head moves fastest and the bottom barely moves. A frozen layer is the limit .
- Gradual unfreezing (ULMFiT, Howard and Ruder, 2018): train the head first, then unfreeze one more layer from the top every epoch or so. Each layer starts training only once the layers above it are sensible, so large, noisy gradients from a random head never reach the bottom.
From scratch: where should training reach?
The digits again. A network with two hidden layers (64 and 32 ReLU units) is pretrained on one half of the images to recognise the digit. Two target problems on the other half, each with only 100 labelled images (the rest, 799 images, is the test set), averaged over 3 random draws of the labels:
- new task, same input: is the digit prime (2, 3, 5, 7)?
- new input, same task: which digit, but on images shifted one pixel to the right, as if the camera moved.
Five plans: train only a new head; layer 2 and the head; all layers; all layers with layer-wise learning rates (0.1, 0.3, 1 times the base rate from bottom to top); and the same architecture from random weights. Every plan uses Adam for 300 full-batch steps at a base rate of 0.003 (a fixed budget, not tuned per plan, which a real project would do on a validation set).
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, digit_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
source = MLPClassifier(hidden_layer_sizes=(64, 32), max_iter=500, random_state=0).fit(X_src, y_src)
pre = [source.coefs_[0], source.intercepts_[0], source.coefs_[1], source.intercepts_[1]] # layer 1, layer 2
def forward(P, A):
h1 = np.maximum(0, A @ P[0] + P[1])
h2 = np.maximum(0, h1 @ P[2] + P[3])
return h1, h2, h2 @ P[4] + P[5]
def finetune(P, lr_mult, Xl, yl, lr=0.003, steps=300):
"""Adam on all six arrays; lr_mult = (layer 1, layer 2, head), 0 means frozen."""
m = [0] * 6; v = [0] * 6
for t in range(1, steps + 1):
h1, h2, z = forward(P, Xl)
p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(yl)), yl] -= 1; g /= len(yl)
g2 = g @ P[4].T * (h2 > 0); g1 = g2 @ P[2].T * (h1 > 0)
G = [Xl.T @ g1, g1.sum(0), h1.T @ g2, g2.sum(0), h2.T @ g, g.sum(0)]
for i in range(6):
k = lr_mult[i // 2]
if k == 0:
continue # frozen: no update, no optimiser state needed
m[i] = 0.9 * m[i] + 0.1 * G[i]; v[i] = 0.999 * v[i] + 0.001 * G[i] ** 2
P[i] = P[i] - k * lr * (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.999 ** t)) + 1e-8)
return P
plans = {"head only": (0, 0, 1), "layer 2 + head": (0, 1, 1), "all layers": (1, 1, 1),
"all, layer-wise lr": (0.1, 0.3, 1), "from scratch": None}
targets = {"new task (prime?)": (X_tgt, np.isin(digit_tgt, [2, 3, 5, 7]).astype(int)),
"new input (shifted)": (np.roll(X_tgt.reshape(-1, 8, 8), 1, axis=2).reshape(-1, 64), digit_tgt)}
sizes = [p.size for p in pre]
print(f"numbers per part: layer 1 {sizes[0] + sizes[1]}, layer 2 {sizes[2] + sizes[3]}, head 66 (prime) or 330 (digit)")
print(f"{'plan':20s}" + "".join(f"{t:>22s}" for t in targets))
results = {}
for tname, (Xt, yt) in targets.items():
k = yt.max() + 1 # number of classes
for seed in range(3):
rng = np.random.default_rng(seed)
lab = np.concatenate([rng.choice(np.where(yt == c)[0], 100 // k, replace=False) for c in range(k)])
test = np.setdiff1d(np.arange(len(yt)), lab)
for name, mult in plans.items():
if mult is None: # same architecture, random weights
P = [rng.normal(0, np.sqrt(2 / 64), (64, 64)), np.zeros(64),
rng.normal(0, np.sqrt(2 / 64), (64, 32)), np.zeros(32)]
mult = (1, 1, 1)
else:
P = [p.copy() for p in pre]
P += [rng.normal(0, 0.1, (32, k)), np.zeros(k)] # a new head
P = finetune(P, mult, Xt[lab], yt[lab])
acc = (forward(P, Xt[test])[2].argmax(1) == yt[test]).mean()
results.setdefault((name, tname), []).append(acc)
for name in plans:
print(f"{name:20s}" + "".join(f"{np.mean(results[(name, t)]):22.3f}" for t in targets))numbers per part: layer 1 4160, layer 2 2080, head 66 (prime) or 330 (digit)
plan new task (prime?) new input (shifted)
head only 0.929 0.845
layer 2 + head 0.945 0.869
all layers 0.937 0.899
all, layer-wise lr 0.941 0.882
from scratch 0.918 0.895
The two columns follow the rule of thumb. For the new task on the same input, training layer 2 with the head is best (0.945); training all layers is slightly worse (0.937), because with 100 labels the extra 4,160 first-layer numbers mostly add variance, and every pretrained plan beats training from scratch (0.918). For the shifted input the order flips: each layer you unfreeze helps, from 0.845 (head only) through 0.869 (layer 2) to 0.899 (all layers), because the first layer is the one that looks at the moved pixels. Layer-wise learning rates land between the two extremes in both columns (0.941 and 0.882): they are a compromise, and here the shifted input wanted the first layer to move faster than 0.1 times the base rate allowed.
Note the last row of the second column: from scratch reaches 0.895, as good as fine-tuning everything. After the shift this small pretrained network has little left to give, which is a useful warning. Always keep the scratch baseline. Each test set has 799 images, so 0.004 is about three images and the differences of 0.01 or more are the ones worth reading.
With PyTorch: freezing a pretrained BERT
The same plans on a real pretrained transformer, google/bert_uncased_L-2_H-128_A-2 (2 encoder layers, hidden size 128, 4.4 million parameters), for movie-review sentiment on the rotten_tomatoes data of the sentence-embeddings lesson. A fixed random 2,000 training and 500 test sentences, cut or padded to 48 word pieces, 3 epochs of AdamW in batches of 32. Freezing is one line per parameter, p.requires_grad = False, chosen here by the parameter's name. The new head gets a learning rate of when it trains alone and the unfrozen encoder , the usual factor of 10 between a random head and pretrained weights.
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers.utils import logging
logging.set_verbosity_error() # hide the "classifier newly initialised" load report
name = "google/bert_uncased_L-2_H-128_A-2"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
test = ds["test"].shuffle(seed=0).select(range(500))
tok = AutoTokenizer.from_pretrained(name)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_tr, X_te = enc(train), enc(test)
y_tr, y_te = torch.tensor(train["label"]), torch.tensor(test["label"])
def fit_and_score(model, lr, epochs=3):
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
g = torch.Generator().manual_seed(0)
for _ in range(epochs):
model.train()
for idx in torch.randperm(len(y_tr), generator=g).split(32):
out = model(input_ids=X_tr["input_ids"][idx], attention_mask=X_tr["attention_mask"][idx], labels=y_tr[idx])
opt.zero_grad(); out.loss.backward(); opt.step()
model.eval()
with torch.no_grad():
logits = model(input_ids=X_te["input_ids"], attention_mask=X_te["attention_mask"]).logits
return (logits.argmax(1) == y_te).float().mean().item()
plans = {"head only": (lambda n: n.startswith("classifier"), 1e-3),
"top layer + head": (lambda n: n.startswith(("classifier", "bert.pooler", "bert.encoder.layer.1.")), 1e-4),
"all layers": (lambda n: True, 1e-4)}
for plan, (is_trained, lr) in plans.items():
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
for n, p in model.named_parameters():
p.requires_grad = is_trained(n) # freeze everything the plan does not train
n_train = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"{plan:17s} trainable {n_train:>9,} test accuracy {fit_and_score(model, lr):.3f}")
# layer-wise learning rates are optimiser parameter groups: one group per depth
base_lr, decay = 1e-4, 0.5
groups = [("classifier + pooler", ("classifier", "bert.pooler"), base_lr),
("encoder layer 1", ("bert.encoder.layer.1.",), base_lr * decay),
("encoder layer 0", ("bert.encoder.layer.0.",), base_lr * decay ** 2),
("embeddings", ("bert.embeddings",), base_lr * decay ** 3)]
param_groups = [{"params": [p for n, p in model.named_parameters() if n.startswith(prefixes)], "lr": lr}
for _, prefixes, lr in groups]
opt = torch.optim.AdamW(param_groups)
for (label, _, _), g in zip(groups, opt.param_groups):
print(f" group {label:20s} lr {g['lr']:.2e} parameters {sum(p.numel() for p in g['params']):>9,}")head only trainable 258 test accuracy 0.574
top layer + head trainable 215,042 test accuracy 0.654
all layers trainable 4,386,178 test accuracy 0.742
group classifier + pooler lr 1.00e-04 parameters 16,770
group encoder layer 1 lr 5.00e-05 parameters 198,272
group encoder layer 0 lr 2.50e-05 parameters 198,272
group embeddings lr 1.25e-05 parameters 3,972,864
Here the order is monotone: 0.574 with a head on the frozen encoder, 0.654 with the top layer unfrozen, 0.742 with everything trained. A 2-layer, 128-wide BERT is a weak feature extractor, and with 2,000 labelled sentences there is enough data to adapt all of it; with a large pretrained model and a task close to its pretraining the frozen and partial plans come much closer to full fine-tuning (compare the frozen sentence embeddings of the sentence-embeddings lesson, 0.728 with 1,000 labels).
The parameter groups show where this small model's weights are: 3.97 of its 4.39 million parameters are the word-piece embeddings (30,522 tokens x 128), and each encoder layer has only 198,272. In large language models the proportions reverse, and the transformer layers hold almost everything. The decay of 0.5 per level gives the embeddings an eighth of the head's learning rate; passing param_groups to the optimiser is all that layer-wise learning rates take.
Advantages and limits
| Advantages | Limits |
|---|---|
| Less memory: no gradients or optimiser state for frozen layers, and a shorter backward pass | Which layers to unfreeze is one more hyperparameter, and depends on the data |
| Less overfitting on small data than full fine-tuning | Still one full copy of the model per task (unlike LoRA adapters) |
| Lower layers stay general, which limits forgetting | When the input itself changed, frozen lower layers hold the model back |
Trivial to implement: requires_grad = False |
Saves less than parameter-efficient methods on very large models: the upper layers are large too |
Pitfalls
- Batch-norm statistics in frozen layers.
requires_grad = Falsedoes not stop a batch-norm layer from updating its running mean and variance intrain()mode. Put frozen CNN stages ineval()(the ResNet lesson shows the damage). Transformers use layer norm, which has no running statistics. - Dropout in frozen layers. In
train()mode dropout is still active in frozen layers. That is usually fine (it regularises), but it means a frozen layer's output is not a fixed feature during training, so precomputing it once (feature extraction) is no longer equivalent. - Building the optimiser before freezing or unfreezing. The optimiser updates only the tensors it was given. After changing
requires_grad, build a new optimiser or add a parameter group. - Forgetting the pooler or the head. In BERT the classification head reads the
pooleroutput; freezing the pooler while training the head is a legitimate choice, but do it on purpose. - Choosing the plan on the test set. Comparing five plans on the test set, as the examples do for brevity, is a choice made with test data. In a real project compare them on a validation split or by cross-validation.
Practice
- In the NumPy example, which plan would you expect to win if the target were 1,000 labelled shifted images instead of 100? Why?
- A colleague freezes a ResNet's first three stages with
requires_grad = False, trains for 10 epochs, and finds the frozen layers' outputs changed. What changed them? - Write the layer-wise learning rates for a 12-layer BERT with base rate and decay 0.9: what is the rate of layer 1 (the lowest)?
Answers
- With 10 times more labels, overfitting is less of a risk, so training all layers (or even from scratch) gains: the shifted input needs the first layer to change, and the data can now support it. The gap between "head only" and "all layers" would grow.
- The batch-norm running statistics: in
train()mode they are updated from every batch even though the weights are frozen. Put the frozen stages ineval()mode. - .
Test yourself
Your model was pretrained on photos and the new task uses infrared images of the same scenes. Which layers most need to adapt?
- Only the head
- The lower layers too, because the input itself changed
- None
- Only the pooler
Why does freezing the lower layers save memory during training?
- The frozen weights are deleted
- No gradients or optimiser state are stored for them, and the backward pass can stop above them
- Frozen layers are quantised
- The forward pass skips them
What is gradual unfreezing?
- Raising the learning rate over time
- Training the head first, then unfreezing one more layer from the top at a time
- Unfreezing random layers each epoch
- Freezing layers after they converge