Fine-tuning

Fine-tuning starts from a pretrained model and trains it on smaller, curated examples so it behaves in a specific way.

The Big Question

Pretraining teaches a transformer a broad skill: given the tokens so far, predict the next token. That objective can teach grammar, facts, style, code patterns, and many regularities in language.

How do we teach a pretrained language model to perform a specific job without training it from scratch?

Fine-tuning is the next stage. It starts with pretrained weights and continues training on a smaller, more specific dataset. The goal is not to relearn language. The goal is to bend an already capable model toward a target behavior.

Pretraining asks: what patterns exist in language? Fine-tuning asks: which of those patterns do we want this model to use?

Core Intuition

Imagine Jessie has read recipes, reviews, menus, novels, textbooks, code, customer support chats, and random forum posts. She knows a lot about language and food. But if a user asks what to put on a cheeseburger, she might continue like a blog article, a forum thread, or a dataset entry.

User: What should I put on a cheeseburger?

Pretrained-style continuation: This question has been discussed by many food bloggers...

Fine-tuned assistant response: Start with cheese, pickles, onion, lettuce, tomato, ketchup, and mustard. For more flavor, add caramelised onions or burger sauce.

The model did not lack all the knowledge. The missing piece was behavior. Fine-tuning shows the model many examples of the kind of continuation we want: direct answers, useful formatting, constraint-following, and task-specific style.

This works because the model does not start from random weights. Pretraining has already built rich internal representations. Fine-tuning adjusts those representations instead of creating them from nothing.

Pretraining Versus Fine-tuning

AspectPretrainingFine-tuning
Starting pointRandom weightsA pretrained model
DataHuge mixture of general textSmaller task-specific examples
GoalLearn broad language patternsAdapt behavior, format, style, or task skill
LossNext-token cross entropyUsually the same next-token cross entropy
ScaleMassive and expensiveMuch smaller, often repeated iteratively

Interactive Demo

Fine-tuning behavior lab

Same prompt, different behavior

User: I only have beef, buns, onion, and cheese. What can I make?
Pretrained continuation

This question appears in many cooking forums and has several possible answers...

Fine-tuned response

You can make a simple cheeseburger. Shape the beef, cook it, melt the cheese on top, toast the bun, and add onion.

Loss mask visualizer

<user>Ionlyhavebeefbunsonioncheese<assistant>Youcanmakeasimplecheeseburger

User tokens provide context. Assistant tokens are the target positions that teach the model what response to produce.

Overfitting simulator

Repeated phrase rate
36%
Unseen prompt score
87%
LoRA parameter counter

Freeze the base, train the update

LoRA keeps the original matrix fixed and learns a small low-rank update. Adjust the rank to see why this is much cheaper than full fine-tuning.

Full fine-tuning parameters
1610.6M
LoRA trainable parameters
6.3M
Reduction factor
256.0x fewer

The same base knowledge can produce very different behavior. Fine-tuning changes which completions become likely for a given kind of prompt.

Fine-tuning Data

A supervised fine-tuning dataset usually contains examples of desired input-output behavior. For an assistant, each example may contain an instruction, optional input, and response.

{
  "instruction": "Suggest a burger using these ingredients.",
  "input": "beef, buns, onion, cheese",
  "response": "You can make a simple cheeseburger with fried onion and melted cheese."
}

That structured example is converted into one formatted training sequence:

### Instruction:
Suggest a burger using these ingredients.
### Input:
beef, buns, onion, cheese
### Response:
You can make a simple cheeseburger with fried onion and melted cheese.

Modern chat models often use special chat templates instead of visible markdown markers:

<|user|>
Suggest a burger using beef, buns, onion, and cheese.
<|assistant|>
You can make a simple cheeseburger with fried onion and melted cheese.

The exact format matters. The model learns patterns from the template. If training examples consistently mark where the assistant answer begins, the model learns to produce assistant-style text after that marker.

Mathematics

Fine-tuning usually uses the same next-token cross-entropy machinery as pretraining. Let the token sequence be:

x1,x2,,xTx_1,x_2,\ldots,x_T

At position tt, the model predicts a distribution over the next token:

pθ(xtx<t)p_\theta(x_t \mid x_{<t})

The token-level negative log likelihood is:

t(θ)=logpθ(xtx<t)\ell_t(\theta)=-\log p_\theta(x_t \mid x_{<t})

Averaged over a full sequence, the loss is:

L(θ)=1Tt=1Tlogpθ(xtx<t)\mathcal{L}(\theta)=-\frac{1}{T}\sum_{t=1}^{T}\log p_\theta(x_t \mid x_{<t})

Concrete Token Example

If the correct next token is You and the model assigns probability 0.700.70, the loss is:

log(0.70)=0.357-\log(0.70)=0.357

If it assigns probability 0.010.01, the loss is:

log(0.01)=4.605-\log(0.01)=4.605

Gradient descent updates the model so desired response tokens become more likely in the same contexts next time. There is no separate obedience module. The desired behavior becomes more probable under the model.

Masking The Loss

In assistant fine-tuning, the user message is context. The assistant answer is the target. We often compute loss only on assistant tokens.

mt={1if xt belongs to the assistant response0otherwisem_t=\begin{cases}1 & \text{if }x_t\text{ belongs to the assistant response}\\0 & \text{otherwise}\end{cases}
L(θ)=1t=1Tmtt=1Tmtlogpθ(xtx<t)\mathcal{L}(\theta)=-\frac{1}{\sum_{t=1}^{T}m_t}\sum_{t=1}^{T}m_t\log p_\theta(x_t \mid x_{<t})

If mt=0m_t=0, the token contributes nothing to the loss. In many PyTorch language-modeling setups, ignored labels are stored as -100.

Fine-tuning Methods

Full Fine-tuning

Full fine-tuning updates all model parameters. If the pretrained model starts at θ0\theta_0, training searches for:

θ=argminθLfine-tune(θ)\theta^*=\arg\min_\theta \mathcal{L}_{\text{fine-tune}}(\theta)

Every attention matrix, feed-forward matrix, embedding matrix, and output matrix can change. This gives maximum flexibility, but it is expensive and creates a complete new copy of the model.

Parameter-efficient Fine-tuning

Parameter-efficient fine-tuning freezes most of the pretrained model and trains only a small number of new parameters. The base model already knows language. The adapter steers that model toward a task.

LoRA

LoRA, short for low-rank adaptation, freezes a large weight matrix WW and learns a small update ΔW\Delta W:

W=W+ΔWW'=W+\Delta W

Instead of learning every entry in ΔW\Delta W, LoRA represents it as a low-rank product:

ΔW=BA\Delta W=BA
ARr×dBRd×rrdA\in\mathbb{R}^{r\times d}\qquad B\in\mathbb{R}^{d\times r}\qquad r\ll d

If d=4096d=4096 and r=8r=8, the full matrix has:

4096×4096=16,777,2164096\times4096=16{,}777{,}216

The LoRA update has:

4096×8+8×4096=65,5364096\times8+8\times4096=65{,}536

That is dramatically smaller. LoRA often works because fine-tuning does not need to invent a new language model. It mostly needs to steer an existing one.

Method Trade-offs

MethodWhat changesStrengthLimit
Full fine-tuningUpdate all model parametersMaximum flexibilityExpensive and easier to over-specialize
LoRAFreeze the base model and train low-rank updatesMuch cheaper; easy to store adaptersLess flexible than changing every weight
PromptingChange only the input promptFastest and cheapestCan be unreliable for repeated structured behavior
RetrievalAdd external facts to the contextBest for changing knowledgeDoes not directly change model behavior

Practical Considerations

Fine-tuning Is Usually About Behavior

Fine-tuning can teach some domain information, but it is usually strongest for behavior, format, style, task structure, and domain habits. If a restaurant menu changes every week, retrieval is usually better because retrieval changes the context at inference time. Fine-tuning changes the model weights.

Prompt First

Prompting changes the input. Fine-tuning changes the model. Prompting is cheaper and easier to iterate on, so a practical rule is: prompt first, fine-tune when prompting repeatedly fails in a measurable pattern.

Data Quality

Fine-tuning amplifies the dataset. If examples are verbose, the model becomes verbose. If examples ignore constraints, the model learns to ignore constraints. A small clean dataset can beat a large noisy one.

Bad example

User: I have no cheese. Suggest a burger.

Assistant: Add cheddar cheese and mozzarella.

Good example

User: I have no cheese. Suggest a burger.

Assistant: Use fried onion, pickles, mustard, and ketchup. Since you have no cheese, rely on sauce and onion for flavor.

Coverage

The dataset should include the important situations the model will face: direct questions, ambiguous requests, constraint-heavy requests, unsafe requests, format-specific requests, corrections, out-of-domain questions, and multi-turn conversations.

Overfitting And Forgetting

Too many epochs can make the model memorize surface quirks. If every answer begins with Great question!, the fine-tuned model may say that everywhere. Aggressive fine-tuning can also cause catastrophic forgetting, where the model gets better at the target task but worse at general abilities.

Fine-tuning usually uses a smaller learning rate than pretraining because the pretrained model is already valuable. The aim is to adapt enough, but not overwrite useful behavior.

The Full Pipeline

Fine-tuning is best treated as an experiment loop, not a one-shot ritual.

1Choose base modelStart from a pretrained model with the right size and license
2Define target behaviorWrite down what the model should do differently
3Collect examplesCreate instruction-response pairs or domain task examples
4Format examplesApply a prompt or chat template consistently
5TokeniseConvert formatted text into token IDs
6Mask labelsIgnore context tokens and train on target response tokens
7TrainRun next-token cross entropy with a small learning rate
8EvaluateCheck validation loss and real model outputs
9Inspect errorsFind missing cases, bad data, overfitting, and format failures
10IterateImprove data or hyperparameters and compare against the base model

The most important step is defining the target behavior. Make the model better is too vague. Answer burger recipe questions in fewer than 120 words, respect ingredient constraints, mention food safety when relevant, and use numbered steps for procedures is measurable.

Implementation

The key object is the labels tensor. User tokens are often masked with -100, while assistant tokens remain as targets.

import torch

optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)

for batch in dataloader:
    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    labels = batch["labels"]  # user positions are -100

    outputs = model(
        input_ids=input_ids,
        attention_mask=attention_mask,
        labels=labels,
    )

    loss = outputs.loss
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

Conceptually, the labels might look like this:

Tokens: User: What can I make? Assistant: Make a simple burger.
Labels: IGNORE IGNORE IGNORE IGNORE Make a simple burger.

Evaluation

Validation loss matters, but it is not enough. A model can have lower loss and still produce bad assistant behavior. Evaluate actual outputs on normal requests, ambiguous requests, adversarial requests, domain edge cases, safety-sensitive prompts, multi-turn conversations, and format-specific prompts.

Useful grading dimensions include helpfulness, correctness, constraint-following, format adherence, calibration, safety, and brevity. Always compare against the base model and against a strong prompt-only baseline.

Interview Discussion

How does fine-tuning differ from pretraining?

Pretraining learns broad language patterns from massive general text. Fine-tuning starts from that model and adapts it with smaller, targeted examples.

Why can supervised fine-tuning use next-token loss?

The desired response is still a sequence of tokens. Training increases the probability of those target tokens in the given context.

Why mask user tokens?

The user message is context. The model should learn to generate the assistant response, not reproduce the user prompt.

What is LoRA?

LoRA freezes large pretrained matrices and trains small low-rank update matrices, reducing the number of trainable parameters.

When should you choose retrieval instead of fine-tuning?

Use retrieval when the main need is access to changing external facts. Use fine-tuning when the main need is stable behavior or format.

Active Recall

1. What does pretraining teach, and what does fine-tuning teach?

2. Why does fine-tuning usually not need a new loss function?

3. Why do chat templates matter?

4. Why are user tokens often masked during assistant fine-tuning?

5. What is the difference between full fine-tuning and LoRA?

6. Why can a small bad dataset damage a model?

7. Why is fine-tuning not ideal for facts that change every week?

8. What should you compare against before deciding fine-tuning was worth it?

Common Mistakes

  • Thinking fine-tuning teaches the model from scratch. It depends on pretraining.
  • Using fine-tuning mainly for changing facts. Use retrieval for knowledge that changes frequently.
  • Fine-tuning without a clear target behavior. Vague goals create vague evaluations.
  • Ignoring data quality and coverage. The model learns the examples you give it.
  • Evaluating only with loss. Inspect real outputs.

Connection To Preference Optimisation

Fine-tuning teaches the model to imitate demonstrations. But imitation is not the same as preference. Two answers can both be valid while one is clearly more helpful.

Preference optimisation teaches from comparisons, ratings, and feedback. Fine-tuning says: make this demonstrated answer more likely. Preference optimisation says: between these possible answers, people prefer this one.