◆ AI All-in-One

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
↗ Plan a path here

Read first

Pretraining Large Language ModelsTransfer Learning

This leads to

Instruction Tuning and Chat ModelsLoRA and Parameter-Efficient Fine-Tuning
The full path from zero — 43 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Tensors and Shapes
  15. NumPy and Array Thinking
  16. Language Modeling and Next-Token Prediction
  17. Supervised Learning
  18. Linear Regression
  19. Training, Validation and Test Sets
  20. The Perceptron
  21. Logistic Regression
  22. Overfitting and the Bias–Variance Tradeoff
  23. Regularization: L1 and L2
  24. Neural Networks
  25. Recurrent Neural Networks
  26. Backpropagation
  27. Activation Functions
  28. Dropout and Regularizing Neural Networks
  29. PyTorch
  30. Vanishing and Exploding Gradients
  31. Normalization Layers: BatchNorm and LayerNorm
  32. Optimizers: SGD, Momentum and Adam
  33. LSTMs and GRUs
  34. Residual Connections
  35. Training Neural Networks in Practice
  36. Sequence-to-Sequence Models
  37. Transfer Learning
  38. Attention
  39. Self-Attention and Multi-Head Attention
  40. Positional Encodings
  41. The Transformer
  42. GPT and Decoder-Only Models
  43. Pretraining Large Language Models
  44. 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.

How much of the model do you change? cheap, instant, reversible costly, slow, permanent Prompting change the input; weights untouched Retrieval paste retrieved text into the input PEFT / LoRA train <1% extra, freeze the rest Full fine-tune nudge every weight on 10³–10⁵ examples Pretraining every weight from random, ~10¹³ tokens fine-tuning changes behaviour, format, style Rough cost: minutes hours to build 1 GPU, hours several GPUs, hours to days thousands of GPUs, months
Fig. 1 The spectrum of ways to adapt a language model to your task, from cheapest (change only the input) to most expensive (train a new model). Fine-tuning sits in the middle: it changes the weights, but only a little and on little data.
  • 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 θ\theta, a loss LL, and you run gradient descent (in practice the Adam family of Optimizers: SGD, Momentum and Adam):

θ←θ−η ∇L(θ)\theta \leftarrow \theta - \eta \, \nabla L(\theta)

Only three things differ from training from scratch:

  1. The starting point. θ\theta begins at the pretrained values, not at random numbers.
  2. The data. Thousands to hundreds of thousands of examples, not trillions of tokens.
  3. The learning rate. η\eta is small, typically around 10−510^{-5} 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 yty_t 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:

L=−1T∑t=1Tlog⁡pθ(yt∣x,y1,…,yt−1)L = -\frac{1}{T} \sum_{t=1}^{T} \log p_\theta(y_t \mid x, y_1, \dots, y_{t-1})

Here xx is the prompt, y1…yTy_1 \dots y_T are the TT tokens of the ideal response, and pθp_\theta 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.

L=−12(ln⁡0.30+ln⁡0.60)=−12(−1.204−0.511)=0.858L = -\tfrac{1}{2}\left(\ln 0.30 + \ln 0.60\right) = -\tfrac{1}{2}(-1.204 - 0.511) = 0.858

After some fine-tuning the probabilities are 0.90 and 0.95:

L=−12(ln⁡0.90+ln⁡0.95)=−12(−0.105−0.051)=0.078L = -\tfrac{1}{2}\left(\ln 0.90 + \ln 0.95\right) = -\tfrac{1}{2}(-0.105 - 0.051) = 0.078

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-tuningevery weight trains output head layer N layer 2 layer 1 ⋮ input tokens Head onlybody frozen, new head trains output head layer N layer 2 layer 1 ⋮ input tokens Adapters / LoRAfrozen body + tiny add-ons output head layer N layer 2 layer 1 ⋮ input tokens trainable (updated by gradients) frozen (fixed)
Fig. 2 Three ways to fine-tune the same pretrained network. Left: full fine-tuning updates every weight. Middle: freeze the body and train only a new output head. Right: freeze everything and insert small trainable adapters (the idea behind LoRA).
  • 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:

7×109×16 bytes=112 GB7 \times 10^9 \times 16 \text{ bytes} = 112 \text{ GB}

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:

  1. 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.
  2. 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.
  3. 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 10−510^{-5} for full fine-tuning (higher, around 10−410^{-4}, 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

  1. 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?
  2. Reduce forgetting: when fine-tuning the forget model, mix 200 examples of task A into every step (compute both losses and add them). How much of task A's accuracy survives?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your manager wants the support bot to know about products launched last week. What does the chapter recommend?

  2. About how much GPU memory does full fine-tuning of a 7-billion-parameter model need with Adam and mixed precision, before activations?

  3. After fine-tuning on a narrow task, the model has become much worse at things it used to do well. What is this called?

  4. In supervised fine-tuning, why are the prompt tokens given the label -100?

  5. A team has 200 clean examples and 10,000 noisy ones for the same task. What does the chapter suggest about data?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Docs

TRL documentation

Hugging Face · Intermediate · Free

Transformer Reinforcement Learning: trainers for supervised fine-tuning (SFT), reward modelling, PPO, DPO and GRPO on Hugging Face models.

Book

Build a Large Language Model (From Scratch)

Sebastian Raschka · 2024 · Intermediate · code free, book paid

Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.

Paper

LIMA: Less Is More for Alignment

Zhou et al. (Meta) · 2023 · Intermediate · Free

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.

Book

AI Engineering

Chip Huyen · 2025 · Intermediate · Paid

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