AI from scratch · Fine-tuning and LoRA · Stage 6: LLM engineering
Fine-tuning and LoRA
Prompting changes what a model is asked; retrieval changes what it's told. Fine-tuning changes the model itself: more training, on your examples, so the behavior you want becomes the most likely continuation without being spelled out every time. Done naively it needs as much memory as training the model from scratch. LoRA made it cheap enough for one GPU, or a laptop for small models, by learning a thin low-rank correction instead of new weights. This lesson covers when it's the right tool, how LoRA works, what data it needs, and, from a real run, both how well it works and what it breaks.
1. Prompt, retrieve, or fine-tune?
| You need the model to… | Start with | Why |
|---|---|---|
| Know facts it wasn't trained on (your docs, today's data) | Retrieval (RAG) | Facts change; passages update instantly and can be cited. Fine-tuning stores facts poorly and can't be corrected line by line. |
| Follow a format or style every time | Prompt with examples, then fine-tune if that's not enough or too costly | Few-shot works (the using-LLMs notebook: 3/10 → 9/10), but the examples are paid for on every call. |
| Do a narrow task well with a small, cheap, fast model | Fine-tune | A fine-tuned small model often beats a prompted big one on its one task, at a fraction of the cost per call. |
| Learn a new language, domain vocabulary or skill | Fine-tune (more data, more layers) | Behavior that a few examples in a prompt can't convey. |
Retrieval adds knowledge, prompting asks for behavior, and fine-tuning bakes behavior into the weights so it no longer has to be asked for.
2. The price of changing every weight
Full fine-tuning is training: every weight gets a gradient and Adam's two averages, about 16 bytes per parameter (the GPUs lesson). For a 7-billion-parameter model that's around 112 GB before activations: several data-center GPUs. And every fine-tuned version is a full copy of the model to store and serve.
Full fine-tuning updates every weight, needing training-sized memory and a full model copy per task.
3. LoRA: learn a thin correction
LoRA (low-rank adaptation, Hu and colleagues at Microsoft, 2021) freezes the pretrained weight matrix \(W\) (size \(d_{\text{out}} \times d_{\text{in}}\)) and learns a correction that is a product of two thin matrices:
\[ W' = W + \frac{\alpha}{r}\, B A, \qquad B: d_{\text{out}} \times r, \quad A: r \times d_{\text{in}}, \quad r \ll d \]
The SVD lesson's idea, put to work: \(BA\) has rank at most \(r\), so it can only change \(W\) along \(r\) directions, and it costs \(r(d_{\text{in}} + d_{\text{out}})\) numbers instead of \(d_{\text{in}} d_{\text{out}}\). \(B\) starts at zero, so training starts from exactly the pretrained model. Only \(A\) and \(B\) get gradients and Adam states; the frozen \(W\) can even be stored in 4 bits (QLoRA).
A 4096 × 4096 attention matrix gets a rank-8 LoRA. How many trainable numbers does the adapter add?
LoRA freezes each weight matrix and learns a rank-r correction BA, two thin matrices with a tiny fraction of the numbers.
Why a low-rank correction is enough, and why B starts at zero
- Fine-tuning moves a pretrained model a short distance: it already knows language; you're adjusting a behavior.
- Measurements of how fine-tuning changes weights (Aghajanyan and colleagues, 2020, "intrinsic dimension") found that the useful change lives in a surprisingly small subspace: a few hundred directions can reach most of full fine-tuning's quality on many tasks.
- A rank-\(r\) matrix is exactly a change confined to \(r\) directions: \(BA x\) first projects \(x\) onto \(r\) directions (\(A\)), then maps them out (\(B\)). The SVD lesson showed most matrices are dominated by a few such directions anyway.
- With \(B = 0\) at the start, \(W' = W\): step 0 is the original model, and the first gradients see the real pretrained behavior. (If both started random, training would start from a randomly damaged model.)
- \(A\) still starts random, so \(B\)'s gradient \(\partial L / \partial B = (\partial L/\partial y)(Ax)^\top\) is nonzero from the first step, and training gets going.
4. Data and the loss
Fine-tuning data for a chat model is conversations: a user message and the assistant reply you want, rendered with the model's chat template (the using-LLMs lesson). Two habits matter:
- Train on the answer only. The loss is cross-entropy on next tokens (chapter 10), but only on the reply's tokens; the prompt's positions get the label −100, which PyTorch's cross-entropy skips. Otherwise the model spends its learning on predicting your users' questions.
- Quality over quantity, and variety. A few hundred to a few thousand clean, varied examples beat ten times as many sloppy or repetitive ones. Whatever's constant in the data (one phrasing, one length, one tone) is what the model learns.
Train on chat-formatted examples with the loss masked to the reply, and make the examples varied, because whatever never varies is what gets learned.
5. A real fine-tune, and what it broke
The practice notebook fine-tunes SmolLM2-135M-Instruct to pull the station and line out of service-alert sentences as JSON, with no examples in the prompt. Rank-8 LoRA on the attention's query and value matrices: 460,800 trainable numbers out of 135 million (0.34%). 80 steps of 8 generated examples, about half a minute on a laptop CPU. Each row is 30 new test sentences:
| Test | Before | After |
|---|---|---|
| Phrasings and stations like the training data | 0 / 30 | 30 / 30 |
| Stations held out of training | – | 29 / 30 |
| Held-out stations and new phrasings ("Shuttle buses replace the B near 135 St.") | – | 19 / 30 |
| "Name three boroughs of New York City." | "…Manhattan, Brooklyn, and Queens." | {"name": "New York City", "boroughs": ["New York", "Queens", "Brooklyn"]} |
The task was learned almost perfectly, and generalized to new stations. New phrasings dropped to 19 of 30: the seven training templates were the "constant" the model partly learned. And the last row is catastrophic forgetting in miniature: everything now looks like an extraction request. Fixes: mix general conversations into the training data, train less (fewer steps, smaller rank), or keep the adapter separate and switch it on only for this task. That last one is LoRA's practical superpower: one base model in memory, many small adapters (megabytes each), chosen per request.
After the fine-tune, how can the same deployed model still answer general questions normally?
- Retrain the whole model on general data
- Keep the LoRA adapter separate and apply it only to extraction requests; without it, W is the untouched original
- Add "answer normally" to the prompt
A small LoRA can learn a narrow task in seconds, and in the same seconds overwrite the model's general behavior; test both, and keep adapters switchable.
Where it breaks: what fine-tuning can't do well
- Facts. Fine-tuning on documents makes a model sound like them, not reliably recall them, and wrong "learned" facts are hard to find and remove. Facts belong in retrieval.
- The test set that looks like the training set. The 30/30 row used the same templates as training; only the new-phrasings row (19/30) says how it will do on real alerts. Always test on data generated differently from your training data (chapter 11, ML strategy's mismatch).
- Forgetting and drift. Every fine-tune trades some general ability for the task. Keep a small set of general questions and run it before and after, as you would any regression test (the next lesson).
- Too little rank, or too much. Rank 1–4 can underfit a hard task; rank 64+ on a little data overfits and forgets more. Rank 8–16 on the attention matrices is the usual start.
6. What to carry forward
- RAG for facts, prompts for quick behavior, fine-tuning for baked-in behavior and small cheap models.
- Full fine-tuning ≈ training memory (16 bytes/parameter); LoRA trains \(r(d_{\text{in}} + d_{\text{out}})\) numbers per matrix, with \(B\) starting at zero.
- QLoRA: the frozen base in 4 bits, adapters in higher precision.
- Data: chat-formatted, varied, loss on the reply only (labels −100 elsewhere).
- Test on differently generated data and on general questions; keep adapters switchable.
All lessons: AI from scratch. Papers: Hu et al., "LoRA" (2021); Dettmers et al., "QLoRA" (2023). Hugging Face's PEFT library implements LoRA for any model; the notebook writes it by hand in 6 lines.
Last updated