Sub topic 1
Why fine-tune a pretrained transformer
This chapter explains why the rest of the tutorial starts from a pretrained transformer encoder and not from random weights. It covers what pretraining gives the model, what fine-tuning changes, and when the approach works poorly. The later chapters build the pipeline step by step: tokenization, the classification head, the Trainer API, metrics and tuning.
Prerequisites
This chapter assumes you know the following:
- Python, including functions and dictionaries.
- The basics of supervised learning: training and test sets, loss, and overfitting.
- PyTorch tensors, meaning shapes,
torch.no_grad(), and moving data between devices. - A rough idea of what a neural network and an embedding are. An embedding is a vector of numbers that represents a token or a piece of text.
You do not need to know the transformer architecture in detail. You need to know that an encoder turns a sequence of tokens into a sequence of vectors, one per token.
To run the code you need torch and transformers installed. The example downloads about 270 MB of weights the first time you run it.
The problem with training from scratch
Suppose you have 5,000 labeled product reviews and want to predict whether each one is positive or negative. A transformer encoder has tens of millions of parameters. If you start from random weights, the model must learn two things from those 5,000 examples:
- How the language works: word meanings, grammar, which words go together, how context changes meaning.
- How that language maps to your labels.
The first task is much larger than the second. Five thousand examples are far too few to learn it. A model trained from scratch on a small dataset usually memorizes the training set and does poorly on new text. It overfits, which means its training loss keeps falling while its validation loss stops improving or gets worse.
You could collect millions of labeled examples, but labeling is slow and costly. Raw text is not. The web, books and articles hold billions of sentences that need no labels. Pretraining uses that text.
What pretraining gives you
Pretraining is a first training phase in which a model learns from unlabeled text using a task made from the text itself. For encoder models like BERT and DistilBERT, the task is masked language modeling. The training code hides about 15% of the tokens and asks the model to predict them from the surrounding words.
To fill in a blank like "The movie was so [MASK] that I fell asleep", the model has to learn several things:
- Syntax: the blank is probably an adjective.
- Semantics: "fell asleep" suggests a word like "boring".
- Context: the same word can mean different things in different sentences.
None of this needs a human label, because the answer is the original token. After many passes over a large corpus, the model has seen far more language than your labeled dataset could ever contain. The result is a set of weights that encode general knowledge about language.
Learning one task and reusing the result for another is called transfer learning. Fine-tuning is the most common way to do it: you keep the pretrained weights as the starting point and continue training on your labeled data.
Seeing what the encoder already knows
You can check the claim that pretraining captures context. The code below passes two sentences through a pretrained DistilBERT encoder. Both contain the word "bank", with different meanings. It then compares the vectors the encoder produces for that word.
import torch
from transformers import AutoModel, AutoTokenizer
checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModel.from_pretrained(checkpoint)
model.eval()
sentences = [
"I deposited cash at the bank.",
"We had a picnic on the river bank.",
"She works at the bank downtown.",
]
inputs = tokenizer(sentences, padding=True, return_tensors="pt")
with torch.no_grad():
hidden = model(**inputs).last_hidden_state # (batch, seq_len, 768)
bank_id = tokenizer.convert_tokens_to_ids("bank")
vectors = []
for i in range(len(sentences)):
position = (inputs["input_ids"][i] == bank_id).nonzero()[0].item()
vectors.append(hidden[i, position])
cos = torch.nn.functional.cosine_similarity
print("money vs river:", cos(vectors[0], vectors[1], dim=0).item())
print("money vs money:", cos(vectors[0], vectors[2], dim=0).item())
print("parameters:", sum(p.numel() for p in model.parameters()))The two financial uses of "bank" should score higher than the financial and river uses. Exact values depend on the library version, but the ordering is the point. A static embedding table such as word2vec gives "bank" one vector regardless of context, so both scores would be 1.0. The encoder produces a different vector for each occurrence, because every layer mixes in information from the other tokens through self-attention.
The last line shows the model size, about 66 million parameters. A model with that many parameters would be hard to train from scratch on a few thousand examples.
What fine-tuning changes
Fine-tuning does three things.
- Adds a small task-specific layer. The pretrained encoder outputs one vector per token. A classification head is a small layer that turns those vectors into one score per class. Its weights start out random. The next chapters cover it in detail.
- Trains with labels. You run the usual supervised loop: forward pass, cross-entropy loss against the true label, backward pass, optimizer step.
- Updates the pretrained weights slightly. Because the starting point is already good, you use a small learning rate, often between 1e-5 and 5e-5. The encoder only needs to shift its representations toward your task. It does not need to learn language.
Because the starting point is good, fine-tuning needs less of everything:
| Resource | Training from scratch | Fine-tuning a pretrained encoder |
|---|---|---|
| Labeled examples | Often hundreds of thousands or more | Often hundreds to a few thousand |
| Training time | Days or weeks on many accelerators | Minutes to hours on one GPU |
| Typical learning rate | Larger, with a long warmup | Small, around 2e-5 |
| Risk of overfitting on small data | High | Lower, but still real |
| Knowledge of language | Learned only from your labels | Inherited from pretraining |
These figures are rough guides. The right amount of data depends on how hard the task is and how close your text is to the pretraining text.
Why this works better on small datasets
There are three reasons.
Better initialization. Gradient descent finds better solutions when it starts in a region where the loss is already low for language-related features. Random weights start far from any useful solution.
Shared features. Lower layers of a pretrained encoder tend to capture local patterns such as word pieces and syntax. Higher layers capture more abstract, task-relevant patterns. Many classification tasks, including sentiment, topic and intent, can reuse these features. Your labeled data only needs to teach the model which of the existing features matter.
Implicit regularization. Fine-tuning with a small learning rate keeps the weights close to their pretrained values. That limits how far the model can drift to memorize the training set.
Choosing a checkpoint
A checkpoint is a saved set of model weights. For classification, you usually pick an encoder, not a generative decoder model. An encoder reads the whole input in both directions at once, which suits tasks where you need a label for the full text. The choice involves a trade-off.
| Checkpoint | Approximate size | Speed | Notes |
|---|---|---|---|
| `distilbert-base-uncased` | 66M parameters | Fast | A distilled BERT. Used throughout this tutorial. |
| `bert-base-uncased` | 110M parameters | Medium | The standard baseline. |
| `roberta-base` | 125M parameters | Medium | Pretrained longer on more data. Often scores a little higher. |
| Domain-specific models (for example, models pretrained on biomedical or legal text) | Varies | Varies | Worth trying when your text differs a lot from general web text. |
For a first project, start with a small model. If the results fall short of what you need, move to a larger one. A bigger model rarely fixes a problem that comes from noisy labels or a bad split.
Also check the model's language. An English-only checkpoint will do poorly on German text. Use a multilingual checkpoint such as xlm-roberta-base in that case.
Common errors and limits
Fine-tuning is not always the right tool, and these mistakes are common.
- Domain mismatch. If your text looks very different from the pretraining corpus, such as source code, chemical formulas or heavy slang, the benefit shrinks. A domain-specific checkpoint or further pretraining on your own unlabeled text can help.
- Too high a learning rate. A rate like 1e-3 can destroy the pretrained knowledge in the first few steps. This is sometimes called catastrophic forgetting. Training loss jumps up and accuracy falls to the majority-class rate.
- Tiny datasets. With a few dozen examples, fine-tuning is unstable. Results change a lot between random seeds. Consider a few-shot approach or a zero-shot classifier instead.
- Leaked test data. Pretrained models may have seen public benchmark text during pretraining. A high score on a famous benchmark can overstate how the model will do on your private data. Always keep a held-out test set from your own distribution.
- Inherited bias. The model carries the biases of its pretraining text. Fine-tuning on a small dataset does not remove them. Check the model's behavior on the groups and cases that matter for your application.
- Truncated inputs. Encoders have a maximum input length, 512 tokens for BERT-style models. Longer texts are cut off, and the label may depend on the part that was cut. The tokenization chapter covers this.
How the rest of the tutorial fits together
Each later chapter handles one step of the pipeline you will build:
- Tokenize text into model inputs.
- Attach a classification head to the encoder.
- Split the data and choose metrics.
- Train with the Trainer API and tune the hyperparameters.
- Diagnose overfitting, class imbalance and errors.
- Save the model, run inference, and consider LoRA as a cheaper alternative to full fine-tuning.
Exercise
A teammate wants to train a 66-million-parameter encoder from random weights on 3,000 labeled support tickets, arguing that "the model will learn exactly our vocabulary". Give two reasons fine-tuning a pretrained encoder is likely to work better, and name one situation where the pretrained model would help less.
Show answer
First, pretraining on a large unlabeled corpus has already taught the encoder general language knowledge (syntax, word meaning in context), so the 3,000 labels only need to teach the mapping to ticket categories. A from-scratch model must learn language and the task from the same small set and will likely overfit. Second, fine-tuning starts from good weights and uses a small learning rate, so it converges in far fewer steps and stays close to a solution that generalizes. The pretrained model helps less when the text is very different from the pretraining data, for example source code, specialized jargon or a language the checkpoint was not trained on. In that case a domain-specific or multilingual checkpoint, or extra pretraining on unlabeled in-domain text, is a better choice.
Exercise
In the "bank" example, why would a static word embedding table give a cosine similarity of exactly 1.0 between the "bank" vectors of the two sentences, while the transformer encoder does not?
Show answer
A static embedding table maps each token ID to one fixed vector, so every occurrence of "bank" gets the same vector and the similarity is 1.0. A transformer encoder applies self-attention across the whole sentence in every layer, so the output vector for "bank" depends on the surrounding words. Occurrences in different contexts therefore get different vectors.