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 withWhy
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 timePrompt with examples, then fine-tune if that's not enough or too costlyFew-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 modelFine-tuneA 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 skillFine-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?

\(8 \times (4096 + 4096) = 65{,}536\), against \(4096^2 \approx 16.8\) million in \(W\): 0.4%.

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
  1. Fine-tuning moves a pretrained model a short distance: it already knows language; you're adjusting a behavior.
  2. 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.
  3. 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.
  4. 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.)
  5. \(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 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:

TestBeforeAfter
Phrasings and stations like the training data0 / 3030 / 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?

\(W' = W + BA\): drop \(BA\) and you're back to the pretrained model exactly. Serving systems (vLLM, Hugging Face TGI) keep one base model and swap or batch many adapters.

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

6. What to carry forward

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