Supervised tuning, LoRA and training data
hard 7 minFine-tuning changes learned behavior using target examples.
Freeze the mural. Paint the change on two strips.
A conservator leaves a large tiled mural untouched and uses a tall strip and a wide strip to specify a small correction.
Video lesson · Chapter 1 of 4
An adapter in the sorting machine
Theory
Read or listen first. About 2 min.
What it is
Fine-tuning changes learned behavior using target examples. Full tuning updates the chosen model parameters, whereas low-rank adaptation leaves the base fixed and trains an additive update with fewer free parameters. Quantized-base variants trade weight storage against numerical and runtime constraints.
Why it exists
First determine whether the failure is behavioral, factual or caused by missing input. Improving a formatting rule through supervision and answering questions about a newly revised handbook are different objectives. Use held-out examples that match the intended change.
Adapt a classifier without updating every weight
Inside this chapter
Chapter sources- When to Fine-Tune
- Fine-tuning is a candidate when a stable behavior or format remains unreliable under good prompting. Frequently changing knowledge is usually cheaper to supply at request time. Establish a baseline on held-out cases first. Otherwise a training run can appear successful because the evaluation duplicates the training examples.
Fine-tuning bakes behaviour into weights, so anything you teach it is frozen until the next training run. That makes it a poor home for policies, prices or product facts, and a good home for habits: a strict format, a tone, a classification scheme. Before training, write the evaluation and record what the best prompt achieves on it. Without that baseline you cannot tell whether the adapter helped or whether the prompt alone would have done the job.
Example. A support assistant knows the policy but ignores a stable output format. Compare prompting and supervised examples before deciding to train an adapter.
Another example. An invoice extractor keeps writing dates as
3 Marchwhen the downstream parser needs2025-03-03. A few-shot prompt fixes 90% of cases on an illustrative 200-invoice holdout; an adapter is only worth training if it closes most of the remaining gap without breaking other fields.Pick the cheapest fix that targets the failure
Training is for stable behaviour such as a fixed output format, not for facts that change next week. - SFT (Supervised Fine-Tuning)
- Supervised fine-tuning updates weights using examples of a desired response to a prompt. Token-level loss rewards the target continuation. Carefully chosen negative or missing-information cases teach when to abstain. Evaluate on unseen tasks and inspect regressions in capabilities outside the target dataset.
SFT is the same next-token objective as pretraining, applied to a curated set of prompt and answer pairs, usually with the prompt positions masked out so the model is not trained to predict the user's words. The model copies whatever the targets show, including their mistakes and their habits, so a dataset with no examples of saying
I don't knowproduces a model that never abstains. Watch for regressions outside the target task: a narrow dataset can erode general instruction following.Example. Train against response targets for labeled ticket categories. Hold one customer’s entire ticket history out so paraphrases from that customer cannot leak across the split.
Another example. A routing dataset holds 3,000 tickets from 40 customers. Splitting by customer, with 6 customers held out entirely, gives a test score that reflects new customers rather than paraphrases of training tickets.
One supervised training example - 1Prompt + target answerticket text and the desired category
- 2Render chat templaterole markers exactly as at inference
- 3Mask prompt tokensloss only on the assistant answer
- 4Token-level lossnegative log probability of each target token
- 5Gradient updateweights move towards the target
The model is rewarded for reproducing the target continuation, token by token.
- PEFT & LoRA Explained
- LoRA freezes a base weight matrix and learns a low-rank update through two smaller matrices. This reduces trainable parameters and optimizer state. It does not shrink every activation or eliminate the base model. Rank, target layers and the adapter scale all affect the result.
LoRA bets that the change a task needs has low rank, so it can be written as the product of a tall thin matrix and a short wide one. A is usually initialised randomly and B at zero, so the adapter starts as an exact no-op and training grows the update from there. Because only A and B have gradients, the optimiser stores state for a small fraction of parameters, which is where most of the memory saving comes from. The base weights and the activations still need memory, and after training the update can be merged into W0 so inference costs nothing extra.
Example. For a 64 × 64 base, rank 4 adds 512 parameters, but rank 32 adds 4,096. The parameter advantage depends on the selected rank.
Another example. On a 4,096 by 4,096 projection, rank 8 trains 8 x (4,096 + 4,096) = 65,536 parameters instead of 16,777,216, about 0.4% of that matrix.
The adapter path runs beside the frozen weight
For the 64 by 64 example, rank 4 gives B with 256 entries and A with 256 entries. Only A and B are trained; alpha over r scales the update. - QLoRA (Quantized LoRA)
- QLoRA keeps a quantized base model frozen while training low-rank adapters. Computation can use a different precision from stored weights. Memory savings make adaptation feasible on smaller hardware, but sequence length, activation storage and optimizer choices still constrain the batch size.
QLoRA shrinks the frozen base to about four bits per weight and dequantises each block on the fly when a layer runs, so arithmetic happens in a 16-bit format while storage stays small. Gradients pass through the frozen weights to reach the adapter, but nothing about the base is updated. The quantised weights stop being the bottleneck, which exposes the next one: activation memory, which grows with sequence length times batch size. That is why doubling context can fail even when the weights fit easily.
Example. A run fits short sequences with the base stored at four bits. Double sequence length and remeasure peak memory before doubling the training batch.
Another example. An adapter run fits at 1,024 tokens and batch 8. At 2,048 tokens the activation memory roughly doubles, so the safe first move is batch 4 with gradient accumulation of 2, then measure peak memory.
Stored at four bits, computed at higher precision
The quantised base never receives updates. Activations for backpropagation still scale with sequence length and batch size. - Synthetic Data Generation
- Synthetic examples can broaden coverage of rare tasks or formats. Generate them from permitted source material, deduplicate them and verify labels. Split by underlying document or problem family before evaluation. Near-identical generated variants on both sides of the split exaggerate generalization.
A generator produces fluent variations, but variations of the same idea share structure and often wording, so a random split puts siblings in both train and test and the test becomes a memory check. Tag every synthetic record with its parent document or problem family and split on that tag. Labels on generated examples also need checking, because the generator can write a paraphrase whose meaning drifted from the original label.
Example. Generate ten paraphrases of one complaint. Keep all ten with the parent complaint in one split, then evaluate on independently sourced complaints.
Another example. To teach a support bot to handle rare refund disputes, generate 500 variants from 50 permitted seed cases, then evaluate on 100 real disputes from a later month that no seed came from.
Variants travel with their parent
Splitting by group keeps near-copies from appearing on both sides of the evaluation. - Training Data Preparation
- Convert training examples to the exact message template expected by the model. Check label masking, length limits, duplicate records and contradictory targets. Keep a versioned manifest of the data split. A template error can teach the model to repeat a user message instead of generating the answer.
Most silent SFT failures are data plumbing. If the mask is shifted by one span, the model trains on the user's words and learns to repeat them. If the end-of-turn token is masked out, the model never learns to stop. If the training template differs from the inference template, the model meets unfamiliar markers at serving time. Decoding a handful of fully processed records back to text, with the mask shown, catches all three in minutes.
Example. Decode one masked training record and inspect which tokens incur loss. The desired assistant answer should align with the target positions.
Another example. A manifest line such as
routing-v3: 2,940 train / 312 test, split by customer_id, template chat-v2, 18 duplicates removedlets anyone reproduce the exact run later.Decoded record: which tokens carry loss
Token span Role Loss mask Why <|system|>policy textsystem 0 context, never a target <|user|>ticket textuser 0 the model should not learn to echo it <|assistant|>marker 0 inserted by the template at inference {"category": "refund"}assistant 1 the behaviour being taught end-of-turn token assistant 1 teaches the model to stop Illustrative template markers. Use the exact template the deployed model expects.
How it works
Step through the idea, or press Play.
Labeled tickets. Train and holdout by customer
Understand it
Worked example
Adapt a classifier without updating every weight
- 1
Train and holdout by customer
Separate related tickets before sampling. Otherwise near-duplicate examples can make the adaptation appear stronger than it is.
- 2
64 × 4 and 4 × 64
For a frozen 64 by 64 projection, rank four learns two 256-parameter matrices. Their product supplies the update during the forward pass.
- 3
512 trainable vs 4,096 full
The parameter comparison applies to this one projection. Measure unseen ticket routing and abstentions before accepting the adapter.
A low-rank update
Follow the handoffs
Adapter size against rank for the 64 by 64 projection
| Rank r | B (64 x r) | A (r x 64) | Trainable total | Share of 4,096 |
|---|---|---|---|---|
| 1 | 64 | 64 | 128 | 3.1% |
| 4 | 256 | 256 | 512 | 12.5% |
| 8 | 512 | 512 | 1,024 | 25% |
| 32 | 2,048 | 2,048 | 4,096 | 100% |
Summary
The whole topic in one minute.
The missing information is current knowledge. An adapter trained on yesterday’s stale examples cannot establish what the policy says today.
First determine whether the failure is behavioral, factual or caused by missing input. Improving a formatting rule through supervision and answering questions about a newly revised handbook are different objectives. Use held-out examples that match the intended change.