QuiddityML

By · 13 November 2026 · 10 min read

Fine-tuning vs transfer learning explained

Why a pretrained model helps on a task it never saw, how freezing layers works in PyTorch, and when fine-tuning stops being enough.

Fine-tuning is continuing to train a pretrained model on your own data, starting from the weights it already learned. Transfer learning is the broader idea of reusing what a model learned on one task or domain to help with a different one. Fine-tuning is a technique, and transfer learning is the idea it relies on. This is why a project with a few thousand labeled examples can start from a pretrained language model instead of training one from scratch.

A loaded model rarely fits your task as is

You can download a pretrained checkpoint, one saved set of trained weights, and it will run and produce real outputs. A checkpoint trained on someone else's data still rarely matches your task exactly. Your task might use a different set of labels or a narrower vocabulary, such as medical or legal terms. It might need a tone the model never saw, or be a task the checkpoint was never trained for at all.

One fallback would be to collect a huge dataset and train a new model from random weights. That throws away what the checkpoint already learned.

It doesn't quite fit. What you loaded, a pretrained checkpoint, runs and produces real outputs. What you actually need differs: a different label set, a narrower domain vocabulary, a task it was never trained for. The question at the bottom is whether to start over from random weights, and a pretrained checkpoint rarely matches a new task out of the box.

Fine-tuning keeps training the same model

A pretrained language model's weights already encode grammar and word meaning, and a large enough checkpoint can already do real tasks. Fine-tuning keeps all of that by continuing training from the loaded weights, on your data.

Fine-tuning adapts a pretrained model. A pretrained checkpoint goes through continue training on your data and becomes a fine-tuned checkpoint, which keeps grammar, word meaning, syntax and task ability. Fine-tuning starts from what the checkpoint already knows, instead of from nothing.

Fine-tuning is the same algorithm as training a model the first time. A forward pass makes a prediction and a loss function scores how wrong it is. Backpropagation computes the gradient of the loss for every weight, and an optimizer step updates the weights. With plain gradient descent the update for the weights $\theta$ is:

$$\theta \leftarrow \theta - \eta \nabla_\theta L$$

$\eta$ is the learning rate, a small number that sets the step size, and $\nabla_\theta L$ is the gradient of the loss $L$. For example, a weight at 0.50 with a gradient of 2.0 and a learning rate of 0.01 moves to $0.50 - 0.01 \times 2.0 = 0.48$. That rule is identical whether $\theta$ started random or pretrained. The only thing fine-tuning changes is the value of $\theta$ before the loop runs.

Fine-tuning runs the usual training loop: forward pass, loss, backward pass, optimizer step. Training from scratch starts with theta random, and fine-tuning starts with theta pretrained. The loop is identical, only the starting weights differ.

Why the starting point helps

Two runs of the same loop can look very different because of where the weights start. Training from scratch starts at random weights that know nothing about language. Reaching good performance usually takes a very large dataset and a long run, because the model has to learn grammar and word meaning before it can learn the task on top.

Fine-tuning starts at weights that already encode that structure. The model mostly has to learn the gap between what it knows and what the new task needs, so it usually reaches good performance with far less data and training time.

Starting point changes the curve. Loss against training steps for two runs. Fine-tuning starts lower and reaches a low loss sooner. Training from scratch starts high and takes longer to get there.

The learning rate usually drops

Pretraining from scratch can use a fairly large learning rate, because every weight starts as noise and there is nothing useful to protect yet. Fine-tuning usually uses a much smaller one. The pretrained weights hold useful structure, and large updates can overwrite it before the model adapts to the new task. Losing pretrained knowledge to large updates like that is called catastrophic forgetting.

Why the learning rate usually drops. Training from scratch uses a large learning rate, since there is nothing useful yet to protect. Fine-tuning uses a small learning rate, which protects useful pretrained structure. If the rate stays large, useful pretrained structure gets overwritten before the model adapts. Overwriting it like this is called catastrophic forgetting.

Full fine-tuning vs freezing

Fine-tuning does not have to update every weight. There are two common ways to do it:

Full fine-tuning vs freezing. In full fine-tuning layers 1, 2 and 3 are all updated, so every weight changes. In freezing layers 1 and 2 are frozen and only a new head is updated, so most weights stay fixed. Full fine-tuning trades compute and forgetting risk for flexibility, and freezing trades flexibility for safety and cost.

A common pattern freezes the early layers and trains the later ones. Early layers tend to learn general structure, such as broad syntax and word meaning in a pretrained language model. Later layers tend to specialize toward the exact task the model was pretrained on, so they usually gain the most from training on a new task.

In PyTorch, every weight tensor carries a requires_grad flag, which is True by default. Setting it to False leaves that tensor out of the gradient computation, so the optimizer never changes it and it stays exactly as pretraining left it. Freezing at the code level means setting that flag.

Choosing which weights move. A parameter tensor has requires_grad = True by default. Setting requires_grad = False freezes it, and the optimizer never touches it. Early layers usually carry general structure, and later layers usually specialize.

Freezing the first layer of a small MLP

Take a small network of three linear layers in nn.Sequential and freeze the first one. The code below then trains it for 50 steps on random data and measures how far each layer's weights moved:

1import torch
2import torch.nn as nn
3 
4torch.manual_seed(0)
5model = nn.Sequential(
6    nn.Linear(20, 64), nn.ReLU(),
7    nn.Linear(64, 64), nn.ReLU(),
8    nn.Linear(64, 10),
9)
10for param in model[0].parameters():
11    param.requires_grad = False
12 
13trainable = filter(lambda p: p.requires_grad, model.parameters())
14optimizer = torch.optim.Adam(trainable, lr=1e-4)
15 
16n_train = sum(p.numel() for p in model.parameters() if p.requires_grad)
17n_total = sum(p.numel() for p in model.parameters())
18print(n_train, "of", n_total, "weights train")
19 
20layers = {"linear 1": model[0], "linear 2": model[2], "linear 3": model[4]}
21before = {k: layer.weight.detach().clone() for k, layer in layers.items()}
22 
23x = torch.randn(256, 20)
24y = torch.randint(0, 10, (256,))
25for step in range(50):
26    loss = nn.functional.cross_entropy(model(x), y)
27    optimizer.zero_grad()
28    loss.backward()
29    optimizer.step()
30 
31for k, layer in layers.items():
32    change = (layer.weight - before[k]).abs().mean().item()
33    print(f"{k}: {change:.6f}")

It prints:

14810 of 6154 weights train
2linear 1: 0.000000
3linear 2: 0.004526
4linear 3: 0.004776

model[0] is the first linear layer, and .parameters() gives its weight and bias tensors. The counts check out by hand. The first layer has $20 \times 64 + 64 = 1344$ weights and is frozen. The second has $64 \times 64 + 64 = 4160$ and the third $64 \times 10 + 10 = 650$, which adds up to the 4810 that train. After 50 steps the first layer has moved by exactly 0, and the other two have moved.

filter keeps only the items for which a function returns True. Here the function is lambda p: p.requires_grad, a one-line function that takes a parameter p and returns its flag. Handing the optimizer only those parameters makes it clear which weights can change.

Freezing a small MLP. Linear 1 is frozen, and linear 2 and linear 3 are trainable. The code sets model[0]: requires_grad = False. The optimizer only receives parameters where requires_grad is True.

The picture below sketches what that measurement looks like on a larger model with an embedding layer, three layers and a head. Without freezing, every layer moves, the most near the output and less near the input. With the early layers frozen, those layers show exactly zero change and all of the movement is in the later layers and the head.

What changes with and without freezing. Weight change per layer for embedding, layer 1, layer 2, layer 3 and head. With full fine-tuning every bar is above zero, growing toward the head. With a frozen backbone, embedding, layer 1 and layer 2 sit at zero, while layer 3 and the head still move. Frozen layers show zero change, the rest still moves.

Freezing GPT-2's early blocks

The same pattern works on a pretrained GPT-2 at a larger scale. GPT2LMHeadModel keeps its 12 transformer blocks in the list model.transformer.h. This freezes every block except the last two:

1from transformers import GPT2LMHeadModel
2 
3model = GPT2LMHeadModel.from_pretrained("gpt2")
4for block in model.transformer.h[:-2]:
5    for param in block.parameters():
6        param.requires_grad = False
7 
8n_train = sum(p.numel() for p in model.parameters() if p.requires_grad)
9n_total = sum(p.numel() for p in model.parameters())
10print(f"{n_train:,} of {n_total:,} weights train ({n_train / n_total:.0%})")
11print(f"{model.transformer.wte.weight.numel():,} in the token embedding table")

It prints:

153,561,088 of 124,439,808 weights train (43%)
238,597,376 in the token embedding table

h[:-2] selects every block except the last two, so blocks 0 to 9 are frozen. The loop never touches the token and position embeddings, the final LayerNorm or the language-modeling head, so those keep training along with blocks 10 and 11. That is why 43% of the weights still train, even with 10 of 12 blocks frozen. The token embedding table alone, 50,257 rows of 768 numbers, holds 38.6 million of them.

Freezing GPT-2's early blocks. Embeddings are trainable, block 0, block 1 and more blocks are frozen, and block 10 and block 11 are trainable. model.transformer.h[:-2] selects every block except the last two.

Adding a task head

Fine-tuning often adds a part that was not in the checkpoint at all, a task-specific head. A pretrained encoder such as BERT was trained on a general objective, predicting hidden tokens, and not on your labels. A small new layer, often one linear layer, goes on top of the encoder's output and maps it to what the task needs, such as class scores. That new head starts from random weights even though the rest of the model does not.

Adding a task-specific head. A pretrained encoder, trained with a small learning rate, outputs H, the last hidden state with one vector per token. Below a dashed line, h_cls = H[:, 0, :] goes into a new classification head that starts random and trains with a normal learning rate. The new head starts random even when the rest of the checkpoint does not.

In code that means wrapping the encoder in a small class of your own. AutoModel.from_pretrained loads the pretrained BERT encoder, and a new nn.Linear becomes the head. The code then freezes the encoder so only the head trains:

1import torch
2import torch.nn as nn
3from transformers import AutoModel, AutoTokenizer
4 
5class BertClassifier(nn.Module):
6    def __init__(self, num_labels):
7        super().__init__()
8        self.bert = AutoModel.from_pretrained("bert-base-uncased")
9        self.head = nn.Linear(768, num_labels)
10 
11    def forward(self, input_ids, attention_mask):
12        H = self.bert(input_ids, attention_mask=attention_mask).last_hidden_state
13        h_cls = H[:, 0, :]
14        return self.head(h_cls)
15 
16model = BertClassifier(num_labels=3)
17for param in model.bert.parameters():
18    param.requires_grad = False
19trainable = filter(lambda p: p.requires_grad, model.parameters())
20optimizer = torch.optim.Adam(trainable, lr=1e-4)
21 
22n_train = sum(p.numel() for p in model.parameters() if p.requires_grad)
23n_total = sum(p.numel() for p in model.parameters())
24print(f"{n_train:,} of {n_total:,} weights train")
25 
26tok = AutoTokenizer.from_pretrained("bert-base-uncased")
27batch = tok(["the cute axolotl is calm", "the tank is too warm"], padding=True, return_tensors="pt")
28logits = model(batch["input_ids"], batch["attention_mask"])
29print(logits.shape)

It prints:

12,307 of 109,484,547 weights train
2torch.Size([2, 3])

The forward pass runs the encoder, takes the hidden vector at position 0 (the [CLS] token BERT's tokenizer puts at the start) with H[:, 0, :], and maps that one vector to 3 class scores. Only the head trains, and it has $768 \times 3 + 3 = 2307$ weights out of about 109 million. The output has one row per sentence and one score per class.

Building the classifier. self.bert, loaded with AutoModel.from_pretrained, gives H, the last_hidden_state. h_cls is H at position 0, and it goes into self.head, a new linear layer. self.bert is pretrained, and self.head starts random.

Freezing the backbone and training the head. self.bert is frozen with requires_grad = False on every parameter, and self.head is trainable since requires_grad stays True. The code is for param in model.bert.parameters(): param.requires_grad = False. The pretrained encoder supplies structure, and the new head learns the task.

Why transfer learning works

The checkpoint never saw your labels and may never have seen your domain, so it is fair to ask why its weights help at all. Much of what a model learns in pretraining is not specific to the pretraining task. Predicting a hidden token or the next token forces the model to learn grammar, word meaning and the general structure of language. That structure is useful for many tasks that have nothing to do with predicting tokens.

Reusing structure learned on one task or domain to help with a different one is transfer learning. Fine-tuning, with or without frozen layers, is one way of doing it.

Term What it is Example
Transfer learning the idea reuse what pretraining learned
Fine-tuning a technique keep training BERT on your labels
Freezing a choice inside fine-tuning train only the new head

Why does this even work? The pretraining objective, mask or predict the next token, teaches grammar, word meaning and general structure, which are not specific to the pretraining objective itself. That structure is useful on a different task. Reusing structure learned on one task or domain to help a different one is transfer learning.

When fine-tuning is not enough

Transfer is not all or nothing. How much of the pretrained structure helps depends on how close the new task and domain are to what the checkpoint saw. A checkpoint pretrained on general web text transfers well to another general-text task, because most of what it learned still applies. The same checkpoint transfers less to a domain it barely saw, such as legal contracts full of specialized terms, or to a language it was never trained on. Less of its structure is useful there, so fine-tuning has to learn more from your data with less of a head start.

How close counts. A spectrum from close to far. Close domain, general web text to general web text: most pretrained structure applies. Far domain, general web text to legal contracts: less pretrained structure applies. The closer the domains, the more transfer helps and the less new data fine-tuning needs.

Fine-tuning also has limits of its own. It still needs some task-specific data, it still costs compute, and pushed too hard it can still forget. If the task is reasonably close to what the checkpoint saw, fine-tuning is the common path. If the target domain or language is very different from anything the checkpoint was trained on, a gentle fine-tune cannot make up for that. Looking for a better-matched pretrained checkpoint is usually worth doing before training a new one from scratch.

When fine-tuning isn't enough. For a task close to pretraining, fine-tuning is the common path. For a task far from pretraining, gentle fine-tuning cannot fix this. Look for a better-matched pretrained checkpoint before training a new one from scratch. Fine-tuning still needs data and compute, and does not fix a badly mismatched base.

Common mistakes

How to load a model with Hugging Face transformers covers getting the checkpoint in the first place, and open-weight vs closed LLMs covers why you need open weights to fine-tune a model yourself. Masked language modeling explained shows the pretraining objective that gives BERT its general structure.

QuiddityML teaches fine-tuning and transfer learning as one concept in the Intro to NLP track. The exercises include freezing the first layer of an MLP as fill in the blank, order the code and write it from scratch, then wrapping BERT in a classifier with a new head and spotting the bugs in it.