Skip to content

Lesson 30 of 40Building LLM systems

Prompting, RAG or Fine-Tuning: Making the Call

Decide when to prompt, retrieve or fine-tune: a ladder backed by evals, what fine-tuning really changes, LoRA and DPO, data prep and the ops cost.

20 min read0/5 questions

A product manager reads a blog post and opens a ticket: "Fine-tune a model on our help centre so the bot knows our product." It sounds reasonable, and it is usually the wrong move. Fine-tuning would cost weeks, go stale with the next docs update, and still not let the bot cite a source. But sometimes fine-tuning is exactly right, and a team that refuses it on principle ends up paying for a large model to do a small model's job two million times a day. RAG and Embeddings answered this question with one table. This lesson gives you the full decision: a ladder you climb only with evidence, what each rung actually changes, how fine-tuning works underneath, and what it costs to own.

The decision ladder

Every rung adds cost, time and things to maintain, so you only climb when an eval shows the rung below cannot reach the bar. "It feels like it is not good enough" is not evidence. A score on a labelled set is.

Climb only when the eval says so
Prompt + examples: hoursPrompt + exampleshoursBigger model or effort: a config changeBigger model or efforta config changeRAG or long context: daysRAG or long contextdaysTools: daysToolsdaysFine-tune: weeks + ongoingFine-tuneweeks + ongoingTrain from scratch: almost neverTrain from scratchalmost neverreasoning gapknowledge gapneeds live databehaviour or cost gaprarely

Start here, with an eval set. Clear instructions, a few good examples, a schema for structured output. This fixes more problems than people expect, and you need the eval anyway to judge every later rung.

1/6

Two questions sort most proposals before any work starts. Is the gap knowledge or behaviour? Knowledge (facts, documents, recent events) points to RAG or tools. Behaviour (format, style, a narrow skill, refusing the right things) points to prompting first, then possibly fine-tuning. Is the gap quality or cost? If a large model already does the job well and the problem is price or latency at volume, fine-tuning a small model on the large model's outputs is a legitimate goal in its own right.

What fine-tuning actually changes

Fine-tuning continues training a model on your examples, nudging its weights so the behaviour in those examples becomes its default. That is good at:

  • Format and structure: always producing your exact output shape, label set or template, without a long prompt explaining it.
  • Tone and style: your brand voice, your clinical note style, your terse internal-tool phrasing.
  • Narrow task skill: a classification or extraction task with its own subtle rules, learned from thousands of labelled cases rather than described in prose.
  • Shorter prompts: behaviour learned into weights does not need to be re-sent, which saves tokens on every call.
  • Distillation: a small, fast model trained on a large model's good outputs can match the large model on one narrow task. This is the most common reason companies fine-tune today.

It is bad at:

  • Adding facts. A model trained on your help centre does not reliably store and recall each fact; it learns the style of your help centre and still hallucinates details. It may even hallucinate more confidently.
  • Staying current. Every docs change means a new training run. RAG picks up a change when you re-index.
  • Citing sources. Weights have no record of which document taught what, so there is nothing to cite and nothing to check.
  • Access control. You cannot stop a fine-tuned model from revealing something one user may see and another may not. Retrieval can filter per user; weights cannot.

That last point is often missed and is decisive in enterprise settings. It also connects to privacy: personal data trained into weights cannot be deleted on request. You would have to retrain without it.

Quick check
HR wants a bot that answers questions about 300 internal policies, which change monthly and differ by country. Employees should only get answers for their own country. What do you build first?
Need a nudge? A hint rules out a wrong answer.

Methods in plain words

Supervised fine-tuning (SFT) is the base method: show the model input and ideal output pairs, and train it to produce the output. Almost every project starts here.

Full fine-tuning updates every weight. It needs memory for all the weights, their gradients and optimiser state, which for a 70B model means a cluster of large GPUs. It is rarely worth it outside labs.

LoRA (low-rank adaptation) freezes the base model and trains small add-on matrices next to some of its weight matrices. A weight matrix of size d × k gets two thin matrices, d × r and r × k, where the rank r is small (8 to 64). Only those are trained. The result is an adapter of a few megabytes to a few hundred megabytes that you load on top of the base model, and one server can host many adapters over one base. QLoRA does the same with the frozen base held in 4-bit precision, so a mid-size model can be tuned on a single GPU. Quality is close to full fine-tuning for most narrow tasks.

Python
# A made-up 8B-class transformer: 32 layers, hidden size 4096.LAYERS, HIDDEN = 32, 4096TOTAL_PARAMS = 8_000_000_000 def lora_params(rank, matrices_per_layer): # Each adapted d x k weight gets two small matrices: B (d x r) and A (r x k). per_matrix = rank * (HIDDEN + HIDDEN) return per_matrix * matrices_per_layer * LAYERS print(f"full fine-tune: {TOTAL_PARAMS:,} trainable parameters")for rank, mats, label in [(8, 2, "q,v"), (16, 2, "q,v"), (16, 4, "q,k,v,o"), (64, 4, "q,k,v,o")]: p = lora_params(rank, mats) print(f"LoRA r={rank:<2} on {label:<7}: {p:>11,} trainable " f"({p / TOTAL_PARAMS:.3%}), adapter file about {p * 2 / 1e6:.0f} MB in 16-bit") # Memory just to hold the frozen base weights during training:for name, bytes_per_param in [("16-bit base (LoRA)", 2), ("4-bit base (QLoRA)", 0.5)]: print(f"{name}: about {TOTAL_PARAMS * bytes_per_param / 1e9:.0f} GB")
Output
Press Run (⌘ Enter) to see what happens.

Even a generous adapter trains under 1% of the parameters. That is why LoRA is cheap, and also why it changes behaviour more than knowledge: there is little room to store new facts.

Predict the outputPython

What does this print?

r, d, k = 8, 1024, 1024
print(r * (d + k), d * k)
Need a nudge? Hints walk you through it.

Preference tuning teaches "this answer is better than that one" rather than "say exactly this". DPO (direct preference optimisation) trains on triples: a prompt, a chosen answer and a rejected answer. It is simpler and more stable than the older RLHF pipeline with a separate reward model, and it is good for style, helpfulness and "do not do this" behaviour that is hard to express as one ideal output.

Reinforcement fine-tuning (RFT) skips ideal outputs entirely. You provide prompts and a grader, code or a model that scores each attempt, and the model is trained to produce higher-scoring answers. It suits tasks with checkable answers (a correct diagnosis code, a passing test, a valid extraction) where you can grade more easily than you can write the perfect answer. Your grader becomes the definition of good, so a sloppy grader trains sloppy behaviour.

Match the pairs0/5 matched

Match each method to the data it needs.

Choose an item, then its match on the other side.

The data is the project

Most fine-tuning projects that fail, fail on data. What works:

  • Quality over quantity. For a narrow task, a few hundred to a low few thousand carefully checked examples typically beat tens of thousands of noisy ones. Every wrong label is a lesson in being wrong.
  • Cover the real distribution. Sample from production traffic, including the hard and rare cases, not only the tidy ones someone wrote by hand.
  • Use the provider's format. Most APIs and open-source trainers take chat-style JSONL: one JSON object per line with a messages list of system, user and assistant turns.
  • Split three ways. Train, validation (to stop training at the right point) and a held-out test set you never touch until the end.
  • Prevent leakage. Near-duplicates (the same ticket with different punctuation, the same customer writing twice) in both train and test make the test score lie. Group near-duplicates first, then split the groups.
Python
import json, random, re, hashlib random.seed(3)raw = [ ("My card was charged twice for order 5512", "billing"), ("my card was charged TWICE for order 5512!!", "billing"), # near-duplicate ("The export button does nothing on Safari", "bug"), ("How do I add a teammate to my workspace?", "how_to"), ("Refund please, I was charged twice", "billing"), ("App crashes when I upload a 2GB file", "bug"), ("Where can I change my invoice address?", "how_to"), ("Export to CSV is broken since yesterday", "bug"), ("How do I add a teammate to my workspace", "how_to"), # near-duplicate ("I want to cancel and get my money back", "billing"),] def fingerprint(text): """Normalise case, digits and punctuation so near-duplicates collide.""" norm = re.sub(r"\d+", "0", text.lower()) norm = re.sub(r"[^a-z0 ]", "", norm) return hashlib.sha1(" ".join(norm.split()).encode()).hexdigest()[:8] # Group by fingerprint, then split GROUPS, so duplicates never straddle train and test.groups = {}for text, label in raw: groups.setdefault(fingerprint(text), []).append((text, label))keys = sorted(groups)random.shuffle(keys)cut = int(len(keys) * 0.7)train = [ex for k in keys[:cut] for ex in groups[k]]test = [ex for k in keys[cut:] for ex in groups[k]]print(f"{len(raw)} examples, {len(groups)} unique after normalising")print(f"train {len(train)}, test {len(test)}")leaks = {fingerprint(t) for t, _ in train} & {fingerprint(t) for t, _ in test}print("leaked groups:", len(leaks)) SYSTEM = "Classify the support ticket as billing, bug or how_to. Reply with the label only."def to_chat_jsonl(text, label): return json.dumps({"messages": [ {"role": "system", "content": SYSTEM}, {"role": "user", "content": text}, {"role": "assistant", "content": label}, ]})print("\nfirst training line:")print(to_chat_jsonl(*train[0]))
Output
Press Run (⌘ Enter) to see what happens.

Synthetic data from a bigger model is how most distillation works: run the large model on real inputs, keep the outputs that pass your checks, and train the small model on them. It is fast and cheap, with three risks. The student learns the teacher's mistakes, so filter with graders or human review. Synthetic inputs tend to be cleaner and more uniform than real ones, so mix in real traffic. And provider terms of service may restrict using outputs to train other models, so check the terms of the model you distil from with whoever owns legal questions.

Where you can do it

  • Provider fine-tuning APIs. OpenAI, Google Vertex AI and Amazon Bedrock offer fine-tuning or customisation for selected models: you upload JSONL, they train and host the result. Which models, which methods (SFT, DPO, RFT) and which regions are supported changes often, so check the current docs. Many frontier models offer no public fine-tuning at all; Anthropic's first-party Claude API, for example, does not offer it.
  • Open-weight models on your own GPUs. Take an open-weight model and train adapters with Hugging Face TRL, Unsloth or Axolotl on rented cloud GPUs. You own the weights and can host them anywhere, and you also own every problem: training infrastructure, serving, security patches and evaluation.

Confirm early that the model you want can be fine-tuned where you need it. Teams have spent weeks building a dataset for a model that turned out not to support tuning in their region.

The cost of owning a custom model

The training run is the cheap part. The ongoing costs are what to put in the proposal:

  • Serving. Custom models are often priced higher per token than the base model, or need dedicated capacity you pay for whether it is busy or not. Self-hosting means GPUs, autoscaling and on-call.
  • Base model deprecation. Providers retire models. When your base is retired, you retrain on the successor and re-run every eval. Budget for that at least yearly.
  • Regressions. Training hard on one task can degrade others, known as catastrophic forgetting. Keep a general sanity eval (safety, instruction following, a few unrelated tasks) next to the task eval, and run both on every new version.
  • A data pipeline forever. New edge cases appear; the training set needs curating, versioning and re-running. The dataset is now a product with an owner.

Compare all of that with the alternative honestly: sometimes a larger model with a good prompt costs more per call but far less per year.

Worked scenarios

Support ticket classifier at 2 million tickets a day. A large model with a careful prompt hits 96% on the eval, but cost and latency at that volume are serious. A small model with the same prompt hits 89%. Fine-tune the small model on 3,000 labels (human labels plus large-model labels that passed review) and it reaches 95% at a fraction of the cost and latency. This is the textbook case: narrow, stable labels, huge volume, a measured gap.

Policy Q&A. Knowledge, frequent changes, citations, access control: RAG, as in the quiz above.

Brand voice for marketing drafts. Start with a style guide and five to ten excellent examples in the prompt, and score drafts with a rubric. Fine-tune only if the voice still drifts after that, and then probably with DPO on pairs your editors marked better and worse.

Structured extraction from invoices. Prompt plus strict schema plus semantic checks (as in Structured Outputs and Tool Schemas) usually gets there with a capable model. Fine-tune a smaller model later if volume makes cost the problem, using the validated outputs of the working system as training data.

Quick check
Your classifier on a large model scores 96% and meets the bar, but at 2 million calls a day the bill and the latency are a problem. A small model with the same prompt scores 89%. What is the strongest next step?
Need a nudge? A hint rules out a wrong answer.
Put it in order6 steps

Put a fine-tuning project in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
supervised fine-tuning
Continuing a model's training on input and ideal-output pairs so that behaviour becomes its default.
LoRA
Low-rank adaptation: freeze the base model and train small add-on matrices, producing a compact adapter.
QLoRA
LoRA with the frozen base model held in 4-bit precision, so larger models fit on less GPU memory.
DPO
Direct preference optimisation: training on pairs of chosen and rejected answers to the same prompt.
reinforcement fine-tuning
Training a model to maximise scores from a grader instead of copying ideal outputs.
distillation
Training a smaller model on a larger model's outputs so it matches the larger one on a narrow task.
catastrophic forgetting
A fine-tuned model losing skills it had before because training focused hard on one task.