SENIORCHAPTER 26

Fine-tuning: when, how, and the alternatives

Fine-tuning changes how a model behaves, not what it knows. Train a LoRA adapter on a laptop for the ticket classifier, and measure it against few-shot prompting on the same fifty tickets

60 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

Your support assistant invents details of the returns policy. A teammate proposes fine-tuning a model on 400 question-and-answer pairs written from the policy document, so that it 'knows' the policy. After training, what is most likely?

Fine-tuning means continuing to train a pretrained model on your own examples, so that the behaviour you want is in the weights rather than in the prompt. It is the most powerful of the three ways you have to change a model’s behaviour, and the most expensive to keep. The other two, the prompt and the context you retrieve, can be changed in a minute and rolled back in a second. A fine-tuned model is a build artefact: data, a training run, an evaluation and a deployment, repeated every time the requirement or the base model changes.

This chapter is about when that cost pays. It explains what fine-tuning changes and what it cannot, how LoRA makes it cheap enough to do on a laptop, and what goes wrong. The lab trains a LoRA adapter on a 1.5-billion-parameter open model for the ticket classifier from prompting-fundamentals, and puts it in the same table as few-shot prompting on the same fifty tickets.

What fine-tuning changes

Recall the layers from pretraining-to-rlhf. Pretraining put knowledge and capability into the weights. Supervised fine-tuning taught the model the shape of a conversation, and preference training taught it which answers to prefer. When you fine-tune, you add one more thin layer of supervised training on top: the same next-token loss, on your examples, usually computed only on the response tokens.

What a thin layer can change is mostly which of the things the model can already do it does by default:

  • Format and style. Always reply with one label; always use the house tone; always emit this JSON shape. A few hundred examples are enough.
  • Decision boundaries. Where “returns” ends and “billing” begins for your team, learnt from examples instead of stated in a definition. This is where a fine-tuned classifier gains most.
  • Compression of the prompt. Instructions and examples that you send on every call move into the weights, so the prompt shrinks. For the ticket classifier, the few-shot prompt is about 350 tokens; the fine-tuned model needs about 50.
  • A small model doing one task well. A 1.5B model fine-tuned on one narrow task can match a much larger general model on that task, at a fraction of the latency and cost. This is distillation when the labels come from the larger model.

What a thin layer does badly is add knowledge. The Predict above is the standard mistake. Gekhman et al. measured it directly: training examples that contain facts the model did not know are learnt slowly, and as they are learnt, hallucination on other questions rises. Ovadia et al. compared unsupervised fine-tuning on the source text with retrieval for injecting knowledge, and retrieval won consistently, both for facts the model had seen in pretraining and for new ones. If the problem is that the model does not know your policy, your catalogue or last week’s incident, put that text in the context. That is what the RAG chapter in this module does.

The order to try things in

Each step down this list is slower to change and more expensive to run. Do not skip one without a measurement that says it is not enough.

The problem Try first Fine-tune when
The model misunderstands the task A clearer prompt: definitions, a tie-break rule, examples Never first. A model that cannot follow a clear prompt will not learn from a few hundred examples either
The model lacks facts Retrieval: put the source text in the context Almost never; fine-tune for how to use retrieved text, not for the facts
Output format drifts Structured outputs, which constrain decoding to a schema The format is not expressible as a schema, such as a house writing style
Quality is good but cost or latency is too high A smaller hosted model, prompt caching, batching, lower effort A small model with a few-shot prompt is close but not close enough, and the volume pays for the work
Data cannot leave your network An open model you host, with a good prompt The hosted-quality gap on your task is too large for the open model you can afford to run
A narrow task needs to run on a device A small open model with a prompt Almost always: small models gain the most from fine-tuning

The second column fixes most problems. Teams that skip it usually discover, after a month of fine-tuning, that a three-line change to the definitions would have done the same.

When fine-tuning beats prompting

Fine-tuning wins when three things hold at once: the task is narrow and stable, the volume is high, and a smaller or local model is worth having. Classification, extraction into a fixed schema, routing, and rewriting into a house style are the classic cases.

Run the numbers for the ticket classifier. With the few-shot prompt, each call sends about 350 input tokens. At three million tickets a day on Claude Haiku 5.5, at $0.10 per million input tokens and $0.50 per million output, input is about $105 a day, and output, which includes the model’s thinking even at effort: "low", adds roughly as much again. Call it $200 a day, $6,000 a month, with p50 latency around 600 to 900 ms from the choosing-a-model lab. A fine-tuned 1.5B model on one rented GPU that costs $1 to $2 an hour handles that load for $750 to $1,500 a month, answers in tens of milliseconds, and needs a 50-token prompt. That is a real saving, and the latency is a capability the hosted model cannot offer. But it buys you a training pipeline, a serving stack, a GPU on call and a retraining process; if your volume were thirty thousand tickets a day the hosted bill would be $60 a month and fine-tuning would never pay back the engineer’s time.

The other strong case is a behaviour no prompt holds: a tone, a format or a judgement call that the model gets right 90% of the time with the best prompt you can write and that you need at 99%. Hundreds of examples of the exact behaviour, chosen from the 10% the prompt gets wrong, move a model further than another paragraph of instructions.

When it does not

  • Low volume. Below hundreds of thousands of calls a month the hosted bill is smaller than the cost of owning a model.
  • Moving requirements. A new category, a new policy, a new product line: the prompt changes in a pull request; the fine-tuned model needs new labelled data and a new training run. The break step of the lab shows this.
  • A frontier model is already at the ceiling. On the fifty tickets, Claude scores in the 90s with a few-shot prompt. If what remains are ambiguous items your own team disagrees on, no training fixes them; better labels do.
  • Knowledge. As above. Retrieval wins.
  • Base model churn. Your adapter is tied to the exact base model it was trained on. When a better base model ships, a prompt moves across with one changed string and a re-run of the eval; an adapter must be retrained, re-evaluated and redeployed. Hosted fine-tuning has the same problem in another form: the tuned model lives only as long as the vendor serves its base.
  • Safety and breadth you were relying on. The Why above. A model narrowed to one task can stop doing others it did before, and it can lose refusal behaviour you never tested.

Whether you can fine-tune the hosted model you use at all is a question for its provider; many frontier models are not tunable by customers. That pushes fine-tuning towards open models you run yourself, which is the path the lab takes.

LoRA: train a small update instead of the model

Full fine-tuning updates every weight. For a 1.5B model in 16-bit precision that is 3 GB of weights, plus gradients and the Adam optimiser’s two moment estimates, so roughly 12 to 16 bytes per parameter in mixed precision, 20 to 25 GB before activations. For a 70B model it is a cluster. And every fine-tuned variant is a full copy of the model.

LoRA (Hu et al., 2021) freezes the pretrained weights and learns a low-rank update beside each chosen matrix. A weight matrix W of shape d_out × d_in gets two new matrices, B of shape d_out × r and A of shape r × d_in, with a small rank r such as 8 or 16. The layer computes W·x + (α/r)·B·A·x. B starts at zero, so training begins from exactly the pretrained model, and only A and B receive gradients.

xW (frozen)1536 × 1536 = 2.36 M weightsA8 × 1536B1536 × 8trainable: 24,576+W·x +(α/r)·B·A·x

The arithmetic for the lab’s model makes the saving concrete. Qwen2.5-1.5B has 28 layers, a hidden size of 1,536 and an MLP width of 8,960. One attention query matrix is 1,536 × 1,536, 2.36 million weights; its rank-8 update is 8 × (1,536 + 1,536) = 24,576, about 1%. Put rank-8 updates on all seven linear layers of a block (query, key, value, output, and the three MLP projections) and you train about 330,000 parameters per layer, 9.2 million across all 28 layers: 0.6% of the model. The adapter file is tens of megabytes; the base model is shared. You can keep one adapter per task or per customer and load them on demand.

Three findings shape how you set LoRA up:

  • Put it on every layer type, not only attention. The original paper adapted only the attention query and value matrices. Later work, including Thinking Machines’ “LoRA Without Regret” (2025), found that adapting the MLP layers matters more, and that attention-only LoRA underperforms even at a higher rank with the same parameter count. In PEFT that is target_modules="all-linear"; MLX-LM adapts every linear layer in the last --num-layers blocks by default.
  • Use a higher learning rate than full fine-tuning. The same post found the best LoRA learning rate about ten times the full fine-tuning one. PEFT recipes commonly use around 1e-4; MLX-LM’s default is 1e-5, but it also scales the update by 20 by default, which is the α/r factor in another form. Change one at a time.
  • LoRA learns less and forgets less. Biderman et al. (2024) found that on hard new domains such as code and maths, LoRA at typical ranks underperforms full fine-tuning, and that it also preserves the base model’s behaviour on other tasks better. For a narrow classifier you want exactly that trade.

QLoRA: the base model in four bits

The frozen weights do not need gradients, so they do not need full precision either. QLoRA (Dettmers et al., 2023) stores the base model in a 4-bit format (NormalFloat4), dequantises each block on the fly during the forward and backward passes, and trains the LoRA matrices in 16-bit. The base weights take a quarter of the memory of 16-bit. That is how the paper fine-tuned a 65B model on a single 48 GB GPU, with results that matched 16-bit fine-tuning on their benchmarks.

On a laptop the same idea is what makes the lab possible. The 4-bit MLX build of Qwen2.5-1.5B-Instruct is an 869 MB download. MLX-LM trains QLoRA automatically when the model you point it at is quantised; on an 8 GB Apple silicon Mac it trains this task in minutes. On Linux with an NVIDIA GPU, PEFT and TRL do the same with the 16-bit weights on an 8 GB card, or in 4-bit with bitsandbytes on a smaller one.

The data is the work

Training code is a dozen lines. The quality of a fine-tuned model is the quality of its data, and three things decide that.

Quantity and coverage. For a six-way classifier, a few hundred examples covering every label, every common phrasing and the ambiguous pairs is a reasonable start. More of the easy cases adds little; more of the boundary cases adds a lot. Where your prompted model fails is where your training data should be dense.

Where labels come from. Real tickets labelled by your team are best. Labels from a stronger model are cheaper and are how most distillation works: the lab has Claude Haiku 5.5 write and label 700 tickets for about three cents. Synthetic data inherits the teacher’s mistakes and its blind spots, and it is more uniform than real traffic: generated tickets are tidier, more on-topic and more evenly balanced than what customers write. Read a sample before you train, and count how many labels you would change. That number is a floor on the error you are teaching.

Separation from the test set. The fifty hand-labelled tickets from prompting-fundamentals are the test set. They must not appear in the training data, and neither should near-copies of them. A teacher model asked for “a ticket about a crushed parcel” can produce something close to ticket 13 by chance. The lab’s data script drops any generated ticket whose word trigrams overlap a test ticket’s too much, and prints how many it dropped. If you skip that check and your score jumps, you do not know whether the model learnt the task or memorised the answers.

Train on the response only. The loss on the prompt tokens teaches the model to predict the system prompt and the ticket, which is wasted capacity at best. MLX-LM calls this --mask-prompt; TRL does it by default for prompt-completion data.

Where it goes wrong

  • No baseline. You cannot say a fine-tuned model is good without the score of the best prompt on the same items. The lab produces both, from the same fifty tickets, in the same format.
  • Chat template mismatch. The model learns the exact token sequence it was trained on. If training renders the conversation with one template and serving uses another, you get a degraded model and no error. The break step in pretraining-to-rlhf showed this for instruction tuning; it is as true for your adapter. Use the tokenizer’s own apply_chat_template in both places.
  • Overfitting. With hundreds of examples and several epochs, the model memorises them. Watch the validation loss: when it stops falling and starts rising, you have trained too long. Keep checkpoints and evaluate the best one, not the last.
  • Narrowing. A model trained only to emit one of six words may answer an unrelated question with “technical”. For a classifier behind an API that never sees anything else, that is fine. For a model that also chats, it is a regression nobody tested. The lab checks it.
  • Safety erosion. If the fine-tuned model talks to users, run your safety and refusal tests on it as well as your task eval, every time you retrain.
  • Confidence without calibration. A fine-tuned classifier outputs a label with no hint of doubt. If you need a confidence signal to route the uncertain cases to a person or a bigger model, use the probability of the label token, not the label alone, and check it is calibrated on held-out data.
LAB LoRA on a laptop, against few-shot on the same fifty tickets ~75 MIN
YOU NEEDThe prompting-fundamentals harness: labs/ai/evals/classify.py and labs/ai/evals/tickets.jsonlOllama with llama3.2:3b for the few-shot comparison (from earlier labs)Python 3.12 with uvMLX path: an Apple silicon Mac with 8 GB of RAM or more and about 1.5 GB of free disk (the 869 MB model, the MLX packages and adapters)PEFT path instead: Linux with an NVIDIA GPU with 8 GB or more, about 3 GB for the model and several GB for PyTorch with CUDAANTHROPIC_API_KEY for step 1 (about $0.03 on claude-haiku-5-5), or a free but slower local generation with Ollama

You will generate about 700 labelled training tickets with a teacher model, keep them apart from the fifty test tickets, train a rank-8 LoRA adapter on Qwen2.5-1.5B-Instruct, and score the base model with the few-shot prompt, the base model with a short prompt, and the adapter with the short prompt, using classify.py’s parser and scoring. Work in labs/ai/finetune/, next to labs/ai/evals/. MLX-LM and PEFT are not added to labs/ai/pyproject.toml: they are platform-specific and large, so the commands bring them in for the run with uv run --with.

1. The shared prompt, and the training data. From the root of your checkout:

mkdir -p labs/ai/finetune/data && cd labs/ai/finetune
cat > common.py <<'EOF'
"""Shared by make_data.py, train_peft.py and ft_eval.py: the short prompt the adapter learns."""
SHORT_SYSTEM = ("Classify the support ticket. Reply with one word: "
                "billing, shipping, returns, account, product or technical.")

def messages(text, label=None):
    m = [{"role": "system", "content": SHORT_SYSTEM}, {"role": "user", "content": text}]
    if label is not None:
        m.append({"role": "assistant", "content": label})
    return m
EOF

Create make_data.py. It asks a teacher model for tickets in six styles per label, drops duplicates and anything too close to a test ticket, and writes MLX-LM’s chat format:

"""Generate labelled training tickets with a teacher model, dedupe, decontaminate, split."""
import argparse, json, random, re, sys, urllib.request
from pathlib import Path

HERE = Path(__file__).parent
sys.path.insert(0, str(HERE.parent / "evals"))
from classify import DEFINITIONS, ITEMS, LABELS, PRICES   # the test set and its definitions
from common import messages

SCHEMA = {"type": "object", "additionalProperties": False, "required": ["tickets"],
          "properties": {"tickets": {"type": "array", "items": {"type": "string"}}}}
STYLES = ["short and blunt, under 15 words", "polite and detailed, two or three sentences",
          "annoyed, with a typo or two", "mentions an order number of 4 to 6 digits",
          "written by someone whose first language is not English",
          "touches a second category too, but this category's team must act first"]

def ask_claude(prompt, model, usage):
    import anthropic
    client = anthropic.Anthropic(max_retries=5)
    # Haiku 5.5 has no server-side fallback; a refusal comes back as stop_reason "refusal"
    r = client.messages.create(model=model, max_tokens=4096, messages=[{"role": "user", "content": prompt}],
        output_config={"effort": "low", "format": {"type": "json_schema", "schema": SCHEMA}})
    usage[0] += r.usage.input_tokens; usage[1] += r.usage.output_tokens
    if r.stop_reason != "end_turn":
        return []
    return json.loads(next(b.text for b in r.content if b.type == "text"))["tickets"]

def ask_ollama(prompt, model, usage):
    body = {"model": model, "stream": False, "format": SCHEMA, "options": {"temperature": 0.9},
            "messages": [{"role": "user", "content": prompt}]}
    req = urllib.request.Request("http://localhost:11434/api/chat", data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=600) as r:
        return json.loads(json.load(r)["message"]["content"])["tickets"]

def trigrams(s):
    w = re.findall(r"[a-z0-9]+", s.lower())
    return {tuple(w[i:i + 3]) for i in range(len(w) - 2)}

def jaccard(a, b):
    return len(a & b) / max(1, len(a | b))

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--backend", choices=["claude", "ollama"], default="claude")
    ap.add_argument("--model")
    ap.add_argument("--per-call", type=int, default=20)
    a = ap.parse_args()
    model = a.model or ("claude-haiku-5-5" if a.backend == "claude" else "qwen2.5:14b")
    ask = ask_claude if a.backend == "claude" else ask_ollama
    test = [trigrams(it["text"]) for it in ITEMS]
    kept, seen, dropped, usage = [], [], {"dup": 0, "near_test": 0, "bad": 0}, [0, 0]
    for label in LABELS:
        for style in STYLES:
            prompt = (f"<categories>\n{DEFINITIONS}\n</categories>\n\nWrite {a.per_call} different "
                      f"customer support tickets for an online shop that belong to the category "
                      f"'{label}'. Style: {style}. Vary the products, the problem and the wording. "
                      'Return JSON: {"tickets": ["...", "..."]}.')
            for text in ask(prompt, model, usage):
                text = text.strip()
                tg = trigrams(text)
                if len(text) < 10 or len(text) > 600:
                    dropped["bad"] += 1
                elif any(jaccard(tg, t) > 0.3 for t in test):
                    dropped["near_test"] += 1
                elif any(jaccard(tg, s) > 0.6 for s in seen):
                    dropped["dup"] += 1
                else:
                    kept.append({"label": label, "style": style, "text": text}); seen.append(tg)
            print(f"{label:9} {style[:40]:40} kept so far {len(kept)}")
    random.Random(0).shuffle(kept)
    n_valid = len(kept) // 10
    (HERE / "data" / "raw.jsonl").write_text("".join(json.dumps(r) + "\n" for r in kept))
    for name, rows in (("valid", kept[:n_valid]), ("train", kept[n_valid:])):
        (HERE / "data" / f"{name}.jsonl").write_text(
            "".join(json.dumps({"messages": messages(r["text"], r["label"])}) + "\n" for r in rows))
    cost = ""
    if model in PRICES:
        cost = f"  ${(usage[0] * PRICES[model][0] + usage[1] * PRICES[model][1]) / 1e6:.3f}"
    print(f"kept {len(kept)} (train {len(kept) - n_valid}, valid {n_valid})  dropped {dropped}{cost}")

if __name__ == "__main__":
    main()
export ANTHROPIC_API_KEY=sk-ant-...        # or `ant auth login`; or use --backend ollama
uv run make_data.py
wc -l data/*.jsonl
36 progress lines, then something like kept 690 (train 621, valid 69) dropped {'dup': 14, 'near_test': 9, 'bad': 0} $0.028. The near_test count is the decontamination check doing its job: a handful of generated tickets were close enough to one of the fifty test tickets to inflate your score, and they are gone. data/train.jsonl lines look like {"messages": [{"role": "system", ...}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "shipping"}]}. With --backend ollama and qwen2.5:14b the run is free and takes ten to twenty minutes; with --model llama3.2:3b it is faster and the tickets are noticeably more repetitive, which you will see in the dup count.

2. Read the labels before you train on them.

uv run python -c "
import json, random
rows = [json.loads(l) for l in open('data/raw.jsonl')]
for r in random.Random(1).sample(rows, 30): print(f\"{r['label']:9} {r['text'][:110]}\")"
Thirty tickets with their teacher labels. Count the ones you would label differently under the tie-break rule. Expect two to four, mostly in the ‘touches a second category’ style: a damaged item labelled returns that your rule sends to shipping, a refund question labelled returns that is billing once the item is back. That rate, around 10%, is label noise you are about to teach. Notice also how tidy the tickets are compared with the fifty you wrote by hand. Both are reasons the test set is human-labelled and never generated.

3a. Train on Apple silicon with MLX-LM.

uv run --with "mlx-lm[train]==0.32.2" mlx_lm.lora \
  --model mlx-community/Qwen2.5-1.5B-Instruct-4bit \
  --train --data data --adapter-path adapters/qwen15-r8 \
  --mask-prompt --num-layers 16 --batch-size 8 \
  --iters 600 --learning-rate 1e-5 --steps-per-eval 100 --save-every 100 --seed 0
The first run downloads the 869 MB model into the Hugging Face cache. Then a line reporting trainable parameters: a few million, well under 1% of the model, because rank 8 goes on every linear layer of the last 16 of the 28 blocks (--num-layers 16) and nowhere else. Training lines report train loss, iterations per second and peak memory, and every 100 iterations a validation loss. Expect validation loss to fall steeply in the first 100 to 200 iterations and then flatten well below where it started; peak memory stays in the low gigabytes; the run takes roughly five to fifteen minutes on an M1 or later. Checkpoints land in adapters/qwen15-r8/ every 100 iterations beside the final adapters.safetensors. If validation loss turns upwards for the last few evaluations while train loss keeps falling, the model is memorising: re-run with fewer --iters, or evaluate an earlier checkpoint.

3b. Or train on Linux with an NVIDIA GPU, with PEFT and TRL. Create train_peft.py. It turns each chat example into a prompt and a completion, which makes TRL compute the loss on the label only:

"""LoRA SFT with PEFT + TRL on the same data/ files MLX-LM uses."""
import argparse, torch
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

ap = argparse.ArgumentParser()
ap.add_argument("--model", default="Qwen/Qwen2.5-1.5B-Instruct")
ap.add_argument("--out", default="adapters/peft-r8")
a = ap.parse_args()

def split(ex):  # conversational prompt-completion: loss on the completion only (TRL's default)
    return {"prompt": ex["messages"][:-1], "completion": ex["messages"][-1:]}

ds = load_dataset("json", data_files={"train": "data/train.jsonl", "valid": "data/valid.jsonl"})
ds = ds.map(split, remove_columns=["messages"])
trainer = SFTTrainer(
    model=a.model, train_dataset=ds["train"], eval_dataset=ds["valid"],
    peft_config=LoraConfig(r=8, lora_alpha=16, lora_dropout=0.05,
                           target_modules="all-linear", task_type="CAUSAL_LM"),
    args=SFTConfig(output_dir=a.out, num_train_epochs=3, per_device_train_batch_size=8,
                   learning_rate=1e-4, logging_steps=10, eval_strategy="epoch",
                   save_strategy="no", report_to="none", max_length=256, seed=0,
                   model_init_kwargs={"dtype": torch.bfloat16}))
trainer.model.print_trainable_parameters()
trainer.train()
trainer.save_model(a.out)  # writes the adapter only, tens of MB
uv run --with "peft==0.21.0" --with "trl==1.17.1" --with datasets train_peft.py
PEFT reports about 9.2 million trainable parameters (rank 8 on all seven linear layers of all 28 blocks, 0.6%), training logs every 10 steps, and an eval loss after each of the three epochs that falls and then flattens. Three epochs over about 620 examples at batch 8 is about 240 steps, a few minutes on an 8 GB card. The adapter is saved to adapters/peft-r8/. The hyperparameters differ from the MLX run on purpose: PEFT’s lora_alpha/r is 2, so it uses the higher learning rate LoRA usually wants; MLX-LM’s scale of 20 does the same job at 1e-5. Use --backend hf in every command below.

4. The evaluator. ft_eval.py scores any model and adapter on the fifty tickets with classify.py’s parser, either with the short prompt the adapter learnt or with classify.py’s own few-shot prompt, and writes per-item results to ../evals/results/ in the same format:

"""Score a local model, with or without a LoRA adapter, on the 50 held-out tickets."""
import argparse, json, math, sys, time
from collections import Counter
from pathlib import Path

HERE = Path(__file__).parent
sys.path.insert(0, str(HERE.parent / "evals"))
from classify import ITEMS, LABELS, SYSTEM, build, parse_label
from common import messages

def chat(text, prompt):
    if prompt == "short":
        return messages(text)
    user, _ = build("few_shot", text, 0)       # the exact few-shot prompt classify.py sends
    return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}]

def mlx_backend(model, adapter):
    from mlx_lm import load, generate
    m, tok = load(model, adapter_path=adapter)
    def run(msgs):
        ids = tok.apply_chat_template(msgs, add_generation_prompt=True)
        return generate(m, tok, prompt=ids, max_tokens=8), len(ids)   # greedy by default
    return run

def hf_backend(model, adapter):
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer
    tok = AutoTokenizer.from_pretrained(model)
    m = AutoModelForCausalLM.from_pretrained(model, dtype=torch.bfloat16, device_map="auto")
    if adapter:
        from peft import PeftModel
        m = PeftModel.from_pretrained(m, adapter)
    m.eval()
    def run(msgs):
        text = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
        enc = tok(text, return_tensors="pt", add_special_tokens=False).to(m.device)
        n = enc["input_ids"].shape[1]
        with torch.no_grad():
            out = m.generate(**enc, max_new_tokens=8, do_sample=False)
        return tok.decode(out[0, n:], skip_special_tokens=True), n
    return run

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--backend", choices=["mlx", "hf"], default="mlx")
    ap.add_argument("--model", default="mlx-community/Qwen2.5-1.5B-Instruct-4bit")
    ap.add_argument("--adapter")
    ap.add_argument("--prompt", choices=["short", "few_shot"], default="short")
    ap.add_argument("--errors", action="store_true")
    a = ap.parse_args()
    run = (mlx_backend if a.backend == "mlx" else hf_backend)(a.model, a.adapter)
    rows, ptoks, t0 = [], 0, time.time()
    for it in ITEMS:
        raw, n = run(chat(it["text"], a.prompt))
        ptoks += n
        rows.append({**it, "pred": parse_label(raw), "raw": raw})
    n, ok = len(rows), sum(r["pred"] == r["label"] for r in rows)
    p = ok / n
    conf = Counter((r["label"], r["pred"]) for r in rows if r["pred"] != r["label"])
    tag = f"{'lora' if a.adapter else 'base'}-{a.prompt}"
    print(f"{tag:15} acc {p:5.0%} (±{1.96 * math.sqrt(p * (1 - p) / n):.0%})  {ok}/{n}  "
          f"unparsed {sum(r['pred'] not in LABELS for r in rows)}  prompt tokens/item {ptoks // n}  "
          f"{1000 * (time.time() - t0) / n:.0f} ms/item")
    print("                top confusions:", ", ".join(f"{t}->{q} x{c}" for (t, q), c in conf.most_common(3)) or "none")
    if a.errors:
        for r in rows:
            if r["pred"] != r["label"]:
                print(f"   #{r['id']:<3} {r['label']:>9} -> {r['pred']}: {r['text']}")
    out = HERE.parent / "evals" / "results" / f"{a.backend}-qwen15-{tag}.jsonl"
    out.write_text("".join(json.dumps(r) + "\n" for r in rows))

if __name__ == "__main__":
    main()
Nothing runs yet. Note what is held constant: the fifty items, the parser, the few-shot prompt (imported from classify.py, not copied) and greedy decoding with eight new tokens. The only things that vary are the prompt and the adapter. prompt tokens/item is counted from the rendered chat template, so it includes the template’s own special tokens.

5. Three rows on the same fifty tickets, plus the earlier baselines.

uv run --with mlx-lm==0.32.2 ft_eval.py --prompt few_shot
uv run --with mlx-lm==0.32.2 ft_eval.py --prompt short
uv run --with mlx-lm==0.32.2 ft_eval.py --prompt short --adapter adapters/qwen15-r8
# PEFT path: replace `--with mlx-lm==0.32.2` with `--with peft==0.21.0 --with trl==1.17.1`, add
# `--backend hf --model Qwen/Qwen2.5-1.5B-Instruct`, and use --adapter adapters/peft-r8
uv run ../evals/classify.py --variants few_shot structured                                   # llama3.2:3b, from prompting-fundamentals
uv run ../evals/classify.py --backend claude --model claude-haiku-5-5 --variants few_shot     # under one cent
Five scores. A typical shape: the base 1.5B model with the short prompt is the weakest, often 40 to 65%, with confusions wherever a label word is not obvious from the ticket; the same model with the few-shot prompt gains ten to twenty points at about 350 prompt tokens per item; llama3.2:3b few-shot is in the 60 to 80% range you saw before; Haiku 5.5 few-shot is in the high 80s or 90s; and the LoRA adapter with the 50-token prompt lands in the mid 80s to low 90s, close to Haiku and well above the 3B model, at tens of milliseconds per item on a laptop. Every interval is about ±10 points on fifty items, so the honest summary is ‘the adapter is in Haiku’s band and clearly above the prompted small models’, not a ranking of the top two. Your numbers will differ with the generated data and the seed.

6. Read where they disagree.

uv run python -c "
import json
a = {r['id']: r for r in map(json.loads, open('../evals/results/mlx-qwen15-base-few_shot.jsonl'))}
b = {r['id']: r for r in map(json.loads, open('../evals/results/mlx-qwen15-lora-short.jsonl'))}
for i in sorted(a):
    if (a[i]['pred'] == a[i]['label']) != (b[i]['pred'] == b[i]['label']):
        print(f\"#{i:<3} {a[i]['label']:>9}  few-shot {str(a[i]['pred']):>9}  lora {str(b[i]['pred']):>9}  {a[i]['text'][:70]}\")"
The tickets that one approach gets right and the other wrong (use peft file names on the PEFT path). Most of the adapter’s gains are on plainly worded tickets the small model misreads with a long prompt in front of them. Its remaining errors cluster on the ambiguous items from prompting-fundamentals (3, 7, 13, 24, 30, 48), which is where the teacher’s labels were noisiest in step 2. That is the ceiling a better teacher or human-labelled training data would raise, and no extra training steps will.

7. Check what the adapter cost the model.

for q in "What is the capital of France?" "Write one sentence about autumn."; do
  uv run --with mlx-lm==0.32.2 mlx_lm.generate --model mlx-community/Qwen2.5-1.5B-Instruct-4bit --max-tokens 40 --prompt "$q"
  uv run --with mlx-lm==0.32.2 mlx_lm.generate --model mlx-community/Qwen2.5-1.5B-Instruct-4bit --max-tokens 40 --prompt "$q" --adapter-path adapters/qwen15-r8
done
The base model answers both normally. With the adapter, answers are often shorter and flatter, and on some runs the model replies with a category word such as product to a question that has nothing to do with tickets, even though the classifier’s system prompt is absent. Six hundred examples of one-word answers moved the default. For a classifier behind an API this does not matter; it is exactly the regression you would ship if the same model also chatted with customers, and it is why a fine-tuned model is evaluated on what it used to do as well as on the new task.
The business adds a seventh team, fraud, for orders and charges the customer did not make. Copy the eval first (cp ../evals/tickets.jsonl ../evals/tickets.bak and cp ../evals/classify.py ../evals/classify.bak), then in classify.py append "fraud" to LABELS, add the line fraud: orders or charges the customer says they did not make to DEFINITIONS and one fraud example to EXAMPLES, and in tickets.jsonl relabel tickets 6 and 30 as fraud. Re-run Haiku few-shot: it picks up the new team at once, because the change was three lines of prompt. Re-run the adapter with the short prompt: it can never answer fraud, because it never saw the word as an answer, and adding fraud to SHORT_SYSTEM does little, because the adapter’s behaviour lives in its weights rather than in that line. Fixing it means regenerating data for seven labels and retraining. That asymmetry, a minute against an afternoon, recurs on every requirement change, and it belongs in the cost column next to the GPU. Restore both files from the copies when you are done.
ARTEFACT Write the fine-tuning business case ~50 MIN
YOU PRODUCEFine-tuning business case with a go/no-go

Template

# Fine-tuning business case: <task>
Owner <name, role> · Approver <name, role> · Date <date> · Decision needed: go or no-go by <date>
Scope: <the one task and the one place it runs>. Out of scope: <what stays as it is>.

## 1. The problem
<What fails today, for whom, measured how: score, latency, cost, volume per day.>

## 2. Alternatives tried first
| Alternative | What you changed | Score on the test items | Cost per month | Latency | Why it was not enough |
|---|---|---|---|---|---|
| Better prompt, few-shot | | | | | |
| Retrieval | | | | | |
| Bigger or hosted model | | | | | |

## 3. Data and labels
Source of examples: <real, teacher-labelled, synthetic>. Count: <train / validation>.
Who labels: <role>, <hours>. Labels you would change in a sample of 30: <n>.
Test set: <n> human-labelled items, checked for overlap with training data.

## 4. Costs, per month
Training: <>. Serving: <>. Retraining when labels or the base model change: <how often, cost>.
Break-even volume: <calls a day>. Assumptions: <list>.

## 5. Evaluation and upkeep
Tuned model vs best prompt on the same items: <score and interval>.
Checks on what the model used to do: <narrowing, refusals>.
Owner of retraining: <role>. Retrain when: <trigger>.

## 6. How this could be wrong
<One way, and what would show it.>

## 7. Decision
Go / no-go: <>. Stop condition: <score or cost>. Rollback: <how, how fast>.
Prepared <name, date>. Approved <name, date>.
WORKED EXAMPLE

At a real company the ML engineer on the support team writes this; the head of engineering and the head of support approve it. Setting: the shop’s ticket router, six labels, about three million tickets a day.

Decision needed. Go or no-go on a LoRA fine-tune of a 1.5B open model for the live suggestion in the contact form, which needs p95 under 150 ms. Out of scope: the final routing, which stays on Claude Haiku 5.5 with the few-shot prompt.

Alternatives first. Haiku 5.5 few-shot scores 91% on the 400-ticket human-labelled set, with p50 about 700 ms; the chapter’s hosted p50 is 600 to 900 ms, so prompt work moves accuracy, not the latency floor. llama3.2:3b few-shot scored 60 to 80% in earlier labs. Retrieval does not apply: the problem is a label boundary, not missing facts.

Data. Lab run: about 700 tickets from Haiku 5.5 for about $0.03; dropped 14 duplicates and 9 near the test tickets, kept 690 (621 train, 69 valid). The support team reads 30 and counts labels it would change; the lab expects two to four. Test items stay human-labelled.

Costs. Hosted: about $200 a day, $6,000 a month, with a 350-token prompt. Tuned: one rented GPU at $1 to $2 an hour, $750 to $1,500 a month, 50-token prompt. Break-even: the GPU’s $750 to $1,500 equals the hosted bill at 375,000 to 750,000 tickets a day, so below that the hosted model is cheaper; at 3 million a day the saving is $4,500 to $5,250 a month. Assumed: four engineer-weeks to build, not priced here.

Upkeep. Any new team, such as fraud, means regenerating data and retraining. A new base model means retraining.

Could be wrong. Fifty tickets give about ±10 points, so they cannot rank the adapter against Haiku. A gap on the 400-ticket set would show it.

Decision. Go, for the live suggestion only. Stop if the adapter falls below Haiku’s band on the 400 tickets. Rollback: the form calls the Haiku prompt again.

Now you

You work at Kolanut Mobile in its launch year: 45 people and 250,000 subscribers, most of them traders who recharge ₦100 or ₦200 at agent stalls. The customer-care team answers recharge questions, and the product lead wants a recharge-support assistant. Customers write in mixed Yoruba, Pidgin and English, and someone has proposed fine-tuning an open model so it handles that mix.

The chapter makes no claim about how any model handles Yoruba, Pidgin or the mix of them, so your case cannot assume it either. Say which alternatives you have scored on your own labelled messages and mark any you have not run as not yet run. Reuse the lab: its prompt-versus-adapter table, its overlap check, the label-noise count from step 2, the narrowing check in step 7 and the break step’s retraining cost. State your own volumes and prices as assumptions. Choose who labels and say what that costs.

The customer-care lead and the head of operations read it; the chief operating officer decides go or no-go.

Self-check

DECIDE

Your ticket router runs Claude Haiku 5.5 with a few-shot prompt: 91% on a 400-ticket human-labelled eval set, about three million tickets a day, p50 latency 700 ms. Product now wants the routing suggestion shown live in the contact form as the customer types, which needs p95 under 150 ms. A teammate proposes a LoRA fine-tune of a 1.5B open model. What do you do?

READING
  1. PAPER
    LoRA: Low-Rank Adaptation of Large Language Models Hu et al., 2021

    The method the lab uses, with the argument for why weight updates have low intrinsic rank. Short and clear. Read: sections 1, 4 and 7 (the rank analysis); skip the GPT-3 experimental tables.

  2. PAPER
    QLoRA: Efficient Finetuning of Quantized LLMs Dettmers, Pagnoni, Holtzman, Zettlemoyer, 2023

    4-bit NormalFloat, double quantisation and paged optimisers: why a 65B model fits on one GPU, and evidence that the 4-bit base costs little quality. Read: sections 1 to 3; section 5 on data quality versus quantity is worth reading too.

  3. POST
    LoRA Without Regret John Schulman and Thinking Machines, 2025

    The practical settings: when LoRA matches full fine-tuning, why to apply it to the MLP layers, the roughly tenfold learning rate, and the batch-size sensitivity. Read before you tune hyperparameters.

  4. PAPER
    LoRA Learns Less and Forgets Less Biderman et al., 2024

    The trade-off stated precisely: on hard new domains LoRA underperforms full fine-tuning, and it preserves the base model's other abilities better. The right framing for a narrow classifier. Read: the abstract, section 1 and the best-practices section at the end.

  5. PAPER
    Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations? Gekhman et al., 2024

    The controlled experiment behind the Predict: new facts are learnt slowly in fine-tuning and raise hallucination once learnt. Cite it the next time someone proposes fine-tuning on the documentation. Read: sections 1, 3 and 4; skip the knowledge-category taxonomy on a first read.

  6. PAPER
    Fine-tuning Aligned Language Models Compromises Safety, Even When Users Do Not Intend To! Qi et al., 2023

    The incident in the Why: ten examples undo refusal training, and benign data weakens it. Read for why every retrain runs your safety tests, not only your task eval. Read: sections 1 and 4.4 (benign fine-tuning); skip the attack construction details.

  7. BOOK
    AI Engineering: Building Applications with Foundation Models Chip Huyen, 2025

    The book-length treatment of when to fine-tune, memory arithmetic for training, PEFT methods, and model merging, with the decision framed against prompting and RAG. Read: chapter 7, Finetuning; the memory-bottleneck section pairs with the LoRA arithmetic here.

  8. CODE
    MLX-LM LoRA guide Apple ML Explore

    The reference for the commands in the lab: data formats, --mask-prompt, QLoRA on quantised models, fusing adapters and the memory-saving flags.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Prompt management, versioning and experimentation →