Project: fine-tune a model with LoRA¶
You will teach a real 494-million-parameter instruction model a narrow skill, turning messy expense messages into exact JSON, by training 1.8% of its parameters with LoRA, and you will prove it worked with a held-out test set you built before training began. The idea to walk away with: fine-tuning is an experiment, and the evaluation, not the training script, is the product.
10,000 ft
A pre-trained model already knows language and a great deal about the world; post-training shapes how it uses that knowledge. Supervised fine-tuning (SFT) is the simplest shaping tool, and LoRA makes it cheap: freeze every pre-trained weight and learn a low-rank correction beside each matrix. That combination is how most teams in 2026 specialise open models for extraction, classification, tone, tool-call formats and domain vocabulary, and the same adapters carry over to preference optimisation and RL. It sits on the third rung of the project ladder: after building a model from nothing (tiny GPT), you now adapt someone else's, and the hard part moves from the architecture to the data and the evaluation.
2,000 ft
Pick a task with an automatic metric. Build a held-out test set that differs from training in ways that matter (new phrasings, new entities), and measure the base model on it with zero-shot and few-shot prompts: that is the bar. Generate or collect training data in the model's chat format, with the loss on the answer tokens only. Wrap every linear layer with a rank-\(r\) adapter \(W_0 + \tfrac{\alpha}{r}BA\), with \(B = 0\) so training starts from exactly the base model. Train for a few hundred steps at about ten times the learning rate you would use for full fine-tuning. Re-run the same test, read the failures, fix the data, and only then merge and ship the adapter.
Ground level¶
What you are building, and the rules¶
The task. Turn a free-text expense message into JSON with four fields:
"Settled INR 24,262 with Decathlon last night"
-> {"amount": 24262, "currency": "INR", "category": "shopping", "merchant": "Decathlon"}
It is a good first fine-tuning task for three reasons. The metric is exact and automatic (the JSON matches or it does not). It mixes format (always valid JSON, integer amounts, a fixed category set), which fine-tuning teaches well, with knowledge (that Decathlon is a sports shop), which must come from pre-training and must survive fine-tuning. And it is the shape of real work: structured extraction is one of the most common reasons to fine-tune a small model instead of calling a large one (structured outputs).
The model. Qwen2.5-0.5B-Instruct: 494M parameters, Apache-2.0 licence, 24 layers, width 896, grouped-query attention with 14 query heads and 2 key-value heads, a 151,936-token vocabulary and tied embeddings (all from its config.json). It is small enough to fine-tune in minutes on one modest GPU or an Apple-silicon Mac, and it is also the model TRL's own documentation uses in examples.
Two paths, same data.
| path | hardware | stack |
|---|---|---|
| GPU | one CUDA GPU with bfloat16 (L4, A10, A100, or a cloud notebook) | PyTorch, Transformers, PEFT, TRL |
| Mac | Apple silicon, 16 GB or more | MLX-LM (mlx_lm.lora) |
What was run for this page. The data generator, the metric, the from-scratch NumPy LoRA and the parameter accounting were run, and their real outputs are shown. The model training and inference scripts were checked against the current TRL (v1.x), PEFT and MLX-LM documentation but not executed here (no GPU, no PyTorch), so their numbers are targets, and your run is the experiment.
Rules. Write metrics.py and build test.jsonl before you train anything. Never look at test-set failures and then add those exact examples to training: that turns your test into a training set and your score into fiction (contamination). Change one thing per run and write down every run.
Milestone 1: LoRA in 30 lines of NumPy¶
Before using a library, prove to yourself what LoRA can and cannot learn. Take a frozen 64×64 "pre-trained" matrix \(W_0\), and a target that needs a rank-4 change \(\Delta W\). Learn \(\tfrac{\alpha}{r}BA\) with \(B\) initialised to zero, for several ranks:
loss with no adaptation: 4.25e-02
rank 1: 128 trainable params (3.1%) step-0 loss 4.25e-02 final 2.52e-02
rank 2: 256 trainable params (6.2%) step-0 loss 4.25e-02 final 1.34e-02
rank 4: 512 trainable params (12.5%) step-0 loss 4.25e-02 final 2.58e-06
rank 8: 1024 trainable params (25.0%) step-0 loss 4.25e-02 final 2.86e-07
merged == adapter path: True
singular values of learned rank-8 update: [1.0623e+00 8.4330e-01 6.7590e-01 6.1290e-01 3.0000e-04 2.0000e-04]
singular values of the true update: [1.0639 0.8424 0.6761 0.6126 0. 0. ]
Four lessons, each of which you will meet again at full scale:
- Step-0 loss equals the base model's loss exactly. With \(B = 0\) the adapter contributes nothing, so fine-tuning starts from the pre-trained behaviour, not from a random perturbation of it.
- Rank is a hard capacity limit. Ranks 1 and 2 plateau far above zero; rank 4 and above solve the task. The learned rank-8 update has exactly four significant singular values matching the true ones (1.06, 0.84, 0.68, 0.61) and four that are about \(10^{-4}\): extra rank costs parameters but is simply unused.
- The trainable fraction is not the point. Rank 4 here is 12.5% of the matrix because the matrix is tiny; on a 4,864×896 MLP matrix rank 16 is 2.1%.
- Merging is exact. \(W_0 + \tfrac{\alpha}{r}BA\) is an ordinary matrix, so after training you can fold the adapter in and serve with zero extra latency.
Milestone 2: data, with a test set that can catch you out¶
make_data.py (in Build it) generates 2,500 examples from templates. The design of the split is the most important decision in the project:
train 2000 examples
valid 200 examples
test 300 examples
BESCOM charged me INR 64691 -> {"amount": 64691, "currency": "INR", "category": "utilities", "merchant": "BESCOM"}
Ola: 308 rupees -> {"amount": 308, "currency": "INR", "category": "travel", "merchant": "Ola"}
Settled INR 24,262 with Decathlon last night -> {"amount": 24262, "currency": "INR", "category": "shopping", "merchant": "Decathlon"}
test prompts also in train: 0
- Train and validation use six phrasings and four merchants per category. Validation is for watching training; it is drawn from the same distribution, so it will look excellent.
- Test uses three different phrasings and one unseen merchant per category (Blinkit, Social, Rapido, Mahanagar Gas, Decathlon). Getting the category right for an unseen merchant requires knowledge from pre-training; getting the format right for an unseen phrasing requires the model to have learned the task rather than the templates.
The test set is the only number you report. If validation reaches 100% and test does not, you have learned the most important fact about your training data: it is too narrow.
Each row is in TRL's conversational prompt-completion format: a prompt list (system and user messages) and a completion list (the assistant's JSON). With this format the trainer computes the loss on completion tokens only, by default. Training on the prompt tokens too would spend capacity teaching the model to generate expense messages, which you do not want. For MLX-LM, to_mlx.py rewrites each row as one messages list, and --mask-prompt restores the completion-only loss.
Milestone 3: the metric and the baselines¶
metrics.py parses the output (tolerating a Markdown code fence, because models love them) and scores validity, each field, and exact match. Here it is on four hand-written outputs that cover the failure modes you will actually see:
The four outputs were: a perfect answer; a correct answer inside a code fence but with the amount as the string "308"; chatty text around a partial object (invalid JSON); and a well-formed object with category "transport" instead of "travel". Notice that "valid JSON" is not "correct", and that a type error ("308" vs 308) is as fatal to a downstream program as a wrong number.
Now run predict.py with no adapter, then with --fewshot (two worked examples placed in the conversation). Record both. These are the bars LoRA must clear, and the few-shot number is the honest one: if a two-example prompt gets you 95% exact match, a fine-tuning pipeline is not worth its maintenance cost. For a 0.5B model on this task, expect the zero-shot baseline to fail mostly on format (free-text categories like "transport" or "food", amounts as strings, extra prose) rather than on reading the message; the few-shot prompt fixes much of the format and little of the category vocabulary.
Milestone 4: configure LoRA¶
Exact parameter accounting for Qwen2.5-0.5B (from count.py, run):
base model parameters: 494,032,768
r=16 on q_proj+v_proj : 1,081,344 trainable (0.22%)
r=16 on all 7 linears : 8,798,208 trainable (1.78%)
r=64 on all 7 linears : 35,192,832 trainable (7.12%)
bf16 weights: 0.99 GB; full fine-tune with AdamW (fp32 master + 2 moments + bf16 grads): ~7.9 GB before activations
LoRA r=16 all-linear: frozen bf16 0.99 GB + adapter states 0.14 GB
The choices, and why:
- Targets: all linear layers (
target_modules="all-linear": the four attention projections and the three MLP matrices in each block). The original LoRA paper adapted only the query and value projections; later work found that adapting the MLPs matters most. Thinking Machines' LoRA Without Regret (Schulman et al., 2025) reports that attention-only LoRA "significantly underperforms" MLP-only LoRA even at matched parameter count. - Rank 16, \(\alpha = 32\). A rank of 8 to 32 is ample for a narrow format task (milestone 1: rank only needs to cover the change the task requires). \(\alpha/r = 2\) sets the adapter's effective step size; keep the ratio fixed if you sweep rank, so the learning rate does not silently change with it.
- Learning rate \(2\times10^{-4}\), about ten times TRL's default for full fine-tuning (\(2\times10^{-5}\)). The same Thinking Machines study measured the optimal LoRA rate at "consistently 10x" the full fine-tuning one. Too low and a short run barely moves; too high and the loss spikes and the model forgets how to chat.
- No LoRA dropout, two epochs, batch 16 (250 optimiser steps). With 2,000 near-duplicate templates the risk is memorising phrasings, not under-fitting.
Milestone 5: train¶
On the GPU path, python train_lora.py. First it prints the trainable-parameter line, which you can predict exactly from the accounting above:
(This is the arithmetic of PEFT's print_trainable_parameters format applied to the counts above; if your line differs, your target modules differ.) Then watch three logged quantities:
- Training loss, averaged over completion tokens only. It should fall steeply in the first few dozen steps (the format is learned fast), then flatten near zero, because the JSON is almost fully determined by the input.
- Validation loss every 50 steps. It should track training loss closely; a gap means the adapter is memorising templates.
mean_token_accuracy, which TRL logs: the fraction of completion tokens predicted exactly. Near 1.0 is expected on this task.
On the Mac path, the equivalent run (commands in Build it) reports training and validation loss every few steps in the terminal. MLX-LM's defaults differ (rank 8, adapters on the last 16 layers, learning rate \(10^{-5}\)), so set them explicitly to match the GPU run, or treat the defaults as a second experiment.
Three ways to train the wrong thing
- No chat template. Training on raw
"text"strings while serving through the chat template teaches a format the model will never see in production. Always let the tokenizer's chat template build both. - Loss on the prompt. If you pass whole conversations as plain text without masking, the model learns to write expense messages. Use prompt-completion data (TRL) or
--mask-prompt(MLX-LM). - No end-of-turn token. If the completion is not followed by the template's end-of-turn token, the model never learns to stop and will run on after the JSON. The chat template adds it; hand-rolled formatting usually forgets it.
Milestone 6: evaluate, then read the failures¶
python predict.py qwen-expense-lora re-runs the same greedy decoding on the same test set with the adapter attached, and prints the same six numbers. Then read predictions.json next to the gold answers. Sort the failures into buckets before you change anything:
| bucket | example | what it tells you |
|---|---|---|
| format | "amount": "24,262" |
training data lacked comma-formatted amounts in some phrasing: fix the generator |
| unseen phrasing | misses the amount in "gave Rapido 300 rupees" | templates too narrow: add variety, not more copies |
| knowledge | Mahanagar Gas → "shopping" |
the base model does not know this entity; no amount of format training will fix it |
| ambiguity | "Social" → "shopping" |
the label is genuinely unclear (it is a restaurant chain); your gold label may be the problem |
Then run a forgetting check: ask the adapted model ten ordinary questions (a definition, a short translation, a simple sum) and compare its answers with the base model's. Narrow fine-tuning at a high learning rate can degrade unrelated behaviour; the paper LoRA Learns Less and Forgets Less (Biderman et al., 2024) measured that LoRA forgets less of the base model's abilities than full fine-tuning, at the cost of learning less on hard targets. On a narrow task that is usually the trade you want.
Milestone 7: merge, quantise and serve¶
An adapter is a small file (8.8M parameters, about 35 MB in fp32) that must be loaded beside the exact base model it was trained on. For serving you usually merge it: model.merge_and_unload() in PEFT, or mlx_lm.fuse on the Mac, writes \(W_0 + \tfrac{\alpha}{r}BA\) into ordinary weights. The merged model can then be quantised (to 4-bit for a laptop, or 8-bit for a server) and served by any engine (serving LLMs, on-device). Re-run the test set after quantising: a 4-bit model is a different model, and extraction tasks are sensitive to small changes in the top token.
Keeping adapters unmerged has its own advantage: one base model in memory can serve many adapters, switching per request, which is how multi-tenant fine-tuning services work.
How you know you have succeeded¶
-
metrics.pyand the test set existed before your first training run, and the test set was never edited after you saw failures. - You have a table of at least three rows (zero-shot, few-shot, LoRA) on the held-out test set, with exact match and valid-JSON rates.
- Target: valid JSON on at least 99% of test rows, and exact match above the few-shot baseline by a margin larger than the noise. With 300 test rows, one standard error of an accuracy near 90% is about \(\sqrt{0.9\times0.1/300} \approx 1.7\) points, so a gain under about 4 points is not evidence (statistics for evals).
- Every remaining test failure is in a named bucket, and you can say which buckets fine-tuning can and cannot fix.
- The forgetting check shows no obvious damage to general answers.
- You can explain why \(B\) starts at zero, why the learning rate is higher than for full fine-tuning, and what
all-linearadapts.
First principles¶
Why a low-rank update should be enough. Fine-tuning changes a model that has already learned almost everything it needs; the task-specific change is a small adjustment in a few directions. Aghajanyan, Zettlemoyer and Gupta (Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning, 2020) showed this directly: optimising in a random subspace of a few hundred dimensions recovers most of full fine-tuning's performance on many tasks, and larger pre-trained models need fewer dimensions. LoRA (Hu et al., 2021) applies that hypothesis per matrix: the update \(\Delta W\) has low rank, so learn it as a product \(BA\).
Why the zero init. At step 0 the adapted model must equal the pre-trained one, or training starts by repairing damage. Setting \(B = 0\) achieves that; \(A\) must then be random, because if both factors started at zero both gradients would be zero (\(\partial \mathcal{L}/\partial B \propto G A^\top\) and \(\partial\mathcal{L}/\partial A \propto B^\top G\)) and nothing would ever move.
Why ten times the learning rate. Full fine-tuning nudges weights that are already well placed; a small learning rate protects them. LoRA's parameters start at zero (B) or at an arbitrary random projection (A) and must travel much further in relative terms to express the update, while the frozen weights are protected structurally. Larger steps are both safe and necessary.
What fine-tuning can teach, and what it cannot. It reliably teaches format, style, task framing, label vocabulary and tool-call syntax, because these are low-dimensional adjustments of behaviour the model can already produce. It is a poor way to add large amounts of new factual knowledge: facts seen a handful of times in a small dataset are learned slowly and unreliably, and Gekhman et al. (Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?, 2024) found that once such examples are learned they increase the model's tendency to hallucinate. For knowledge, use retrieval; for behaviour, fine-tune. The "knowledge" bucket in milestone 6 is this principle showing up in your own error analysis.
The maths¶
Forward pass. For a frozen \(W_0 \in \mathbb{R}^{d_{\text{out}}\times d_{\text{in}}}\), input \(x \in \mathbb{R}^{d_{\text{in}}}\), \(A \in \mathbb{R}^{r\times d_{\text{in}}}\), \(B \in \mathbb{R}^{d_{\text{out}}\times r}\), \(r \ll \min(d_{\text{in}}, d_{\text{out}})\):
Computed right to left, the adapter costs \(r(d_{\text{in}} + d_{\text{out}})\) multiply-adds per token, never forming the \(d_{\text{out}}\times d_{\text{in}}\) product.
Gradients. Let \(G = \partial\mathcal{L}/\partial W_{\text{eff}}\) be the gradient full fine-tuning would apply to the effective matrix (\(G = \sum_{\text{tokens}} \delta\, x^\top\), with \(\delta = \partial\mathcal{L}/\partial h\)). Then
At step 0, \(B = 0\) so \(\partial\mathcal{L}/\partial A = 0\) and only \(B\) moves, in the direction \(G A^\top\): the full fine-tuning gradient projected onto the \(r\) random directions in \(A\). LoRA's first step is a random projection of full fine-tuning's first step, which is why it learns the most important directions early (the PEFT page develops this).
Trainable parameters. Summed over adapted matrices and layers:
For Qwen2.5-0.5B with \(r = 16\): q and o are 896→896 (\(16\times1792 = 28{,}672\) each), k and v are 896→128 (\(16\times1024 = 16{,}384\) each), gate and up are 896→4864 and down is 4864→896 (\(16\times5760 = 92{,}160\) each). Per layer \(366{,}592\); times 24 layers, \(8{,}798{,}208\).
Memory. Full fine-tuning with AdamW in mixed precision keeps, per parameter, a bf16 weight (2 bytes), an fp32 master copy (4), two fp32 moments (8) and a bf16 gradient (2): about 16 bytes, so \(16 \times 494\text{M} \approx 7.9\) GB before activations. LoRA keeps the base weights in bf16 (0.99 GB) and the 16 bytes per parameter only for the 8.8M adapter parameters (0.14 GB). QLoRA shrinks the frozen part again by storing it in 4-bit NF4, about 0.25 GB here, which is what lets 7B to 70B models be fine-tuned on one GPU (mixed precision, compute maths).
Why α/r and not just α
With \(A\) initialised with entries of variance \(\sigma^2\) and \(B\) trained, the update \(BAx\) has a magnitude that grows with \(r\) early in training, because it sums \(r\) terms. Dividing by \(r\) makes the initial effective learning rate roughly independent of rank, so a learning rate tuned at \(r = 8\) still works at \(r = 32\) as long as \(\alpha/r\) is kept fixed or \(\alpha\) scales with \(r\). Kalajdzievski (2023) argued that dividing by \(\sqrt{r}\) ("rsLoRA") is the correct scaling for stable learning at high rank; PEFT exposes it as use_rslora=True.
Build it¶
Seven files: run the first four anywhere (pure Python and NumPy, outputs shown above); run the training and prediction scripts on a GPU or a Mac.
make_data.py: the synthetic expense dataset (output in milestone 2)
"""Synthetic expense-parsing data: free text -> JSON. Test uses unseen phrasings and merchants."""
import json, random
CATS = {"groceries": ["BigBasket", "DMart", "Nature's Basket", "Zepto", "Blinkit"],
"dining": ["Swiggy", "Zomato", "Starbucks", "Haldiram's", "Social"],
"travel": ["Uber", "Ola", "IndiGo", "IRCTC", "Rapido"],
"utilities": ["Tata Power", "Airtel", "Jio", "BESCOM", "Mahanagar Gas"],
"shopping": ["Amazon", "Flipkart", "Myntra", "Croma", "Decathlon"]}
CUR = {"INR": ["Rs {a}", "₹{a}", "{a} rupees", "INR {a}"], "USD": ["USD {a}", "{a} dollars"]}
TRAIN_T = ["Paid {m} {p} today", "{p} spent at {m}", "{m} charged me {p}",
"Just paid {p} to {m}", "{m}: {p}", "bill from {m} came to {p}"]
TEST_T = ["Settled {p} with {m} last night", "{m} debit of {p} on my card", "gave {m} {p}"]
def amount(rng):
a = rng.choice([rng.randint(20, 999), rng.randint(1000, 99999)])
return a, (f"{a:,}" if a >= 1000 and rng.random() < 0.5 else str(a))
def example(rng, templates, held_out):
cat = rng.choice(list(CATS)); pool = CATS[cat]
m = pool[-1] if held_out else rng.choice(pool[:-1]) # last merchant of each list: test only
cur = "INR" if rng.random() < 0.8 else "USD"
a, shown = amount(rng)
text = rng.choice(templates).format(m=m, p=rng.choice(CUR[cur]).format(a=shown))
target = {"amount": a, "currency": cur, "category": cat, "merchant": m}
return {"prompt": [{"role": "system", "content": "Extract the expense as JSON with keys amount, currency, category, merchant."},
{"role": "user", "content": text}],
"completion": [{"role": "assistant", "content": json.dumps(target)}]}
rng = random.Random(0)
splits = {"train": [example(rng, TRAIN_T, False) for _ in range(2000)],
"valid": [example(rng, TRAIN_T, False) for _ in range(200)],
"test": [example(rng, TEST_T, True) for _ in range(300)]}
for name, rows in splits.items():
with open(f"{name}.jsonl", "w") as f:
f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)
print(f"{name:5s} {len(rows):5d} examples")
for r in splits["train"][:2] + splits["test"][:1]:
print(r["prompt"][1]["content"], "->", r["completion"][0]["content"])
train_texts = {r["prompt"][1]["content"] for r in splits["train"]}
print("test prompts also in train:", sum(r["prompt"][1]["content"] in train_texts for r in splits["test"]))
metrics.py: validity, per-field accuracy, exact match (output in milestone 3)
"""Score model outputs against gold JSON: validity, per-field accuracy, exact match."""
import json
FIELDS = ("amount", "currency", "category", "merchant")
def parse(text):
text = text.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip()
try:
obj = json.loads(text)
return obj if isinstance(obj, dict) else None
except json.JSONDecodeError:
return None
def score(golds, outputs):
n = len(golds); valid = exact = 0; field = dict.fromkeys(FIELDS, 0)
for gold, out in zip(golds, outputs):
pred = parse(out)
if pred is None:
continue
valid += 1
hits = [pred.get(k) == gold[k] for k in FIELDS]
for k, h in zip(FIELDS, hits):
field[k] += h
exact += all(hits)
return {"valid_json": valid / n, "exact_match": exact / n} | {k: v / n for k, v in field.items()}
if __name__ == "__main__":
gold = [{"amount": 308, "currency": "INR", "category": "travel", "merchant": "Ola"}] * 4
outs = ['{"amount": 308, "currency": "INR", "category": "travel", "merchant": "Ola"}',
'```json\n{"amount": "308", "currency": "INR", "category": "travel", "merchant": "Ola"}\n```',
'Sure! Here is the JSON: {"amount": 308}',
'{"amount": 308, "currency": "INR", "category": "transport", "merchant": "Ola"}']
for k, v in score(gold, outs).items():
print(f"{k:12s} {v:.2f}")
lora_numpy.py: LoRA from scratch on a planted rank-4 update (output in milestone 1)
import numpy as np
rng = np.random.default_rng(0)
d_in, d_out, n = 64, 64, 2048
W0 = rng.normal(0, d_in**-0.5, (d_out, d_in)) # "pre-trained", frozen
U, V = rng.normal(size=(d_out, 4)), rng.normal(size=(4, d_in))
dW_true = 0.05 * U @ V / 4 # the task needs a rank-4 change
X = rng.normal(size=(n, d_in)); Y = X @ (W0 + dW_true).T
def train_lora(r, alpha=16, lr=1e-2, steps=1500):
A = rng.normal(0, d_in**-0.5, (r, d_in)); B = np.zeros((d_out, r)); s = alpha / r
m = {k: 0 for k in "AB"}; v = {k: 0 for k in "AB"}
for t in range(1, steps + 1):
err = X @ (W0 + s * B @ A).T - Y # (n, d_out)
if t == 1: step0 = (err**2).mean()
G = 2 * err.T @ X / (n * d_out) # dL/dW_eff
grads = {"B": s * G @ A.T, "A": s * B.T @ G}
for k, P in (("A", A), ("B", B)): # Adam, in place
m[k] = 0.9 * m[k] + 0.1 * grads[k]; v[k] = 0.999 * v[k] + 0.001 * grads[k]**2
P -= lr * (m[k] / (1 - 0.9**t)) / (np.sqrt(v[k] / (1 - 0.999**t)) + 1e-8)
return step0, (err**2).mean(), A, B, s
print(f"loss with no adaptation: {((X @ W0.T - Y)**2).mean():.2e}")
for r in (1, 2, 4, 8):
step0, final, A, B, s = train_lora(r)
print(f"rank {r}: {r*(d_in+d_out):4d} trainable params ({r*(d_in+d_out)/(d_in*d_out):.1%})"
f" step-0 loss {step0:.2e} final {final:.2e}")
x = rng.normal(size=d_in)
merged = W0 + s * B @ A
print("merged == adapter path:", np.allclose(merged @ x, W0 @ x + s * B @ (A @ x)))
sv = np.linalg.svd(s * B @ A, compute_uv=False)
print("singular values of learned rank-8 update:", np.round(sv[:6], 4))
print("singular values of the true update: ", np.round(np.linalg.svd(dW_true, compute_uv=False)[:6], 4))
count.py: exact parameter and memory accounting for Qwen2.5-0.5B (output in milestone 4)
# Qwen2.5-0.5B-Instruct, from its config.json: hidden 896, 24 layers, 14 query heads,
# 2 key/value heads (head size 64), MLP 4864, vocab 151,936, tied embeddings, q/k/v biases.
H, L, F, Vocab, kv = 896, 24, 4864, 151_936, 2 * 64
shapes = {"q_proj": (H, H), "k_proj": (H, kv), "v_proj": (H, kv), "o_proj": (H, H),
"gate_proj": (H, F), "up_proj": (H, F), "down_proj": (F, H)} # (in, out)
per_layer = sum(i * o for i, o in shapes.values()) + (H + kv + kv) + 2 * H # + qkv biases + 2 RMSNorms
total = Vocab * H + L * per_layer + H
print(f"base model parameters: {total:,}")
for r, targets in ((16, ["q_proj", "v_proj"]), (16, list(shapes)), (64, list(shapes))):
lora = L * sum(r * (shapes[t][0] + shapes[t][1]) for t in targets)
print(f"r={r:2d} on {'all 7 linears' if len(targets) == 7 else '+'.join(targets):14s}: "
f"{lora:>10,} trainable ({lora / total:.2%})")
GB = 1e9
print(f"bf16 weights: {2 * total / GB:.2f} GB; full fine-tune with AdamW (fp32 master + 2 moments + bf16 grads): "
f"~{(2 + 4 + 8 + 2) * total / GB:.1f} GB before activations")
lora = L * sum(16 * (i + o) for i, o in shapes.values())
print(f"LoRA r=16 all-linear: frozen bf16 {2 * total / GB:.2f} GB + adapter states {16 * lora / GB:.2f} GB")
train_lora.py: LoRA SFT with TRL and PEFT (GPU path)
"""LoRA SFT of Qwen2.5-0.5B-Instruct on the expense task. Needs a CUDA GPU with bf16
(e.g. L4, A10, A100). pip install "trl>=1.0" peft datasets accelerate"""
import torch
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
data = load_dataset("json", data_files={"train": "train.jsonl", "valid": "valid.jsonl"})
peft_config = LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.0,
target_modules="all-linear", # q,k,v,o and gate,up,down in all 24 layers
task_type="CAUSAL_LM")
args = SFTConfig(
output_dir="qwen-expense-lora",
num_train_epochs=2, per_device_train_batch_size=16,
learning_rate=2e-4, lr_scheduler_type="cosine", warmup_steps=20, # ~10x a full-FT rate
max_length=256, bf16=True, model_init_kwargs={"dtype": torch.bfloat16},
logging_steps=10, eval_strategy="steps", eval_steps=50, save_strategy="no",
report_to="none", seed=0)
trainer = SFTTrainer(model="Qwen/Qwen2.5-0.5B-Instruct", args=args,
train_dataset=data["train"], eval_dataset=data["valid"],
peft_config=peft_config) # prompt-completion data: loss on completion only
trainer.model.print_trainable_parameters()
trainer.train()
trainer.save_model("qwen-expense-lora") # saves only the adapter (~35 MB in fp32)
predict.py: greedy predictions and scores, with or without the adapter
"""Greedy predictions on test.jsonl, scored. python predict.py [adapter_dir] [--fewshot]"""
import json, sys, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from metrics import score
BASE = "Qwen/Qwen2.5-0.5B-Instruct"
SHOTS = [("Swiggy order 450 rupees", {"amount": 450, "currency": "INR", "category": "dining", "merchant": "Swiggy"}),
("Airtel charged me USD 12", {"amount": 12, "currency": "USD", "category": "utilities", "merchant": "Airtel"})]
args = [a for a in sys.argv[1:] if not a.startswith("--")]
tok = AutoTokenizer.from_pretrained(BASE); tok.padding_side = "left" # left-pad for generation
model = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16, device_map="auto")
if args:
from peft import PeftModel
model = PeftModel.from_pretrained(model, args[0])
model.eval()
def messages(row):
msgs = list(row["prompt"])
if "--fewshot" in sys.argv:
shots = [m for q, a in SHOTS for m in ({"role": "user", "content": q},
{"role": "assistant", "content": json.dumps(a)})]
msgs = msgs[:1] + shots + msgs[1:]
return msgs
rows = [json.loads(line) for line in open("test.jsonl")]
golds = [json.loads(r["completion"][0]["content"]) for r in rows]
outs = []
for i in range(0, len(rows), 32):
texts = [tok.apply_chat_template(messages(r), tokenize=False, add_generation_prompt=True)
for r in rows[i:i + 32]]
enc = tok(texts, return_tensors="pt", padding=True).to(model.device)
with torch.no_grad():
gen = model.generate(**enc, max_new_tokens=64, do_sample=False)
outs += tok.batch_decode(gen[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
json.dump(outs, open("predictions.json", "w"), indent=1)
for k, v in score(golds, outs).items():
print(f"{k:12s} {v:.3f}")
The Mac path: MLX-LM commands
# to_mlx.py: MLX-LM's chat format is one "messages" list per row
import json, os
os.makedirs("data_mlx", exist_ok=True)
for split in ("train", "valid", "test"):
with open(f"{split}.jsonl") as src, open(f"data_mlx/{split}.jsonl", "w") as dst:
for line in src:
row = json.loads(line)
dst.write(json.dumps({"messages": row["prompt"] + row["completion"]}, ensure_ascii=False) + "\n")
pip install mlx-lm
python to_mlx.py
# train: adapters on all 24 layers, loss on the assistant turn only
mlx_lm.lora --model Qwen/Qwen2.5-0.5B-Instruct --train --data data_mlx \
--num-layers 24 --batch-size 8 --iters 500 --learning-rate 2e-4 --mask-prompt
# held-out loss with the adapter (written to ./adapters by default)
mlx_lm.lora --model Qwen/Qwen2.5-0.5B-Instruct --adapter-path adapters --data data_mlx --test
# one generation, then fuse the adapter into the weights (saved to ./fused_model)
mlx_lm.generate --model Qwen/Qwen2.5-0.5B-Instruct --adapter-path adapters --prompt "gave Rapido 300 rupees"
mlx_lm.fuse --model Qwen/Qwen2.5-0.5B-Instruct
--test reports loss and perplexity, not exact match. For the real metric, load the model with mlx_lm.load(..., adapter_path="adapters"), generate greedily for each test prompt and pass the outputs to metrics.score, exactly as predict.py does. Note that the generate command above omits the system prompt used in training; the score you report must come from prompts formatted exactly as in training.
Stretch goals, roughly in order of difficulty
- Rank and target sweep. \(r \in \{2, 8, 32\}\) crossed with attention-only vs all-linear. Plot test exact match. Does milestone 1's lesson (rank as capacity) appear, or is every rank enough for this task?
- Data-size curve. Train on 100, 300, 1,000 and 2,000 examples. Where does test accuracy saturate? This curve, not a hyperparameter, usually decides real projects.
- Harder data. Add multi-expense messages ("Uber 250 and Swiggy 480"), refunds (negative amounts), and messages with no expense (the right answer is
null). Rebuild the test set first. - QLoRA. Load the base model in 4-bit NF4 (
BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")passed asquantization_configto the trainer) and compare quality and memory with bf16 LoRA (quantisation). - Full fine-tuning baseline. Same data, all parameters, learning rate \(2\times10^{-5}\). Compare test accuracy and the forgetting check. Do you see "learns less, forgets less"?
- A real dataset. Repeat the project on public data with a strong metric, for example a function-calling dataset scored by exact argument match, and compare with prompting a frontier model.
- Preference tuning. Generate pairs (correct JSON vs a plausible wrong one) and run DPO on top of your SFT adapter. Measure whether it reduces the remaining failure buckets.
- Write LoRA into your tiny GPT. Add
LoRALinearto the model from the tiny-GPT project, pre-train on Shakespeare, then adapt to a different author with rank 4 and compare with full fine-tuning.
Common misconceptions¶
- "Fine-tuning teaches the model new facts." It mostly teaches behaviour. Facts belong in retrieval; see the knowledge bucket in milestone 6.
- "Validation accuracy is the result." Validation shares templates with training. Only the held-out test, with new phrasings and entities, measures the skill.
- "Higher rank is always better." Rank only needs to cover the change the task requires (milestone 1); beyond that it adds parameters, not quality, and learning-rate interactions can make it worse.
- "LoRA is an approximation, so it is always worse." For small-to-medium SFT datasets and for RL, careful studies find it matches full fine-tuning; it falls behind when the dataset carries more information than the adapter can hold.
- "An adapter works on any version of the base model." It is a delta on specific weights. Load it on a different checkpoint, or a quantised one it was not trained with, and quality can drop silently. Re-evaluate every combination you ship.
Check yourself¶
Why must the test set use different phrasings and merchants from training, and what does each difference test?
New phrasings test whether the model learned the task (find the amount, currency and merchant anywhere in the sentence) rather than six templates. Unseen merchants test whether pre-trained knowledge (what Decathlon sells) survives fine-tuning and is used to assign the category. A test drawn from the training distribution would show near-100% and test neither.
Your training loss drops to 0.01 in 40 steps. Good news or a bug?
On this task it is plausible: the JSON is almost fully determined by the input and the format is easy to learn. But check two bugs that produce the same curve: the loss computed on prompt tokens with an answer leaked into the prompt, and duplicated rows between training and validation. The test-set score, not the training loss, decides.
Why is B initialised to zero and A randomly, and what happens if you swap them?
\(B = 0\) makes the adapted model identical to the base model at step 0. \(A\) must be non-zero so that \(B\) receives a gradient (\(\propto GA^\top\)). Swapping (random \(B\), zero \(A\)) still gives \(BA = 0\) at step 0 and still trains, because \(A\)'s gradient is \(\propto B^\top G \ne 0\); the conventional choice mirrors the original paper. Both zero would never train.
With r = 16 and all-linear on Qwen2.5-0.5B, which module type holds most of the adapter parameters, and why?
The MLP projections: gate, up and down each have \(16\times(896+4864) = 92{,}160\) adapter parameters per layer, versus 28,672 for q and o and 16,384 for k and v (which are narrow because of grouped-query attention). The MLP accounts for 276,480 of 366,592 per layer, about 75%.
Few-shot prompting gets 93% exact match; your LoRA model gets 95% on 300 test rows. Ship it?
Not on this evidence. The standard error of each accuracy is about 1.3 to 1.5 points and the difference is 2 points, well within noise; use a paired test on the same rows (McNemar) before claiming a gain. Then weigh the costs: an adapter is a model to version, evaluate and serve; a prompt is a string. Improve data until the gain is clear, or ship the prompt.
Why does LoRA tolerate a learning rate about ten times higher than full fine-tuning?
The frozen weights cannot be damaged by large steps, and the adapter parameters start at zero or at an arbitrary random projection, so they must move a long way relative to their initial scale. Full fine-tuning needs small steps to avoid wrecking well-placed pre-trained weights. Empirically the optimal ratio is close to 10.
Hard: after merging the adapter and quantising to 4-bit, exact match drops from 96% to 89%. Explain and fix.
Quantisation adds error to every weight, including the merged low-rank update, which may be small relative to the quantisation step and partly erased; extraction is sensitive to small shifts in the top token (a digit, a quote). Fixes: quantise with a calibration set drawn from the task (GPTQ or AWQ), keep sensitive layers at higher precision, serve the adapter unmerged on top of the quantised base, or train with QLoRA on the quantised base so the adapter learns to compensate.
Hard: a colleague proposes fine-tuning the model on your company's 10,000 internal policy documents so it can answer policy questions. What do you advise?
Use retrieval for the knowledge and fine-tuning, if at all, for the behaviour. Facts absorbed through a few epochs of SFT are recalled unreliably, cannot be updated without retraining, cannot be cited, and can increase confident hallucination. A RAG system retrieves the relevant policy at question time with a citation and updates when a document changes. Fine-tune afterwards if the answers need a house style or the model must learn to say "the policy does not cover this".
Go deeper¶
Papers
- LoRA: Low-Rank Adaptation of Large Language Models — Hu et al., 2021. Section 4 is the method; section 7 analyses the rank and the subspace of the learned update.
- QLoRA: Efficient Finetuning of Quantized LLMs — Dettmers et al., 2023. NF4, double quantisation and paged optimisers: fine-tuning large models on one GPU.
- Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning — Aghajanyan, Zettlemoyer and Gupta, 2020. The empirical reason a low-rank update can be enough.
- LoRA Learns Less and Forgets Less — Biderman et al., 2024. Careful LoRA vs full fine-tuning comparisons on code and maths; the trade-off behind milestone 6.
- Parameter-Efficient Transfer Learning for NLP — Houlsby et al., 2019. Adapters, the idea LoRA refined.
- DoRA: Weight-Decomposed Low-Rank Adaptation — Liu et al., 2024. Splits magnitude and direction; a common drop-in variant (
use_dora=Truein PEFT).
Articles and documentation
- LoRA Without Regret — Schulman et al., Thinking Machines, 2025. When LoRA matches full fine-tuning, why MLP layers matter, the 10× learning rate and RL at rank 1.
- Practical Tips for Finetuning LLMs Using LoRA — Sebastian Raschka. Hundreds of runs distilled into rank, alpha, epochs and target-layer advice.
- TRL: SFT Trainer — Hugging Face. Dataset formats, completion-only and assistant-only loss, PEFT integration; the API this project uses.
- PEFT: LoRA developer guide — Hugging Face. Initialisation options, rsLoRA, DoRA, target modules and merging.
- MLX-LM: LoRA and QLoRA — Apple MLX team. The Mac path: data formats, flags, evaluation, fusing and memory tips.
Code
- huggingface/peft — Read
tuners/lora/layer.pyto see the 20 lines that matter. - unslothai/unsloth — Fused kernels for faster, lower-memory LoRA and QLoRA on a single GPU.
- hiyouga/LLaMA-Factory and axolotl — Config-driven fine-tuning frameworks for when you outgrow a single script.
Where this leads¶
- Parameter-efficient fine-tuning: LoRA and QLoRA — the theory page behind this project, with the full gradient analysis and NF4.
- Project: a RAG assistant and a tool-using agent — the next rung: give a model knowledge at question time instead of training it in.
- DPO and direct preference optimisation — what to put on top of an SFT adapter when "correct" is a preference rather than a label.
- Evals in practice — how to grow milestone 3's metric into a proper evaluation suite.