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
| Aspect | Pretraining | Fine-tuning |
|---|---|---|
| Starting point | Random weights | A pretrained model |
| Data | Huge mixture of general text | Smaller task-specific examples |
| Goal | Learn broad language patterns | Adapt behavior, format, style, or task skill |
| Loss | Next-token cross entropy | Usually the same next-token cross entropy |
| Scale | Massive and expensive | Much smaller, often repeated iteratively |
Interactive Demo
Same prompt, different behavior
This question appears in many cooking forums and has several possible answers...
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 tokens provide context. Assistant tokens are the target positions that teach the model what response to produce.
Overfitting simulator
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.
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:
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:
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:
At position , the model predicts a distribution over the next token:
The token-level negative log likelihood is:
Averaged over a full sequence, the loss is:
Concrete Token Example
If the correct next token is You and the model assigns probability , the loss is:
If it assigns probability , the loss is:
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.
If , 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 , training searches for:
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 and learns a small update :
Instead of learning every entry in , LoRA represents it as a low-rank product:
If and , the full matrix has:
The LoRA update has:
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
| Method | What changes | Strength | Limit |
|---|---|---|---|
| Full fine-tuning | Update all model parameters | Maximum flexibility | Expensive and easier to over-specialize |
| LoRA | Freeze the base model and train low-rank updates | Much cheaper; easy to store adapters | Less flexible than changing every weight |
| Prompting | Change only the input prompt | Fastest and cheapest | Can be unreliable for repeated structured behavior |
| Retrieval | Add external facts to the context | Best for changing knowledge | Does 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.
| 1 | Choose base model | Start from a pretrained model with the right size and license |
| 2 | Define target behavior | Write down what the model should do differently |
| 3 | Collect examples | Create instruction-response pairs or domain task examples |
| 4 | Format examples | Apply a prompt or chat template consistently |
| 5 | Tokenise | Convert formatted text into token IDs |
| 6 | Mask labels | Ignore context tokens and train on target response tokens |
| 7 | Train | Run next-token cross entropy with a small learning rate |
| 8 | Evaluate | Check validation loss and real model outputs |
| 9 | Inspect errors | Find missing cases, bad data, overfitting, and format failures |
| 10 | Iterate | Improve 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:
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.