Fine-Tuning
LoRA and QLoRA, the decision framework, data pitfalls and serving adapters.
Fine-tuning is the most misunderstood tool in this part of the guide. It is often reached for first, to “teach the model our data”, which is the job it does worst. It is often dismissed as too expensive, when a useful fine-tune of an open model fits on one GPU. This chapter is about what it changes, what it costs, when it pays, and how it goes wrong.
Chapter 9 covered the theory, with experiments on forgetting and reward hacking. The experiments here are the practical ones: low-rank adapters at several sizes, how much data is enough, what bad data does, and what quantizing the base model costs. All run on the transformer from Chapter 7 and the word-capitalizing task from Chapter 9.
17.1What fine-tuning is
Continued training that changes behavior, not a way to load facts.
Fine-tuning takes a pretrained model and keeps training it, with the same next-token loss, on your own pairs of input and desired output. Gradient descent adjusts the weights until your pattern is the likely continuation, with no need for the prompt to carry it.
| Where the pattern lives | What you pay | How fast it changes | |
|---|---|---|---|
| Prompting | In the context | Tokens on every request | Instantly |
| Fine-tuning | In the weights | A training run, then nothing per request | Only by retraining |
The distinction that settles most decisions is behavior versus knowledge. Fine-tuning is good at behavior: output format, tone, the shorthand of a field, when and how to call a tool. It is unreliable for knowledge. Section 9.3 measured this: a model fine-tuned to name the speaker of a line learned the answer format perfectly and the answers not at all.
The pattern recurs in practice. A team fine-tunes on five hundred product questions and answers. The demonstration is impressive, because it uses those questions. Real users phrase things differently and receive confident inventions. Then the documentation changes, and the weights are out of date. The task wanted retrieval (Chapter 15).
Common take“Fine-tune it on our data so that it knows our business.”
Sharper take“Fine-tuning changes how a model behaves and retrieval changes what it knows. I often ship both: a tuned model answering over retrieved facts.”
17.2The memory wall
Why training needs eight times the memory of serving.
Section 3.4 counted what training holds in memory for every weight: the weight, its gradient, and the optimizer’s two running statistics. With mixed precision that comes to about 16 bytes per parameter, before activations.
| Model | Serving at 16 bits | Full fine-tuning |
|---|---|---|
| 8B parameters | 16 GB | About 128 GB: more than one 80 GB GPU holds |
| 70B parameters | 140 GB | About 1.1 TB: fourteen or more such GPUs for the training state alone |
- weights
- gradients
- optimizer state and master copy
- adapter training state
The bottleneck is not the time the computation takes. It is that gradients and optimizer state exist for every trainable weight. Make fewer weights trainable and most of that tower disappears. That is the idea behind every parameter-efficient method.
Common take“If we can run the model, we can fine-tune it.”
Sharper take“Full fine-tuning needs about eight times the memory of serving, because every trainable weight carries a gradient and optimizer state. The practical question is how few weights I can train.”
17.3LoRA
Freeze the model and train small low-rank patches.
LoRA, low-rank adaptation, leaves every original weight frozen and adds a small trainable detour beside each weight matrix. The count is what makes it cheap. For one 4,096 × 4,096 matrix with rank r = 16, full fine-tuning trains 16.8 million numbers and the adapter trains 131,000, under 1%. Across an 8B model the trainable total is in the tens of millions, and its optimizer state drops from 128 GB to well under one.
In code it is one line added to each layer. This is the version used in the experiment below:
def lin(x, name, bias=None):
out = mt.linear(x, P[name], bias) # the frozen weight: W x
if name + '.A' in A: # the patch: scale * B A x
out = mt.add(out, scale_op(mt.linear(mt.linear(x, A[name + '.A']), A[name + '.B']), scale))
return outThe figure at the top of the chapter is the result. The base model has 161,920 weights, and the task is capitalizing words it has not seen.
| Method | Weights trained | Share of the model | Accuracy on unseen words | Size of the patch |
|---|---|---|---|---|
| Full fine-tuning | 161,920 | 100% | 99.5% | 632 KB (a whole new model) |
| LoRA, rank 1, on every weight matrix | 3,456 | 2.1% | 16% | 14 KB |
| LoRA, rank 2, on every weight matrix | 6,912 | 4.3% | 81.5% | 27 KB |
| LoRA, rank 4, on every weight matrix | 13,824 | 8.5% | 98% | 54 KB |
| LoRA, rank 8, on every weight matrix | 27,648 | 17.1% | 98% | 108 KB |
| LoRA, rank 8, on two attention matrices only | 6,144 | 3.8% | 88% | 24 KB |
Three readings. Rank 4, training 9% of the weights, reached 98%, against 99.5% for retraining everything. Below that the patch was too narrow for the task within the same number of steps: rank 1 reached 16%. And where the patches go is a choice with consequences: rank 8 on only two of the attention matrices reached 88% with 6,144 weights, ahead of rank 2 on every matrix (82% with 6,912) and well behind rank 4 on every matrix.
On a model this small the fractions are large, because a rank of 4 is not small beside a width of 64. On a model with a width of 4,096 the same ranks are a fraction of a percent, which is why the method matters at scale. Three consequences follow in practice.
- The artifact is small. The adapters here are 14 to 108 KB beside a 632 KB model. For real models they are tens of megabytes beside tens of gigabytes: cheap to store, version and ship.
- Merge or swap. The patch can be added into the weights, leaving no cost at inference, or kept separate and switched per request (section 17.9).
- An adapter belongs to one base model. It was learned as a change to particular weights. On a different version of the base it is noise.
Common take“LoRA is a cheaper, lower-quality fine-tune.”
Sharper take“LoRA trains a low-rank change to frozen weights. With enough rank for the task it came within a point and a half of full fine-tuning here, training under a tenth as many weights. I choose the rank against an evaluation, not by habit.”
17.4QLoRA and quantization
Compress the frozen base, and learn what compression costs.
LoRA shrinks the trainable part. The frozen base still has to sit in memory. QLoRA observes that a frozen model is read-only during training, so it can be stored compressed, at 4 bits per weight in place of 16. An 8B model drops from 16 GB to about 5 GB and a 70B model from 140 GB to under 40 GB, which brings fine-tuning of large open models within reach of a single GPU.
Compression is not free, and it is worth seeing how unfree. I rounded the weights of the Chapter 7 model to fewer and fewer bits, with the simplest possible scheme, and measured its loss on ordinary text.
| Bits per weight | Loss on ordinary text |
|---|---|
| 32 (as trained) | 1.69 |
| 8 | 1.69 |
| 6 | 1.72 |
| 4 | 2.28 |
| 3 | 3.87 |
| 2 | 4.58 |
Eight bits changed nothing. Six bits cost almost nothing. At four bits, plain rounding did real damage, and below that the model was destroyed. That is why practical 4-bit schemes are more careful than plain rounding: QLoRA’s format places its sixteen levels where weights are densest, following their bell-shaped distribution, and uses a separate scale for each small block of weights. Larger models also tolerate rounding better than this tiny one, since they have more redundancy.
The honest summary: QLoRA changed who can fine-tune a large model, from a lab with a cluster to an engineer with one GPU. It did not change whether you should.
Common take“We’ll quantize to 4 bits. It’s the same model, only smaller.”
Sharper take“It’s an approximation of the model. With careful 4-bit formats the cost is usually small, and I confirm that on my own evaluation, because with naive rounding this model’s loss went from 1.69 to 2.28.”
17.5The decision
Prompt, then retrieval, then fine-tuning, with a test at each step.
1. PROMPT, with examples and a schema hours to change, nothing to run
test: has the prompt reached its ceiling on the labeled set?
2. RETRIEVAL if the gap is knowledge
test: is retrieval fine and behavior still wrong?
3. FINE-TUNING if the gap is behavior, at scale
test: still below target?
4. A STRONGER MODEL or reasoning setting if the gap is capabilityThis is the ladder from section 13.10 with its gates. Fine-tuning is the third rung, and there are four situations in which it earns its place.
| Case | How it wins | Example |
|---|---|---|
| Distillation for cost and speed | A large model writes thousands of example outputs; a small model is tuned on them and matches it on that narrow task for a fraction of the price | A high-volume classifier, extractor or summarizer |
| Style at scale | Thousands of tokens of rules and examples still drift; tuning moves the pattern into the weights and shrinks the prompt to a line | A brand voice; house document formats |
| The dialect of a field | The model misreads specialized shorthand | Structuring clinical notes; parsing logs |
| Reliable structure on a small model | A small tuned model follows your exact schemas as well as a large prompted one | A high-volume router that emits tool calls |
The first case is the most common in production. Check the terms of the model whose outputs you train on, since some providers restrict using them to train competing models.
And the cases where it does not pay: facts, anything that changes weekly, low traffic, where the engineering time is never recovered, and the non-reason that “we have data lying around”.
Common take“We have 50,000 support transcripts, so let’s fine-tune.”
Sharper take“Having data is not a reason. I ask which gap I’m closing. If it’s knowledge, I retrieve. If it’s behavior that prompting can’t hold at our volume, I fine-tune, and I can say which of the four cases it is.”
17.6Data preparation
Where fine-tunes fail.
Fine-tuning projects fail in the dataset far more often than in the training loop. A model imitates everything in its training data, flaws included. Three of the classic failures can be shown on the small model.
Too little data. How many examples does the capitalizing task need?
Missing coverage. I removed every training word that contains k, v or w, leaving 961 words, and fine-tuned as before.
| Test words | How many | Capitalized correctly |
|---|---|---|
| Made only of letters seen in training | 148 | 99.3% |
| Containing k, v or w | 52 | 0% |
Its answers for four of them: “bawdy” became BARDY, “jewel” became JEREL, “kneel” became DNEEL, “smock” became SMOCZ.
The model was nearly perfect on words made of letters it had practiced and wrong on every single word containing a letter it had not. Its errors are instructive: it replaced the unseen letter with a seen one. A fine-tuned model is exactly as broad as its data.
No end marker. Each training answer normally ends with a line break, which teaches the model where to stop. I trained once with it and once without.
| Training answers | Stops after the answer | First five letters correct | Output for “rings” |
|---|---|---|---|
| End with a line break | 100% | 99.5% | RINGS, then stops |
| Have no end marker | 0% | 97% | RINGSSSERNNGGG and on |
Without the end marker in training, the answer was still right, and the model then kept writing, every time. This is one of the most recognizable fine-tuning failures in practice.
The full list, with what each looks like later:
| Failure | Mechanism | Symptom |
|---|---|---|
| Chat-template mismatch | Training text is formatted with different role markers from the base model’s (section 6.8) | The tuned model emits role tags, or is inexplicably worse than the base |
| Missing end marker | The model never sees where an answer stops | Outputs run on, as above |
| Loss on the prompt | The loss also counts the input tokens, diluting the signal | Slow learning; the model sometimes repeats instructions back |
| Narrow data | Thousands of examples in a few shapes | Excellent on inputs like the training set, brittle elsewhere, as above |
| Leakage | Test examples, or near-copies of them, are in the training set | Scores that collapse on real traffic |
| Noisy labels | Inconsistent or wrong target outputs | The model reproduces the inconsistency faithfully |
A few hundred to a few thousand clean, varied examples usually beat tens of thousands of scraped ones. Before any training run, print a handful of examples exactly as the model will see them, tokens and all, and read them.
Common take“The loss went down, so the fine-tune worked.”
Sharper take“The loss says the model fits the training data. I read tokenized examples before training, check coverage and end markers, and test on inputs that were not in the set.”
17.7Forgetting and evaluation
Measure what you gained and what you lost.
Section 9.4 showed that fine-tuning overwrites old abilities. The capitalizing task shows it again, and shows what an adapter does about it.
| Model | Accuracy on the new task | Loss on ordinary text |
|---|---|---|
| The original model | 0% | 1.69 |
| After full fine-tuning | 99.5% | 9.42 |
| Rank-4 adapter applied | 98% | 6.88 |
| Rank-4 adapter switched off | 0% | 1.69 |
Full fine-tuning left the model unable to do what it was pretrained for: its loss on ordinary text went from 1.69 to 9.42, more than twice the loss of guessing uniformly. With the adapter applied, ordinary text suffers too. The difference is that the adapter can be switched off, and the base model underneath is untouched, bit for bit. Full fine-tuning has no such switch.
For that reason every fine-tune should be judged on two panels, before and after.
- The target panel: held-out examples of the new task, including rephrasings and edge cases.
- The regression panel: a sample of everything else the model must still do, such as general questions, other formats, refusals and tool calls.
Ship when the first has improved and the second has not fallen. Section 9.4 listed the ways to protect the second: mixed-in general data, a lower learning rate, fewer passes, adapters.
Common take“The fine-tuned model scores 98% on our task. Ship it.”
Sharper take“What does it score on everything else? I run a regression panel beside the target panel. Here the same model that reached 99.5% on the task lost its original ability completely.”
17.8Hosted or self-run
The hosted options have narrowed.
There are two ways to fine-tune: ask a provider to tune one of its models for you, or tune open weights yourself. As of November 2026 the first route is narrower than it was.
| Route | Status in late 2026 |
|---|---|
| OpenAI models | Being wound down in stages since May 2026: new organizations can no longer start jobs, and existing customers lose the ability to create new ones in January 2027. Existing fine-tunes keep serving until their base model is retired |
| Claude models | Not offered on Anthropic’s own API. The one managed route, Claude 3 Haiku on Amazon Bedrock, ended when that model reached end of life in September 2026 |
| Gemini models | Supervised, preference and reinforcement tuning are offered through Google’s cloud platform |
| Open-weight models | Managed tuning on several cloud and inference platforms, or your own GPUs with open-source tools |
Check the current state before planning around any row; this table will date quickly. The trade-offs last longer.
| Hosted tuning of a provider’s model | Tuning open weights | |
|---|---|---|
| Effort | Upload examples, wait | You run training, or pay a platform to |
| The result | A private model identifier. You cannot download the weights | An adapter file that you own and can move |
| If the provider retires the base model or the service | Your tuned model goes with it | Nothing changes |
| Control | A few settings | Everything: rank, targets, data mixing, evaluation during training |
| Serving | The provider’s, often at a higher price per token | Yours to arrange (Chapter 29) |
The middle rows are the ones this year made concrete. A fine-tune is an investment in data, evaluation and training runs, and with a hosted model that investment is tied to a service you do not control. Keep the dataset and the evaluation panels in your own hands whichever route you take, since they are what lets you rebuild elsewhere.
Common take“We’ll fine-tune through the API. It’s the easy option.”
Sharper take“It’s easy to start. I also ask what I own at the end and what happens if the base model is retired. The dataset and the evaluation are the durable assets, so those stay with me.”
17.9Serving adapters
One base model, many small patches.
Because an adapter is small and separate from its base, one copy of the base model in memory can serve many fine-tunes. The server loads the base once, keeps a library of adapters, and applies the right one to each request: one per customer, per task or per language. Adding a fine-tune costs megabytes, where a separate deployment of a fully tuned model would cost a GPU.
| Choice | When | Cost |
|---|---|---|
| Merge the adapter into the weights | One fine-tune per deployment | No overhead at inference; the base is no longer shared |
| Keep adapters separate and switch per request | Many fine-tunes on one base | A small overhead per request; batching across different adapters is harder |
Two rules keep this workable. Version adapters together with the exact base they were trained on, since an adapter on the wrong base is noise (section 17.3). And evaluate each adapter separately, because a shared base means a change to the base is a change to every fine-tune at once.
Common take“Each customer’s fine-tuned model needs its own deployment.”
Sharper take“Each customer needs its own adapter. One base model in memory serves all of them, and I track which base version every adapter was trained on.”
17.10Beyond supervised
Preferences, rewards, and tuning retrievers.
Everything above assumed examples of the right output. Three other kinds of fine-tuning are in practical use.
- Preference tuning. When you can say which of two outputs is better and not what the ideal output is, methods such as DPO train on pairs (section 9.5). In practice: gather pairs from real usage, such as an answer a user accepted against one they rejected, keep the learning rate low, and watch the regression panel, since preference tuning forgets like any other.
- Reinforcement fine-tuning. When outputs can be scored by a program or a grader model, the model can be tuned toward a higher score with no reference outputs at all (section 9.6). It is powerful for tasks with checkable answers and carries the hazard that section showed: the model optimizes the grader, loopholes included. Audit high-scoring samples by reading them.
- Tuning the retriever. In a retrieval system, the model most worth tuning is often not the language model. An embedding model fine-tuned on your queries and passages, or a reranker tuned on your judgments of relevance, lifts the ceiling that section 14.10 described, and both are small and cheap to train (section 14.9).
Common take“Fine-tuning means training the chat model on question–answer pairs.”
Sharper take“That’s one kind. If I have comparisons, I tune on preferences. If I have a checker, I can tune on rewards, carefully. And in a retrieval system I look at tuning the embedder or reranker first, because that’s where the ceiling is.”
Key takeaways
- Fine-tuning is continued training on your examples. It changes behavior well and stores facts badly.
- Full fine-tuning needs about 16 bytes per parameter, eight times the memory of serving, because every trainable weight carries a gradient and optimizer state.
- LoRA freezes the model and trains small low-rank patches. A rank-4 patch on 9% of the weights reached 98%, against 99.5% for retraining all of them; rank 1 reached 16%.
- An adapter belongs to one base model. On another version it is noise.
- QLoRA stores the frozen base at 4 bits. Compression has a cost: with naive rounding, 8 bits cost nothing and 4 bits raised this model’s loss from 1.69 to 2.28.
- Climb in order: prompt, retrieval, fine-tuning, stronger model, with a test at each step.
- Fine-tunes fail in the data: 32 examples taught nothing, words with unseen letters scored 0%, and without an end marker the model never stopped.
- Judge every fine-tune on a target panel and a regression panel. Full fine-tuning took the original task’s loss from 1.69 to 9.42.
- With hosted fine-tuning you do not own the weights. Keep the dataset and the evaluation, which let you rebuild.
- One base model can serve many adapters, and the retriever is often the model most worth tuning.
Check your understanding
-
A team fine-tunes a model on 500 questions and answers about its products. Internal testing with those questions is near-perfect. In production, customers get confident wrong answers, and after a pricing change the model still quotes old prices. Explain both problems and propose a design.
Answer outline
The model memorized 500 question-and-answer strings. It did not acquire the facts in a form that survives rephrasing, so differently worded questions get plausible inventions; testing on the training questions hid this, which is leakage. And facts in weights go stale the moment the source changes. Design: answer from retrieved documentation, so that facts come from the current source and can be cited; fine-tune, if at all, only for tone and format; and evaluate on rephrased questions that were never in any training set.
-
After fine-tuning an open model on your own chat data, the model’s replies never end: it answers correctly and then continues, often writing the user’s next message itself. Name the two most likely causes and how you would confirm each.
Answer outline
Either the training targets lacked the end-of-turn token, so the model never learned where a reply stops, as in the experiment where every output ran on; or the training text used a different chat template from the base model, so the markers it learned are not the ones the server stops on. Confirm by printing a few training examples exactly as tokenized: check that each assistant turn ends with the base model’s end-of-turn token and that role markers match the base model’s template. Then check that the server treats that token as a stop condition.
-
You serve one adapter per customer on a shared base model. The platform team proposes moving to a newer version of the base for its better general quality. What breaks, and what is the migration plan?
Answer outline
Every adapter was learned as a change to the old base’s weights and will produce poor output on the new one. Plan: keep the old base serving; retrain each adapter on the new base from the stored datasets; run each customer’s target and regression panels on the new pair; move customers one at a time, with the ability to switch back; retire the old base only when every adapter has passed. The plan depends on having kept each customer’s training data and evaluation set, which is the argument for treating those as the durable assets.
Further reading
- Chip Huyen, AI Engineering, chapter 7: when to fine-tune, and the parameter-efficient methods.
- Sebastian Raschka, Build a Large Language Model (From Scratch), chapters 6 and 7 and appendix E: fine-tuning for classification and for instructions, and LoRA in code.
- Jay Alammar and Maarten Grootendorst, Hands-On Large Language Models, chapter 12: fine-tuning generation models.
- Hu et al. (2021), “LoRA”, and Dettmers et al. (2023), “QLoRA”: the two papers behind sections 17.3 and 17.4.