Imagine you run support for a software product and you want an assistant that reads each incoming ticket and writes a reply in your company's voice, formatted as JSON that your ticketing system can parse. You try a general-purpose language model with a carefully written prompt, and it does well most of the time. Now and then it turns chatty, or wraps the JSON in an apology, or forgets a field. Fine-tuning is the next step people reach for: you keep training the model's weights, this time on a few thousand examples of exactly the replies you want. Chapter 10 explained what supervised fine-tuning (SFT), LoRA and DPO are. This chapter covers the practical side, the part that ends with a working adapter, a small set of extra trainable weights that sits on top of the frozen model.
We'll follow that one support assistant the whole way. First comes the question of whether to fine-tune at all, because most projects that start down this road probably should have stopped at a better prompt or at retrieval. If you do commit, the memory on your GPU decides how to train: mixed-precision AdamW (a standard training recipe we'll unpack) costs 16 bytes per trainable parameter, so fine-tuning every weight of a 7B model takes about 108 GB, while a rank-16 adapter on a 4-bit base model takes under 4. We'll work through where each of those bytes goes, and the same ledger will explain why adapters are cheap.
After the memory comes what the two LoRA knobs, rank and alpha, control, and why a low-rank update can be enough. Then we turn to the data, which decides the outcome far more than any hyperparameter does. You'll match the base model's chat template exactly, hold out a real evaluation set before you start, and treat falling training loss as evidence of memorisation, not of usefulness. A working Unsloth pipeline, a way of checking whether the fine-tune helped, and a look at what it quietly cost you (catastrophic forgetting) close out the chapter.
If you want one sentence for an interview, it's this: fine-tuning reliably changes how a model behaves and unreliably changes what it knows. This chapter assumes the LoRA and SFT ideas from chapter 10, but we'll restate each one in a line when we use it.
01The decision before the decision
Back to the support assistant. Its replies are sometimes off-brand and sometimes badly formatted, and before we spend GPU hours on that we should ask which of four tools fits the problem. They form a ladder, ordered from cheapest to most expensive, and the sensible habit, since most teams reach for fine-tuning a rung or two too early, is to stop at the first rung that solves your problem. At the bottom sits prompting: you write better instructions. It's free, instant and revisable in seconds, so exhaust it properly before concluding it failed. Next comes few-shot examples, where you paste a handful of ideal ticket-and-reply pairs into the prompt. That's still just prompting, it costs context window (the amount of text the model can read at once), and it often fixes format problems outright.
The third rung is retrieval, usually called RAG for retrieval-augmented generation (chapter 11). At request time you look up the relevant documents, say the current refund policy, and paste them into the prompt. It's the right answer whenever the problem is knowledge, because updating a fact means editing a document and nothing needs retraining. At the top, fine-tuning changes the weights themselves. It has the slowest loop and is the hardest to undo, and it's the only rung that reshapes the model's default behaviour.
So what does that expense buy? Four things, mostly. Fine-tuning can fix style and tone, so that every reply sounds like your organisation wrote it. It can fix format adherence, producing valid JSON in a fixed schema without a paragraph of instructions each time. It can absorb domain idiom, the way a specialist field phrases things, which prompting only mimics shallowly. And it can cut cost and latency: you teach a small model one narrow job well and stop paying for a large one. What it can't do is make a weak base model competent, rescue a poor choice of base architecture, or keep a changing fact up to date. Here are the four rungs side by side.
| Prompting | Few-shot | Retrieval | Fine-tuning | |
|---|---|---|---|---|
| Time to try a change | Seconds | Seconds | Minutes — reindex | Hours to days — retrain, then re-evaluate |
| Cost of fixing one wrong fact | Edit a sentence | Edit an example | Edit a document | Rebuild the dataset and train again |
| Can point at its source | No | No | Yes | No |
| Per-request token cost | Grows with the instruction | Grows fastest | Grows with retrieved context | Near zero — the behaviour is in the weights |
| What it fixes | Most things, if you try properly | Output format, usually | Knowledge, freshness, provenance | Default behaviour: style, format, idiom |
Read the bottom rows against the rightmost column. Fine-tuning's one real advantage over everything to its left is that the behaviour becomes the default and stops costing tokens on every call, and every other row in the table is an argument for trying a cheaper rung first.
How do you know it's a fine-tuning problem?
Three questions settle it before you write any code. First, would a perfect prompt fix this? If the support model produces the right reply when you ask carefully and fails when you ask casually, the problem is consistency, and consistency is a genuine fine-tuning case. If it can't produce the reply at all, fine-tuning won't teach it to. Second, will the right answer be different next quarter? If so, it belongs in a document. Weights give you no way to find what you baked in, no way to correct a single fact, and no citation when someone asks where an answer came from. Third, could you write two hundred examples you'd be happy to ship? If not, you don't have a dataset yet, and the run will faithfully learn whatever inconsistency you give it. You'll then read the result as a modelling failure when it was a data failure.
Not everyone draws the line in the same place. Unsloth's own fine-tuning guide argues that fine-tuning can replicate everything RAG does, since it changes the weights and RAG doesn't. That's technically defensible, because weights do store knowledge. Practitioners object on operational grounds: a fact stored in weights can't be updated without another training run, carries no citation, and gives you no way to check where an answer came from, while a fact in a document is edited in seconds and cites itself. A better rule isn't "fine-tuning can't learn facts". It's to put the parts that change in retrieval and the parts that never change in the weights.
Suppose our assistant passes all three questions: the voice and the JSON format are stable, the facts live in a help-centre database, and we have a few thousand resolved tickets. Now we have to pick a training method, and as it turns out the hardware in front of you usually picks it for you.
02Choosing the method: your VRAM decides
VRAM is the memory on the GPU itself, and training has to fit everything it needs into it at once. There are three options. In a full fine-tune every weight in the model gets updated. LoRA (low-rank adaptation, whose maths chapter 10 covers) freezes the base model and trains small adapter matrices next to it. QLoRA does the same but first stores the frozen base in 4-bit form, using quantization, which means keeping each weight in fewer bits so the model takes less room. The table compares them.
| Full fine-tune | LoRA | QLoRA | |
|---|---|---|---|
| What updates | Every weight | Small low-rank adapters, base frozen | Same adapters, on a 4-bit quantized base |
| Relative memory | Highest: weights, gradients and optimizer state for every parameter | Much lower: optimizer state only for adapter weights | Lowest: adapters plus a quantized frozen base |
| Reach for it when | You have multi-GPU budget and are changing the model deeply | The full-precision base fits comfortably in VRAM | The base only fits when quantized, which is the common case on one GPU |
| Main cost | Expensive, and you get one model per task | Slight quality gap versus full fine-tuning on some tasks | Quantizing the base adds its own small quality cost |
One property of adapters deserves attention. Because the base stays frozen, a single base model can serve many tasks by swapping small adapter files, whereas full fine-tuning leaves you with a whole separate model per task. The next diagram shows why the adapter is so small.
BA can be folded into W, so the served model has exactly the original shape and no extra latency.Look at the figure from left to right. Start with the big frozen matrix W is 4096 × 4096, or 16.8 million numbers, and LoRA leaves it alone. Beside it sit two thin matrices, B and A, whose product has the same shape as W. Only those thin matrices get trained, so gradients (the signals that tell each weight how to change) flow only through them. Adding their product to W gives the effective weight the model uses. That saving is large, but the figure leaves a question open: why does training fewer parameters shrink memory by so much more than the parameter count suggests? Section 03 answers it with arithmetic.
Before that, a short word on the starting values people use for the adapter's settings. They come from Unsloth's LoRA hyperparameters guide, and you should expect to move them. The rank r is the thin dimension in the figure. Start at 16 or 32, with common values running from 8 to 128, and know that higher rank adds capacity and also adds overfitting risk. lora_alpha is a scale factor, and the usual choice is to set it equal to r, or to 2r if you want the adapter to learn more aggressively. We'll see in section 04 what each one does. lora_dropout, which randomly switches off part of the adapter during training as a guard against overfitting, is zero by default and does little on short runs, so raise it only if you see overfitting. For target_modules, the list of layers that get adapters, use all seven linear layers of a transformer block, since omitting some saves very little memory and measurably costs quality. The learning rate, how big a step each update takes, is usually 2e-4 for LoRA and QLoRA. And train for one to three epochs, an epoch being one full pass over the dataset, because beyond three the guide reports diminishing returns and rising overfitting risk.
The fourth family: prompt and prefix tuning
LoRA isn't the only way to train a small number of parameters, and the alternatives teach something useful because they fail in an instructive direction. Prompt tuning (Lester et al., 2021) freezes the entire network and learns a short sequence of continuous vectors that gets prepended to the input embeddings. Nothing inside the model moves. In their experiments it only caught up with full model tuning at T5-XXL, which has 11B parameters. Prefix tuning (Li & Liang, 2021) learns such vectors at every layer and not only at the input, and that's why it holds up at smaller scales, and the paper reports comparable performance while training about 0.1% of the parameters.
Both spend context window at inference, and neither can be folded back into the weights, so they add latency that LoRA doesn't. They earn their place when the base model must stay literally untouched, or when you can't change the serving stack at all. For our assistant neither applies, so LoRA or QLoRA it is, and the next step is to find out which one fits on a 24 GB card.
03The memory arithmetic, line by line
Take one 24 GB card and one 7B model. Full fine-tuning needs about 108 GB before a single activation exists, while QLoRA needs under 4. Both numbers fall out of the same short ledger, and it pays to trace it once instead of memorising the conclusion. For every parameter we train, the GPU has to hold four things. There's the weight itself. There's its gradient, the number that says which way and how far the loss would change if that weight moved. And there's the optimizer state, extra bookkeeping the optimizer keeps per parameter. For AdamW, the standard optimizer, that bookkeeping is two running averages of the gradient (its first and second moments, written and ). On top of that, mixed precision training does its matrix multiplications in bf16, a 16-bit number format that takes 2 bytes per value, and keeps a separate 32-bit master copy of the weights for the updates themselves. A worked example below adds up the bytes for Llama-2-7B.
Worked example Where the 108 GB in a full 7B fine-tune actually goes
Llama-2-7B has 6,738,415,616 parameters. Assume the standard recipe: bf16 forward and backward, AdamW, no sharding. Every line is bytes per parameter.
-
Two bytes per parameter, because the matmuls run in bf16 to reach the tensor cores. This is the only line most people count, and it is an eighth of the bill.
-
One gradient per trainable parameter, in the dtype the backward pass produced it in. This line is what LoRA deletes: a frozen weight has no gradient.
-
bf16 carries seven explicit mantissa bits, so its spacing near a value is about one part in 256. Add a relative update of to a bf16 weight and it rounds back to where it was. So the optimizer keeps an fp32 copy, updates that, and casts down for the next forward pass.
-
A running first and second moment per parameter, both fp32. Four times the size of the weights they are optimising, and the single largest line in the ledger.
-
Sixteen bytes per parameter, the same accounting page 28 uses for distributed training. Adding the four rounded lines above gives 107.9 rather than 107.8 — each one rounds up, and four of those add a tenth. The exact figure is 107.81 GB. Activations are on top of this and depend on batch and sequence length.
Why does freezing the base save so much?
The payoff line in the box is the whole story. Gradients, the master copy and Adam's two moments exist only for parameters you're training, so they're priced by the number of trainable parameters, and only the bf16 weights are priced by the total. LoRA's saving doesn't come from the adapter being small in itself. It comes from three of the four lines being indexed by trainable parameters, and a rank-16 adapter makes that number about 0.6% of the model.
How small exactly? Each targeted matrix of shape gets an of shape and a of shape , so it costs parameters instead of . Summed over Llama-2-7B's seven projections and 32 layers, at , that is 40.0M.
We can have the computer run the whole ledger for five configurations of the same model. lora_params applies the formula above to every targeted matrix in every layer. In the loop, weights cost bytes_per_w per parameter of the whole model (2 for bf16, 0.5 for 4-bit), gradients cost 2 bytes per trainable parameter, and the optimizer line uses 12 bytes per trainable parameter: the 4-byte master copy plus the two 4-byte Adam moments.
Try it The whole ledger, for five configurations of the same model
# Llama-2-7B geometry, straight from its config.json.
L, H, FF = 32, 4096, 11008
BASE = 6_738_415_616 # its real parameter count
SHAPE = {"q": (H, H), "k": (H, H), "v": (H, H), "o": (H, H),
"gate": (H, FF), "up": (H, FF), "down": (FF, H)}
def lora_params(r, targets):
"""A is r x d_in, B is d_out x r, for every targeted matrix."""
return L * sum(r * (SHAPE[t][0] + SHAPE[t][1]) for t in targets)
ALL7 = list(SHAPE)
QV = ["q", "v"]
print("%-22s %9s %8s %7s %7s %8s"
% ("", "trainable", "weights", "grads", "optim", "total"))
for name, train, bytes_per_w in [
("full fine-tune bf16", BASE, 2),
("LoRA r=16, q+v", lora_params(16, QV), 2),
("LoRA r=16, all 7", lora_params(16, ALL7), 2),
("LoRA r=64, all 7", lora_params(64, ALL7), 2),
("QLoRA r=16, all 7", lora_params(16, ALL7), 0.5)]:
w = BASE * bytes_per_w / 1e9
g = train * 2 / 1e9 # bf16 gradient per trainable
o = train * 12 / 1e9 # fp32 master + Adam m + Adam v
print("%-22s %8.1fM %7.1fG %6.2fG %6.2fG %7.1fG"
% (name, train / 1e6, w, g, o, w + g + o))
print("\nactivations are on top of all of these and depend on"
"\nbatch, sequence length and gradient checkpointing.")
grads and optim columns down the rows. Full fine-tuning spends 13.48 and 80.86 GB on them. The two r=16 LoRA rows that target all seven layers spend 0.08 and 0.48 GB, and even r=64 stays under 2 GB on optimizer state, because those columns are priced by trainable parameters. Now compare weights across the last two rows: identical adapters, 13.5 against 3.4 GB, purely from quantizing the frozen base. Those are two independent levers, and QLoRA pulls both at once.The rows split into two groups. Full fine-tuning spends 13.48 GB on gradients and 80.86 GB on optimizer state, and the LoRA rows spend a small fraction of that, because those two columns are priced by trainable parameters. Look at the last two rows for the second lever. Their adapters are identical, yet the weights column drops from 13.5 to 3.4 GB purely because the frozen base is quantized. QLoRA pulls both levers at once.
The table also settles a question about rank. Going from r=16 to r=64 costs 1.7 GB, which you can afford on a 24 GB card, so the reason to keep rank low is overfitting risk and not memory. This diagram draws the same totals against one axis.
Does it fit in 24 GB?
For QLoRA the ledger prints 3.9 GB: 3.4 for the 4-bit base and 0.56 for the adapters' gradients and optimizer state. (Two small items sit outside the ledger. The adapters' own weights come to roughly 0.08 GB at 2 bytes each, and the 4-bit base carries roughly 0.1 GB of quantization constants.) What's missing is activations, the intermediate values the forward pass has to remember so the backward pass can compute gradients. They're the term people forget, and they're the one that scales with your sequence length.
With gradient checkpointing on, which stores only one hidden state per layer boundary and recomputes the rest during the backward pass, you keep GB at batch size 1. Add the logits (the model's raw output scores) and their fp32 copy for the loss, about 0.39 GB, plus the recomputation peak inside one layer, and call it 1.2 GB.
So the whole job needs about five gigabytes on a 24 GB card. That headroom is what you spend on batch size and sequence length, both of which multiply the activation term and leave the other 3.9 GB untouched. LoRA on a bf16 base comes to about 15 GB by the same arithmetic, which also fits, with far less room to grow the sequence. Memory is settled for our assistant. What remains is to understand the adapter itself, because rank and alpha are the two knobs you'll turn and they do quite different things.
04What LoRA is doing
Chapter 10 states the LoRA equation, and here it is again with each symbol spelled out. The layer's output is the original layer's output plus a scaled correction that passes the input through two thin matrices.
- W the pretrained weight, frozen: no gradient, no optimizer state, and after quantization not even full precision.
- A initialised from a Gaussian. It projects the input down to dimensions.
- B initialised to exactly zero, so at step 0 and training starts exactly at the pretrained model.
- α/r a fixed scalar that is not learned. It scales the whole update.
The zero initialisation of is a small detail with a large consequence. On the first forward pass, fine-tuning is bit-identical to the base model's, so there's no warm-up period where a random adapter degrades a working model.
Why would a low-rank update be enough?
The claim is about , the change that adapting to one task requires. itself is plainly not low rank. The rank of a matrix is the number of independent directions it uses, and a matrix of rank 3 can be written as a sum of three simple pieces however large it is. Evidence for this predates LoRA. Aghajanyan et al. (2020) measured the intrinsic dimension of fine-tuning directly: RoBERTa-Large reaches 90% of full fine-tuning performance on MRPC while optimising 200 parameters inside a random low-dimensional subspace, and 774 on QQP. That's a 355M-parameter model adapted by a few hundred numbers. LoRA's bet follows from it. If the useful update lives in a subspace that small, you can parameterise a low-rank one directly and skip the random projection.
You can watch the mechanism on a matrix small enough to take apart. This code makes a 128 × 128 "pretrained" weight W0 and a target W_task that differs from it by a rank-3 change, because U and V each have only 3 columns. Then it trains a full dense matrix on that task with ordinary gradient descent, with no low-rank constraint anywhere. Finally it takes the SVD (singular value decomposition) of W - W0. Singular values measure how much each independent direction contributes to a matrix, so a matrix that is nearly low rank shows a few large ones followed by a cliff. The energy line is the running share of the total squared singular value covered by the top few directions.
Try it Train a full weight matrix on a narrow task, then look at the spectrum of what changed
import numpy as np
rng = np.random.default_rng(0)
d, k = 128, 3
W0 = rng.normal(0, 0.05, (d, d)) # the "pretrained" weight
# The new task only exercises a k-dimensional slice of the input
# and only moves a k-dimensional slice of the output.
U = np.linalg.qr(rng.normal(size=(d, k)))[0]
V = np.linalg.qr(rng.normal(size=(d, k)))[0]
W_task = W0 + U @ rng.normal(size=(k, k)) @ V.T
W = W0.copy()
for _ in range(600): # plain full-matrix SGD
X = rng.normal(size=(64, d))
Y = X @ W_task + rng.normal(0, 0.02, (64, d)) # noisy labels
W -= 0.05 * X.T @ (X @ W - Y) / 64
s = np.linalg.svd(W - W0, compute_uv=False)
energy = np.cumsum(s ** 2) / np.sum(s ** 2)
print("delta W is a full %d x %d matrix (%d numbers)"
% (d, d, d * d))
print("its top 8 singular values:", np.round(s[:8], 3))
print("energy captured by rank 1..5:", np.round(energy[:5], 4))
print("rank needed for 99% of it:",
int(np.searchsorted(energy, 0.99)) + 1,
" -- LoRA would store %d numbers at that rank"
% (2 * d * (int(np.searchsorted(energy, 0.99)) + 1)))
0.435, then 0.009. Nothing constrained this optimisation, since it had all 16,384 entries of a dense matrix, noisy labels and ordinary gradient descent, and the update it found is still rank 3, with 768 numbers reproducing 99.98% of it. The task is rank 3 by construction, so this shows the mechanism, and the evidence for real models is Aghajanyan's measurement above.The cliff sits between the third and fourth singular values, 0.435 and then 0.009. Nothing constrained this optimisation. It had all 16,384 entries of a dense matrix, noisy labels and plain gradient descent, and the update it found is still rank 3, with 768 numbers reproducing 99.98% of it. Be clear about what this does and doesn't show. This task is rank 3 by construction, so it demonstrates the mechanism, and the evidence that real fine-tuning behaves this way is Aghajanyan's measurement above.
What r and alpha each control
The two knobs are routinely confused, including in tutorials. r is a capacity knob: it sets the rank of and therefore how many independent directions the update can move in. alpha is a multiplier and adds no capacity at all. The next snippet checks three claims: an adapter with B at zero changes nothing, the rank of the update follows r while the stored parameter count grows with it, and alpha only scales the result. Note that delta_w applies the alpha / r factor from the equation, with the same seed for both alpha values so the comparison is fair.
Try it Confirm which knob changes the rank and which one only changes the scale
import numpy as np
d = 256
W = np.random.default_rng(0).normal(0, 0.02, (d, d))
def delta_w(r, alpha, seed, zero_B=False):
g = np.random.default_rng(seed)
A = g.normal(0, 0.01, (r, d)) # Gaussian init
B = np.zeros((d, r)) if zero_B else g.normal(0, 0.01, (d, r))
return (alpha / r) * (B @ A) # the effective dW
# 1. B starts at exactly zero, so a fresh adapter is a no-op.
print("fresh adapter leaves W untouched:",
np.array_equal(W + delta_w(16, 32, 1, zero_B=True), W))
# 2. r is the capacity knob: it sets the RANK of the update.
for r in (1, 4, 16, 64):
dw = delta_w(r, 16, 2)
print("r=%-3d rank(dW)=%-3d stored %6d numbers (%5.2f%% of W)"
% (r, np.linalg.matrix_rank(dw), 2 * r * d,
100 * 2 * r * d / d ** 2))
# 3. alpha is not a capacity knob. It is a plain multiplier.
a16, a32 = delta_w(16, 16, 3), delta_w(16, 32, 3)
print("alpha=32 is exactly 2x alpha=16:", np.allclose(a32, 2 * a16))
print("same rank either way:", np.linalg.matrix_rank(a16),
np.linalg.matrix_rank(a32))
alpha=32 is exactly 2x alpha=16, at identical rank. Doubling alpha is arithmetically the same as doubling , so it acts as a learning-rate multiplier on the adapter and adds no capacity. Setting or holds the effective scale fixed as rank changes, so the learning rate survives. Note also that r=64 stores half of a 256-wide , while the same rank on a 4096-wide layer is 3.1%.The line to notice is that alpha=32 is exactly twice alpha=16 at identical rank. Doubling alpha is arithmetically the same as doubling , so it acts as a learning-rate multiplier on the adapter and not as extra capacity. That's why setting or works as a convention: it holds the effective scale fixed as rank changes, so the learning rate survives. Notice too that r=64 stores half the numbers of a 256-wide , while the same rank on a 4096-wide layer is 3.1%. Low rank only saves anything when the layers are wide.
Which layers to target
Two published findings look contradictory and aren't. The LoRA paper's ablation, at a fixed parameter budget, found that spending the budget on and beat spending it on any single projection, and that a rank as low as 1 sufficed in that setting. The QLoRA paper found that matching full fine-tuning required applying LoRA to all linear layers in the transformer block, beyond the attention projections.
They answer different questions. If the budget binds, attention's query and value projections are where it buys the most. But the ledger in section 03 shows that the budget usually doesn't bind: all seven projections at cost 0.56 GB of gradients and optimizer state on a 24 GB card. So the practical default is the second finding. Target everything, keep the rank modest, and treat the attention-only configuration as what you fall back to when memory is tight, which after section 03 it probably isn't.
Because is a matrix of exactly 's shape, it can be added into once and thrown away. Your served model then has the original architecture, the original parameter count and the original latency, which prompt and prefix tuning can't offer. Or you keep the adapter separate: a 40M-parameter adapter is roughly 80 MB in bf16, so one base model in memory can serve many tasks by swapping files. A separate adapter also means you can turn a fine-tune off, and that's the cheapest catastrophic-forgetting insurance available. We'll come back to that in section 08. With the training machinery in place, what it needs most is data.
05Data
Hyperparameters move results by a little and the dataset moves them by a lot, so budget your time accordingly. For our assistant, a supervised fine-tuning example is a conversation: the customer's ticket as the instruction, optionally a system message, and the reply you wish the model had given. Training teaches the model to predict the tokens of that reply. It's the same next-token objective from chapter 10, pointed at a much smaller and much more deliberate pile of text.
The chat template trap
Every instruct model was post-trained with a specific chat template, the exact special tokens and markers that separate system, user and assistant turns. Llama's template differs from ChatML, and ChatML differs from Gemma's. If you train with a template the base model has never seen, you teach it a new formatting convention at the same time as your actual task, and both suffer. It's probably the most common way a first fine-tune quietly underperforms.
The failure looks like a data problem, and that makes it expensive. It rambles past where it should stop, leaks role markers into its output, or ignores the system prompt at inference. People usually respond by collecting more data, and more data doesn't fix it. Matching the template does.
How much data
There is no universal minimum, and any specific number you see quoted is a rule of thumb, not a finding. Unsloth's Unsloth's datasets guide says plainly that quality and quantity together determine the result. A useful heuristic is directional. Teaching style or format needs far fewer examples than teaching a domain, because you're nudging a behaviour the model can already produce and not installing something new. Start small, evaluate, and add data only where evaluation shows a gap.
Three anchors are published results and not folklore. At the small end, LIMA (Zhou et al., 2023) fine-tuned a 65B base on exactly 1,000 hand-curated prompt-response pairs, with no RLHF at all, and reported performance competitive with models trained on vastly more. It's the strongest single piece of evidence that curation beats volume. A few hundred examples is probably enough to move tone or lock an output format, where you're steering a behaviour the base can already produce on a good day, and our assistant's voice-and-JSON job sits in that range. A genuine domain shift takes tens of thousands of examples or more, and that's also the point where the question from section 01 comes back, because retrieval may well be doing that job better.
What quality means
"Quality over quantity" is a slogan until you say what quality means, and for our tickets it comes down to six checks you can run by reading fifty examples. Every reply should be one you'd ship, because the model reproduces the average of what you give it and examples that are merely acceptable pull that average down. There should be one convention throughout: if half the replies open with a greeting and half don't, you're training a coin flip. Lengths should match the target, since response length is one of the easiest things to learn and one of the easiest to teach wrong. Prompts should look like production, because clean, well-formed instructions teach the model to expect clean, well-formed instructions, and real tickets are messy. Failure cases belong in the set too, the tickets where the right reply is "I don't know" or a refusal, or the model will learn that an answer always exists. And there should be no near-duplicates, which inflate the apparent dataset size, get memorised first, and leak across a random train/eval split.
Generating training data with a larger model is now the default, and it works. In the standard shape you prompt a frontier model for candidate replies, filter them against an explicit written rubric, then read a random sample by hand before anything trains. People skip the filter, and skipping it produces a dataset with one voice, one sentence rhythm and one way of being wrong. You then fine-tune a smaller model to imitate exactly that. You end up with a model that's fluent, plausible and strangely uniform, and no aggregate metric will tell you, because the eval set was generated the same way.
The remaining habits are unglamorous. Deduplicate before you split. Hold out a real eval set before training, and split by source or by time where you can, so near-duplicates can't straddle the split. Read fifty random examples by hand, since that finds problems no aggregate statistic surfaces. And mask the prompt: compute the loss on the reply tokens only, so the model learns to answer tickets and doesn't learn to reproduce them. We'll see the line that does this in the pipeline, which is next.
06Doing it with Unsloth
Unsloth is a drop-in optimisation layer for fine-tuning on a single GPU. It's not a new algorithm. It rewrites the model's PyTorch modules as Triton kernels (small programs that run directly on the GPU) and derives the backward pass by hand, so you run the same LoRA or QLoRA training with less memory and more speed. One property matters most and is easy to skip past: because it makes no approximations, the result is mathematically the same training you would have run anyway. You're buying throughput and giving up no accuracy.
Be careful with the measured gains you see quoted. Hugging Face's benchmark write-up reported roughly 2x speedups and large memory reductions, but it was measured against Transformers 4.36 on specific small models. Read it as directional evidence that the gains are real and not as a current spec sheet.
The pipeline, end to end
The first block loads a quantized base and attaches adapters, using the values from section 02. load_in_4bit=True is the setting that makes this QLoRA, and the model name points at a base that's already stored in 4-bit. get_peft_model adds the adapters, listing all seven linear layers as targets. The use_gradient_checkpointing line turns on the activation-saving trick from section 03.
from unsloth import FastLanguageModel
max_seq_length = 2048
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
max_seq_length = max_seq_length,
load_in_4bit = True, # QLoRA: 4-bit frozen base
dtype = None, # autodetect bf16 / fp16
)
model = FastLanguageModel.get_peft_model(
model,
r = 16,
lora_alpha = 16,
lora_dropout = 0,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
use_gradient_checkpointing = "unsloth",
)
The second block applies the chat template that matches your base model, and getting this wrong is the trap from section 05. get_chat_template installs the Llama 3.1 format on the tokenizer, and formatting_func turns each conversation in the dataset into a single string with that format applied.
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(tokenizer, chat_template = "llama-3.1")
def formatting_func(examples):
convos = examples["conversations"]
texts = [tokenizer.apply_chat_template(c, tokenize = False,
add_generation_prompt = False)
for c in convos]
return {"text": texts}
dataset = dataset.map(formatting_func, batched = True)
The third block trains. A batch size of 2 with 4 gradient accumulation steps gives an effective batch of 8 while holding only 2 examples in memory at a time. The adamw_8bit optimizer stores Adam's moments in 8 bits to save more memory. warmup_steps ramps the learning rate up over the first 10 steps. And train_on_responses_only is the prompt masking from section 05: it uses the two marker strings to find where the assistant's turn begins, so the loss is computed on that turn alone.
from trl import SFTTrainer, SFTConfig
from unsloth.chat_templates import train_on_responses_only
trainer = SFTTrainer(
model = model,
processing_class = tokenizer, # older examples call this `tokenizer=`
train_dataset = dataset,
args = SFTConfig(
dataset_text_field = "text",
max_length = max_seq_length,
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4, # effective batch size 8
num_train_epochs = 2,
learning_rate = 2e-4,
warmup_steps = 10,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
logging_steps = 1,
output_dir = "outputs",
seed = 3407,
),
)
trainer = train_on_responses_only(
trainer,
instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
)
trainer.train()
The last block saves, and the export you want depends entirely on where the model will run. Saving the adapter alone gives a small file that can be swapped against the same base. Merging folds the adapter into the base, which gives a normal model for an ordinary serving stack. GGUF is the file format that llama.cpp and Ollama read.
# Just the adapter. Small, and swappable against the same base.
model.save_pretrained("lora_model")
tokenizer.save_pretrained("lora_model")
# Adapter folded into the base, for a normal serving stack.
model.save_pretrained_merged("merged_model", tokenizer,
save_method = "merged_16bit")
# GGUF, for llama.cpp and Ollama. See page 30.
model.save_pretrained_gguf("gguf_model", tokenizer,
quantization_method = "q4_k_m")
That last export is the handoff to chapter 30, and a q4_k_m GGUF is the format most people run a fine-tune in locally. Training has now produced an adapter, but nothing so far tells us whether it's any good.
07Did it work?
Training loss going down tells you the model is fitting your data, and a model that memorises the data shows the same curve. It says nothing about whether the support assistant got better. Only one measurement counts: the same held-out eval set, scored before and after, ideally with outputs you read yourself. Set that up before training starts, because building an eval after you have a result is how you end up grading your own homework.
Why isn't a falling training loss good news on its own?
Because there are three ways a fine-tune can go wrong, and the first two look fine on the training curve. Overfitting is when training loss keeps dropping while held-out quality stalls or declines. Unsloth's guide flags training loss below roughly 0.2 as a sign of memorisation. Fix it by cutting epochs, lower the learning rate, or add data. Underfitting is the opposite: the result is barely distinguishable from the base model. Raise the learning rate, raise rank, or train longer, in that order. Third comes catastrophic forgetting, where your task improves and unrelated general ability quietly rots. It's invisible unless you deliberately test capabilities you never trained on, so keep a small general-purpose probe set and run it every time. Section 08 covers how much of it you can prevent.
Build one habit alongside the metrics. Keep base and fine-tuned outputs side by side for the same prompts, and read them. Aggregate scores hide the regressions that a human notices in ten seconds. And since forgetting is the failure that evaluation built from your own task can't see, it's the one we should look at closely.
08Catastrophic forgetting, and what helps
Your support model now answers in house style, and it has quietly stopped being able to write a Python function. Nothing in your evaluation could have told you, because your evaluation is made of support tickets. Why it happens isn't mysterious. General ability and your new behaviour ride on the same weights, and gradient descent on a narrow objective moves those weights toward whatever serves that objective. It has no term that cares what else they were doing. That makes the damage invisible by construction: every metric you built points at the task you trained on, and on that task the numbers improve.
Here's the shape of it on a model small enough to train while you read. Our network has a deliberately tight shared trunk (the layers both tasks use) with two output heads, one per task. It first learns task A, a random linear rule on 16 inputs, then learns task B, a different rule, and we measure accuracy on both after each step. The train function takes a learning rate and a trunk flag. With trunk=False only the heads move. The last variant mixes 150 task-A examples, 5% of the task-B training size, into the task-B data. That mixing is called replay, since the old task is replayed alongside the new one, and the hm array routes each example to its own head.
Try it Forget task A by learning task B — then try four ways of not doing that
import numpy as np
rng = np.random.default_rng(0)
D, HID = 16, 4 # a deliberately tight shared trunk
def task(w, n):
X = rng.normal(size=(n, D))
return X, (X @ w > 0).astype(float)
wA, wB = rng.normal(size=D), rng.normal(size=D)
XA, yA = task(wA, 3000); XB, yB = task(wB, 3000)
TA, tA = task(wA, 2000); TB, tB = task(wB, 2000)
P0 = [rng.normal(0, .3, (D, HID)), np.zeros(HID),
rng.normal(0, .3, (HID, 2)), np.zeros(2)]
def fwd(P, X):
h = np.maximum(X @ P[0] + P[1], 0) # shared trunk
return h, h @ P[2] + P[3] # two task heads
def train(P, X, y, head, steps=600, lr=.5, trunk=True):
P = [q.copy() for q in P]
i = np.arange(len(X))
for _ in range(steps):
h, z = fwd(P, X)
gz = np.zeros_like(z)
gz[i, head] = (1 / (1 + np.exp(-z[i, head])) - y) / len(X)
gh = (gz @ P[2].T) * (h > 0)
P[2] -= lr * h.T @ gz; P[3] -= lr * gz.sum(0)
if trunk:
P[0] -= lr * X.T @ gh; P[1] -= lr * gh.sum(0)
return P
def show(tag, P):
a = ((fwd(P, TA)[1][:, 0] > 0) == (tA > 0)).mean()
b = ((fwd(P, TB)[1][:, 1] > 0) == (tB > 0)).mean()
print("%-27s A=%.3f B=%.3f" % (tag, a, b))
old, new = np.zeros(3000, int), np.ones(3000, int)
P = train(P0, XA, yA, old)
show("after task A", P)
show("then task B, nothing else", train(P, XB, yB, new))
show(" same, 1/10 learning rate", train(P, XB, yB, new, lr=.05))
show(" same, trunk frozen", train(P, XB, yB, new, trunk=False))
k = 150 # 5% replay
Xm = np.vstack([XB, XA[:k]]); ym = np.r_[yB, yA[:k]]
hm = np.r_[new, np.zeros(k, int)]
show(" same, 5% task-A replay", train(P, Xm, ym, hm))
0.996 to 0.759 without the model ever seeing a task-A example, because the shared trunk moved. Freezing that trunk protects A perfectly and fails to learn B at all (0.680), and that's what over-constraining looks like. A tenth of the learning rate is worse at both than the last row. 5% replay recovers A to 0.941 and keeps B at 0.994.Read the four lines after the first as points on one tradeoff curve. Task B alone drags task A from 0.996 to 0.759 without the model ever seeing a task-A example, because the shared trunk moved. Freezing that trunk protects A perfectly and fails to learn B at all (0.680), and that's what over-constraining looks like. A tenth of the learning rate is worse at both than the last row. And 5% replay recovers A to 0.941 while keeping B at 0.994. What matters isn't any one number. Every row trades the same two quantities, the frozen trunk preserves the old behaviour and learns nothing, and training hard learns the new task perfectly and damages the old one. Replay and restraint move you along the curve and don't escape it.
What can you do about it?
There are five levers, and it helps to order them by what they cost you. Cheapest is to train less: fewer epochs, a lower learning rate, and early stopping judged on a general probe and not on training loss. This is the most common real fix and it's free, because most forgetting comes from runs that went on too long. Next comes constraining what can move. LoRA is already this, since the base is untouched and the update is confined to rank per matrix, and lowering rank and targeting fewer modules moves less of the model, at the cost of how much your task can change. Then comes replay, as in the demo, where mixing a few percent of general instruction data into the fine-tuning set recovered most of what was lost at no cost to the new task.
Two more levers cost almost nothing. Don't merge the adapter. Keep it as a separate file and the base model is still there, unchanged, one flag away, so you can serve both, compare them on the same prompts, and roll back in seconds. And measure deliberately: keep a small fixed probe set of capabilities you never trained on, such as code, arithmetic, a different language and instruction following, and run it at every checkpoint. Forgetting you can't see is forgetting you'll ship. So the honest question isn't how to avoid forgetting. It's how much general ability this behaviour is worth, and whether you've measured what you gave up.
09Where you meet this in the wild
The pattern across real uses is the same one our support assistant showed: fine-tuning wins where the requirement is a consistent behaviour that would otherwise cost a long prompt on every single call. Take structured output first. A small model fine-tuned on a few thousand schema-conforming examples will emit that schema more reliably than a large model told to, and you stop paying for the instruction tokens on every request. A close cousin is cost reduction, the common production pattern. You use a frontier model to generate and curate training data for one narrow task, fine-tune something much smaller on it, then serve the small one, and latency and cost both drop sharply.
In regulated writing, legal, medical and financial text has conventions that prompting approximates and fine-tuning internalises. Facts still belong in retrieval and phrasing belongs in the weights. Classification is a labelling job wearing a chat interface: routing tickets, tagging content, triaging intent. A fine-tuned small model often beats a prompted large one on both accuracy and cost, and maybe a plain classifier beats both, so check that first. And for on-device use, where memory has a hard ceiling, you fine-tune a small model on one job, export it to GGUF, and run it locally with no API call and no data leaving the machine. Chapter 30 covers what fits.
The mirror image is when to look elsewhere. Reach for fine-tuning when you need consistent behaviour that prompting produces only sometimes, when a long instruction preamble on every call has become a recurring bill, when you want a smaller model to do one job as well as a larger one does it generally, when the target is style, format or idiom, and when you have or can generate consistent examples. Look elsewhere when the problem is missing or changing facts, and that's a retrieval problem. Look elsewhere too if you haven't exhausted prompting, since many reported fine-tuning wins were probably available from a better prompt. Likewise when you need citations or provenance, because weights can't tell you where an answer came from. Small, inconsistent or unread data is another reason, since you'll train the model on your inconsistency. And if the base model isn't good enough, fine-tuning shapes competence and doesn't manufacture it.
10Summary
- Fine-tune last, not first. Prompting, few-shot examples and retrieval are cheaper rungs, and the three questions in section 01 (would a perfect prompt fix it, will the answer change next quarter, do you have two hundred examples you'd ship) decide whether you've earned the top one.
- Fine-tuning changes behaviour more reliably than knowledge. Put the parts that change in retrieval and the parts that never change, such as style, format and idiom, in the weights.
- Your VRAM picks the method. Full fine-tuning updates every weight, LoRA trains small adapters on a frozen base, and QLoRA does that on a 4-bit base, the common case on one consumer GPU.
- Mixed-precision AdamW costs 16 bytes per trainable parameter. That's 2 for the bf16 weight, 2 for the gradient, 4 for the fp32 master copy and 8 for Adam's two moments, so a full 7B fine-tune is about 107.8 GB before activations.
- LoRA's saving comes from what's frozen. Three of the four lines are priced by trainable parameters, and a rank-16 adapter on all seven projections trains about 40.0M parameters, roughly 0.6% of the model. QLoRA also shrinks the weights line, which brings the states to about 3.9 GB.
- Rank is capacity and alpha is a multiplier. The update has rank at most , and doubling alpha doubles the update without adding capacity. Setting or keeps the scale steady as rank changes.
- A low-rank update is enough because the change a task needs is small. Aghajanyan et al. found hundreds of parameters sufficient for 90% of full fine-tuning performance, and the zero-initialised means training starts exactly at the base model.
- The dataset decides the outcome. Match the base model's chat template, mask the prompt, deduplicate, keep one convention and read fifty examples by hand. A thousand curated examples (LIMA) can go a long way, and style or format needs far fewer than a new domain.
- Falling training loss proves nothing yet. Score a held-out set before and after, read base and fine-tuned outputs side by side, and treat training loss below about 0.2 as a memorisation warning.
- Forgetting is invisible to task metrics and has no free fix. Train less, constrain what moves, replay a few percent of general data, keep the adapter unmerged, and run a probe set of untrained capabilities at every checkpoint.
11Interview questions
BeginnerWhen would you fine-tune instead of using RAG?
Fine-tune when the gap is behavioural: style, tone, output format, or a domain's idiom that prompting only approximates. Use RAG when the gap is knowledge, especially knowledge that changes or needs to be cited. The operational argument is decisive. A fact in a document is updated by editing the document; a fact in the weights requires another training run and still gives you no provenance. The two compose well, and a common production shape is a fine-tuned model that formats and reasons over retrieved context.
BeginnerWhat is the practical difference between LoRA and QLoRA?
LoRA freezes the base model and trains small low-rank adapter matrices, so optimizer state only exists for the adapters. QLoRA does the same thing but quantizes the frozen base to 4-bit first, which cuts the memory needed to merely hold the base. The distinction matters when the full-precision base does not fit in your VRAM at all. QLoRA is what makes fine-tuning a mid-sized model feasible on a single consumer GPU, at the cost of a small quality hit from quantizing the base.
IntermediateYour fine-tuned model rambles and leaks role markers like "assistant" into its output. What went wrong?
Almost certainly a chat template mismatch. Every instruct model is post-trained with a specific set of special tokens delimiting system, user and assistant turns. If you format training data with a different template, the model is simultaneously learning a new formatting convention and your task, and it does neither cleanly. The symptoms are exactly this: failing to stop in the right place, and emitting role markers as ordinary text. The fix is to apply the base model's own template, not to collect more data.
IntermediateWhy mask the instruction tokens during SFT?
If loss is computed over the whole sequence, the model spends capacity learning to predict your prompts as well as the responses. You do not want a model that is good at generating user questions. Masking the instruction portion, which Unsloth exposes as train_on_responses_only, restricts the loss to assistant tokens so all the gradient signal goes toward producing better answers. It matters most when prompts are long relative to responses, since otherwise most of the loss is being spent on text you will never need generated.
IntermediateTraining loss dropped steadily. Is the fine-tune working?
Unknown, and the question is a trap. Falling training loss shows the model is fitting the training set, which is also exactly what memorisation looks like. The measurement that matters is held-out performance, scored before and after on a set you split off before training. Unsloth's guide treats training loss below roughly 0.2 as a memorisation warning rather than a success signal. You should also probe capabilities you never trained on, because catastrophic forgetting is invisible to any metric computed only on your task.
IntermediateWhy does a full 7B fine-tune need over 100GB when QLoRA fits on a 24GB card?
Count bytes per parameter under mixed-precision AdamW. Two for the bf16 weights, two for the gradients, four for the fp32 master copy the optimizer updates — bf16 has too few mantissa bits to absorb small updates — and four each for Adam's first and second moments. Sixteen bytes per parameter, so 6.74 billion parameters is 107.8 GB before a single activation. The key structural fact is that only the first of those four lines is indexed by total parameters; the other twelve bytes are per trainable parameter. Freezing the base and training a rank-16 adapter across all seven projections leaves about 40M trainable parameters, roughly 0.6% of the model, so gradients and optimizer state collapse from 94 GB to about half a gigabyte. That still leaves 13.5 GB of frozen weights, which is what the 4-bit quantization in QLoRA attacks, taking it to about 3.4 GB. Total states under 4 GB, plus roughly 1 GB of activations at sequence 2048 with gradient checkpointing.
IntermediateWhat do rank and alpha control in LoRA, and which modules should you target?
The update is ΔW = (α/r)·BA, added to a frozen W. Rank r is the capacity knob: it is literally the rank of ΔW, so it sets how many independent directions the update can move in, and it determines the parameter count, r(d_in + d_out) per matrix. Alpha is not capacity — it is a plain scalar multiplier, so doubling alpha is arithmetically identical to doubling B, and it behaves like a learning-rate multiplier on the adapter. The convention of setting α = r or 2r keeps the effective scale α/r constant as you vary rank, so you do not re-tune the learning rate every time. On modules: the LoRA paper's ablation, at a fixed parameter budget, found query and value projections the best place to spend it. The QLoRA paper found that matching full fine-tuning required all linear layers. Those answer different questions, and since all seven projections at r=16 cost well under a gigabyte of optimizer state, the budget is usually not the binding constraint — so target everything and keep the rank modest.
DeepHow would you detect catastrophic forgetting, and what actually mitigates it?
You cannot detect it with your task metrics, because by construction they only measure the thing you trained on, and that improves. Detection requires a deliberate probe: a small fixed set of capabilities you never trained on — code, arithmetic, a second language, plain instruction following — scored at every checkpoint against the base model's own scores on the same set. Mitigations, cheapest first: train less, since most forgetting comes from too many epochs or too high a learning rate, with early stopping judged on the probe rather than on training loss. Then constrain what can move — LoRA at a modest rank is exactly that, since the base is frozen and the update is rank-limited per matrix. Then replay: mixing a few percent of general instruction data into the fine-tuning set recovers most of the loss for almost no cost to the new task. And keep the adapter unmerged, so the unchanged base is one flag away and you can roll back or A/B in seconds. None of these is free. Freezing enough to protect the old behaviour perfectly also prevents learning the new one, so the real question is how much general ability the behaviour is worth, and whether you measured what you gave up.
DeepYou have one 24GB GPU and need a customer-support model in a specialised domain. Walk through your plan.
Start by not fine-tuning. Establish a prompted baseline with retrieval over the support corpus, and measure it, because that may be the whole answer and it is the cheapest thing to maintain. Assume it leaves a gap in tone and format consistency rather than in knowledge, since knowledge is what retrieval already handles.
Then: pick a small instruct base that fits in 24GB when 4-bit quantized, so QLoRA rather than LoRA. Build a few thousand curated examples from real resolved tickets, deduplicated, with a held-out split made by time so near-duplicates cannot leak across it. Apply the base model's own chat template and mask instruction tokens. Start at rank 16, alpha 16, learning rate 2e-4, two epochs, targeting all seven linear modules.
Evaluate against the prompted baseline on held-out tickets, reading outputs rather than only scoring them, and separately probe general ability to catch forgetting. Keep retrieval in the final system regardless: the fine-tune supplies the voice and the format, retrieval supplies the facts and the citations.
12Go deeper
●Now write it yourself
Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.
Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.