Level 3 In-Depth AI · Transformers and Language Models
Fine-Tuning
Taking a model that has already learned a lot and training it a little more on your own examples, so it does your task in your style. When to do it, how it works, and what it can break.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 43 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 43 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Dropout and Regularizing Neural Networks
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Optimizers: SGD, Momentum and Adam
- LSTMs and GRUs
- Residual Connections
- Training Neural Networks in Practice
- Sequence-to-Sequence Models
- Transfer Learning
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- Fine-Tuning
Read them roughly in this order. See it on the concept map →
Why it matters
Pretraining a large language model costs millions of dollars and months of GPU time. What comes out is a base model: a superb next-token predictor that has absorbed grammar, facts, code and styles of writing from trillions of tokens, but that does not reliably do any particular job. Ask a base model a question and it may answer, or it may continue with five more questions, as if it were completing a quiz page.
Fine-tuning means taking a model that has already been trained and continuing to train it, briefly, on a much smaller dataset chosen for a specific purpose. It is how nearly every useful language model is made:
- Chat assistants such as ChatGPT, Claude and Gemini start as base models and are fine-tuned on examples of helpful conversations (Instruction Tuning and Chat Models) and then on human preferences (RLHF and Preference Optimization).
- Specialised models for law, medicine or a company's own support tickets are fine-tuned on in-domain text.
- Small, cheap models are fine-tuned to do one narrow job (extracting fields from invoices, classifying support emails) as well as a much bigger general model, at a fraction of the cost.
Fine-tuning is the language-model form of Transfer Learning: reuse what was learned on a huge general task to do well on a small specific one. This chapter explains how it works, what it costs, what it can break, and when you should reach for something simpler. The next chapter, LoRA and Parameter-Efficient Fine-Tuning, shows how to fine-tune while training only a tiny fraction of the weights.
The intuition
Think of a newly qualified doctor. Medical school (pretraining) took years and taught a vast amount of general knowledge. A residency in cardiology (fine-tuning) takes far less time and teaches no new chemistry or anatomy from scratch. It sharpens and redirects what is already there towards one speciality and one way of working.
Fine-tuning a model is similar. You do not teach it language again. You show it a few thousand, sometimes a few hundred, examples of exactly the behaviour you want, and nudge its billions of weights a short distance in that direction. Because the starting point is already so capable, a small push goes a long way.
But a residency can also make a doctor rusty at things they no longer practise. Fine-tuning has the same risk, called catastrophic forgetting: push the weights too hard on narrow data and the model loses abilities it used to have.
It helps to see fine-tuning as one point on a spectrum of ways to adapt a model, ordered by how much you change it and how much it costs.
- Prompting changes only the input. No training at all. See Prompt Engineering.
- Retrieval (Retrieval-Augmented Generation) looks up relevant documents and pastes them into the prompt, so the model can use facts it never saw in training.
- Parameter-efficient fine-tuning trains a small set of new weights and freezes the rest (LoRA and Parameter-Efficient Fine-Tuning).
- Full fine-tuning updates every weight of the model.
- Pretraining builds a model from scratch.
Key idea Fine-tuning continues training a pretrained model on a small, targeted dataset. It is good at changing behaviour, format and style, and fairly poor at adding new facts. For facts, use retrieval.
How it works
The same training loop, a different starting point
Mechanically, fine-tuning is ordinary training. You have a model with parameters , a loss , and you run gradient descent (in practice the Adam family of Optimizers: SGD, Momentum and Adam):
Only three things differ from training from scratch:
- The starting point. begins at the pretrained values, not at random numbers.
- The data. Thousands to hundreds of thousands of examples, not trillions of tokens.
- The learning rate. is small, typically around for full fine-tuning of an LLM, often 10 to 100 times smaller than the peak pretraining rate, so the weights move only a little away from where they started.
Supervised fine-tuning
The most common kind for language models is supervised fine-tuning (SFT): you show the model pairs of (prompt, ideal response) and train it to produce the response. The loss is the same next-token cross-entropy used in pretraining. For each token of the response, the model predicts a probability distribution given everything before it, and the loss is the negative log of the probability it gave the correct token:
Here is the prompt, are the tokens of the ideal response, and is the model's predicted probability.
Notice the sum runs over the response tokens only. The prompt tokens are fed in but not scored. This is loss masking: you don't want to train the model to predict the user's question, only its own answer. In code it is usually done by setting the label of every prompt token to a special "ignore" value (-100 in PyTorch and Hugging Face).
A worked example
Suppose an SFT example is the prompt "Capital of France?" and the response "Paris.", which tokenises into two response tokens, Paris and .. Before fine-tuning, the base model gives Paris probability 0.30 (it also likes continuations such as Capital of Spain?) and . probability 0.60 after it.
After some fine-tuning the probabilities are 0.90 and 0.95:
The gradient of that loss nudges every weight so that, given a question, the answer becomes more likely than another question. Repeat over thousands of examples and the model learns the general habit "when asked, answer", not just this one fact.
What gets trained
There are several choices for which weights change.
- Full fine-tuning updates every weight. It is the most flexible and usually gives the best results when you have enough data and hardware.
- Head-only training (also called a linear probe) keeps the body as frozen weights, weights excluded from the update so they cannot change, and trains only a new final layer. This was the classic recipe for encoder models doing classification. It is cheap and can't forget, but it can only reuse the features the body already computes.
- Parameter-efficient fine-tuning (PEFT) freezes the original weights and adds a small number of new trainable ones. LoRA, the most popular method, typically trains under 1% of the parameter count and often comes close to full fine-tuning. See LoRA and Parameter-Efficient Fine-Tuning.
What it costs
Full fine-tuning is expensive in memory, not because of the data but because of the optimizer. With Mixed Precision Training training and Adam, each parameter needs roughly 16 bytes of GPU memory: 2 for the 16-bit weight, 2 for its gradient, 4 for a 32-bit master copy of the weight and 8 for Adam's two running averages. For a 7-billion-parameter model:
That is before the activations, which grow with batch size and sequence length. A single 80 GB GPU is not enough, so full fine-tuning of a 7B model needs several GPUs and Distributed Training tricks. Just running the same model needs only the 2 bytes per parameter, about 14 GB. This gap is the main reason LoRA and QLoRA became so popular.
Fine-tune, prompt or retrieve?
A practical rule of thumb, roughly in order:
- Try prompting first. A clear instruction plus a few examples in the prompt solves a surprising number of problems, costs nothing to train, and you can change it in seconds.
- If the model lacks knowledge (your product catalogue, last week's news, private documents), use retrieval (Retrieval-Augmented Generation). Fine-tuning is an unreliable way to add facts: the model may half-learn them and then hallucinate confident mixtures.
- Fine-tune when you need a behaviour the prompt can't reliably produce: a strict output format, a house style or tone, a narrow classification task, a smaller and cheaper model that matches a bigger one on your task, or shorter prompts at high volume.
These combine. Many production systems fine-tune a model to use retrieved documents well, and then retrieve at run time. Fine-Tuning an Open Model in Practice walks through the engineering side.
Data matters more than anything else
The quality of the fine-tuning set dominates the result. The LIMA paper (Meta, 2023) fine-tuned a 65-billion-parameter base model on just 1,000 carefully curated prompt–response pairs and got an assistant that human raters often preferred to models trained on far more data. The OpenAI InstructGPT work (2022) used about 13,000 demonstration prompts for its SFT stage. The lesson, often summarised as the "superficial alignment hypothesis", is that the knowledge is already in the base model; fine-tuning mostly teaches it which of its many possible behaviours to use.
Good fine-tuning data is consistent (the same kind of input always gets the same kind of output), representative of what users will actually send, and correct. A few hundred clean examples beat ten thousand noisy ones.
In code
This small PyTorch experiment shows the three key effects: pretraining helps when data is scarce, freezing can help with very little data, and full fine-tuning can wipe out the old skill. Two synthetic tasks, A and B, share the same hidden structure, much as different language tasks share grammar and world knowledge.
import copy, torch, torch.nn as nn
torch.manual_seed(0)
# Two related tasks: both labels depend on the same hidden features z = tanh(Wx)
W = torch.randn(8, 20)
U_A, U_B = torch.randn(5, 8), torch.randn(5, 8)
def make(n, U):
x = torch.randn(n, 20)
return x, (torch.tanh(x @ W.T) @ U.T).argmax(1)
xa, ya = make(20000, U_A); xa_test, ya_test = make(2000, U_A) # big task A
xb, yb = make(200, U_B); xb_test, yb_test = make(2000, U_B) # tiny task B
def net(): return nn.Sequential(nn.Linear(20, 64), nn.ReLU(),
nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 5))
def train(m, x, y, params, steps=300, lr=1e-2):
opt = torch.optim.Adam(params, lr=lr)
for _ in range(steps):
loss = nn.functional.cross_entropy(m(x), y)
opt.zero_grad(); loss.backward(); opt.step()
def acc(m, x, y): return (m(x).argmax(1) == y).float().mean().item()
base = net(); train(base, xa, ya, base.parameters(), steps=1500) # "pretrain"
scratch = net(); train(scratch, xb, yb, scratch.parameters()) # no pretraining
full = copy.deepcopy(base); full[-1] = nn.Linear(64, 5) # new head
train(full, xb, yb, full.parameters(), lr=1e-3) # full fine-tune
head = copy.deepcopy(base); head[-1] = nn.Linear(64, 5)
for p in head[:-1].parameters(): p.requires_grad = False # freeze body
train(head, xb, yb, head[-1].parameters()) # head only
forget = copy.deepcopy(base); train(forget, xb, yb, forget.parameters())
print(f"pretrained, task A: {acc(base, xa_test, ya_test):.2f}") # 0.93
print(f"from scratch, task B: {acc(scratch, xb_test, yb_test):.2f}") # 0.67
print(f"full fine-tune, task B: {acc(full, xb_test, yb_test):.2f}") # 0.78
print(f"head only, task B: {acc(head, xb_test, yb_test):.2f}") # 0.82
print(f"after tuning on B, task A: {acc(forget, xa_test, ya_test):.2f}") # 0.41
With only 200 examples of task B, a pretrained start beats training from scratch (0.78 and 0.82 versus 0.67). Here the frozen body wins because 200 examples are too few to safely move the body's 5,500 weights. The last line is catastrophic forgetting in miniature: after fine-tuning on B, accuracy on the original task A collapses from 0.93 to 0.41. Exact numbers vary with the seed and PyTorch version, but the pattern holds.
For a real language model, Hugging Face's TRL library wraps SFT, including chat formatting and loss masking, in a few lines. This needs a GPU and downloads a model and dataset, so it is not run here:
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
dataset = load_dataset("trl-lib/Capybara", split="train") # chat-format examples
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B", # a small base model
train_dataset=dataset,
args=SFTConfig(output_dir="qwen-sft", learning_rate=2e-5, num_train_epochs=1),
)
trainer.train()
Common pitfalls
- Trying to teach facts. Fine-tuning on a handful of documents rarely makes a model reliably recall them, and it can make it confidently wrong. Use retrieval for knowledge.
- Learning rate too high. The single most common cause of a fine-tune that destroys the model. Start around for full fine-tuning (higher, around , for LoRA) and watch a held-out loss.
- Too many epochs on small data. The model memorises the training answers word for word (Overfitting and the Bias–Variance Tradeoff). One to three epochs is typical. Stop when validation loss turns up.
- Mismatched chat template. Instruction-tuned models expect a specific format of special tokens around each turn. Fine-tune in one format and serve in another and quality quietly drops. See Instruction Tuning and Chat Models.
- Forgetting to mask the prompt. Without loss masking the model spends capacity learning to imitate user inputs.
- No evaluation set. Keep a few hundred examples aside and also re-check general abilities, not just your task. See Evaluating LLM Applications.
Watch out Fine-tuning can quietly remove safety behaviour. Researchers have shown that fine-tuning an aligned chat model on even a small number of harmful examples, and sometimes on harmless ones, can weaken its refusals. If you fine-tune a model you will deploy, re-test its safety behaviour afterwards.
Variations
- Continued pretraining (domain-adaptive pretraining): keep training with the plain next-token loss on lots of raw in-domain text (legal filings, medical papers, code) before any SFT. This is the one form of fine-tuning that does add substantial knowledge, because it uses far more data.
- Parameter-efficient fine-tuning (LoRA, QLoRA, adapters, prefix tuning) trains tiny add-ons instead of the whole model: LoRA and Parameter-Efficient Fine-Tuning.
- Instruction tuning is SFT on many different tasks phrased as instructions, which produces general assistants: Instruction Tuning and Chat Models.
- Preference fine-tuning (RLHF, DPO) trains on comparisons of good and bad answers rather than on single ideal answers: RLHF and Preference Optimization.
- Distillation fine-tunes a small model on a big model's outputs: Knowledge Distillation and Small Models.
- Fighting forgetting: mix some general data back into the fine-tuning set ("replay"), use a lower learning rate, use PEFT, or penalise moving important weights (elastic weight consolidation).
A bit of history
Fine-tuning pretrained networks became standard in computer vision around 2014, when people found that features from ImageNet-trained CNNs transferred to almost any image task. For language, the breakthrough came in 2018. Jeremy Howard and Sebastian Ruder's ULMFiT pretrained a language model and fine-tuned it for text classification, with tricks such as gradual unfreezing and lower learning rates for earlier layers. OpenAI's first GPT paper and Google's BERT followed the same year, and "pretrain, then fine-tune" became the default recipe for every NLP task.
As models grew, two things changed. GPT-3 (2020) showed that a big enough model could do many tasks from the prompt alone, without any fine-tuning. And full fine-tuning of hundred-billion-parameter models became too expensive for most people, which drove the invention of LoRA (2021) and QLoRA (2023). Meanwhile InstructGPT (2022) showed that a short phase of SFT followed by RLHF turned a base model into a far more useful assistant, the recipe behind ChatGPT. Today almost every deployed LLM is a fine-tuned one.
Try it
- In the code, raise task B's training set from 200 to 5,000 examples. Does full fine-tuning now beat head-only training? Why would more data favour the more flexible method?
- Reduce forgetting: when fine-tuning the
forgetmodel, mix 200 examples of task A into every step (compute both losses and add them). How much of task A's accuracy survives?- Work out the memory for full fine-tuning of a 70-billion-parameter model at 16 bytes per parameter. How many 80 GB GPUs is that, before counting activations?
Hint for 2: the replay trick works because the gradient now has to keep task A's loss low as well.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
TRL documentation
Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.
Build a Large Language Model (From Scratch)
Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.
Universal Language Model Fine-tuning for Text Classification (ULMFiT)
Showed that pretraining a language model and then fine-tuning it beats training from scratch on text tasks. An early, readable statement of the pretrain-then-fine-tune recipe.
LIMA: Less Is More for Alignment
Fine-tunes a 65B base model on just 1,000 carefully chosen examples and gets a strong assistant, evidence that most knowledge comes from pretraining.
Overcoming catastrophic forgetting in neural networks (EWC)
Elastic weight consolidation: slow down learning on the weights that mattered most for an old task, so a new task does not erase it.
AI Engineering
Building applications on foundation models: evaluation, prompting, RAG, agents, fine-tuning, inference optimisation.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/fine-tuning.md