Summary#
There are three ways to make a general-purpose large language model (LLM) good at your task, in rising order of cost:
- Prompting. Instructions, examples and output formats in the context window. Instant to change, and usually the first 80% of the quality.
- Retrieval-augmented generation (RAG). Fetch relevant documents and put them in the prompt. This is how a model gets knowledge that is fresh, private or citable.
- Fine-tuning. Continue training the model's weights on your examples. This is how a model learns behaviour: a consistent format, tone or style, a narrow skill, domain jargon, or doing with a small cheap model what a large model does with a long prompt.
Fine-tuning has stages:
- Supervised fine-tuning (SFT), also called instruction tuning, trains on prompt-response demonstrations.
- Preference tuning trains on comparisons ("response A is better than B"). It comes in two main forms:
- RLHF trains a reward model, then optimises the LLM with reinforcement learning against it.
- DPO optimises directly on preference pairs, with no separate reward model.
- Parameter-efficient fine-tuning (PEFT) makes all of this affordable. LoRA freezes the base weights and trains small low-rank matrices beside them. QLoRA does the same on a 4-bit quantised base, so models with tens of billions of parameters fit on a single GPU.
Data quality decides the outcome. A few thousand clean, diverse, representative examples routinely beat a hundred thousand noisy ones.
Evaluation is the other half of the job, and the half teams most often skip:
- Public benchmarks for general capability, with a large grain of salt.
- Task-specific evals on your own data, with programmatic checks where possible.
- LLM-as-judge for open-ended output, calibrated against humans.
- Human evaluation for the final word.
These run offline before shipping and online (A/B tests, user feedback, sampled grading) after. A regression suite runs on every prompt, model or data change. Hallucination and safety metrics (groundedness, factual precision, refusal rates, jailbreak resistance) get their own tracking.
Serving. Fine-tuned LoRA adapters can be served cheaply: one shared base model on the GPU, with many small adapters swapped or batched per request.
Why It Exists#
General models are trained to be broadly helpful. Products need something narrower and more dependable:
- Consistency. A support bot must always answer in the company voice, follow policy, and return valid JSON for downstream code, ten million times a day. Prompts get you close. Variance at scale still hurts.
- Cost and latency. A frontier model with a 3,000-token prompt of instructions and examples is slow and expensive per call. A small model fine-tuned on the same behaviour can be several times cheaper and faster, and can run on your own hardware or devices.
- Specialised skills and language. Legal clause classification, medical coding, an internal query language, a rare programming language. The base model has seen little of it.
- Control and privacy. Self-hosted open-weight models, tuned on private data, keep data in-house and remove dependency on a provider's model updates.
Why evaluation exists. LLM outputs are open-ended and non-deterministic, and ordinary unit tests don't capture "is this answer good?". Without a systematic evaluation practice, every change is a gamble. A prompt tweak that fixes one complaint can silently break ten other cases. A provider's model update can change behaviour overnight. A fine-tune can improve the target task while making the model worse at following instructions, or more prone to hallucinate. Evaluation turns "it seems better" into a measured, repeatable decision, the same role tests and canaries play for ordinary software (CI/CD and Deployment Strategies).
How It Works#
The full lifecycle of adapting a model looks like any ML lifecycle, with evaluation at the centre (ML System Design and Feature Stores):
The sections that follow cover the decision between prompting, RAG and fine-tuning; the training methods; parameter-efficient tuning; data; evaluation methods, offline and online; regression suites; hallucination and safety measurement; and serving.
Prompting vs RAG vs fine-tuning: the decision#
The three techniques solve different problems and combine freely. The key question is what's actually missing: knowledge or behaviour?
| Need | Best first tool | Why |
|---|---|---|
| Facts that change (prices, policies, tickets) | RAG | Update the index, not the weights; answers can cite sources |
| Private or per-user data | RAG with permission filters | Access control at retrieval time; nothing baked into weights |
| A specific output format or schema | Prompting plus structured output; fine-tune if still flaky | Constrained decoding often solves it outright |
| Consistent tone, style or persona at scale | Fine-tuning (SFT) | Habits are learned better from examples than instructions |
| A narrow classification or extraction task at high volume | Fine-tune a small model | Large cost and latency savings at equal quality |
| Shorter prompts and lower latency | Fine-tune to internalise long instructions | Removes thousands of prompt tokens per call |
| Domain language or a rare programming language | Fine-tuning (sometimes continued pre-training) | The base model lacks exposure |
| Better reasoning on a verifiable task (math, code) | Prompting first; RL with verifiable rewards for model builders | Expensive; only worth it at scale |
| Citable, auditable answers | RAG | Fine-tuned facts can't be traced to a source |
Why fine-tuning is a poor way to add facts:
- Facts don't stick reliably. Training on documents teaches the model to imitate their style and recall facts approximately, without citations, and those facts are frozen at training time.
- It can make hallucination worse. Research such as "Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?" (Gekhman et al., 2024) found that teaching a model many facts it didn't already know made it more prone to confident errors.
- Updating is a retrain. Changing one fact means another training run.
- Use RAG for knowledge, and fine-tune for how the model uses knowledge: to quote retrieved passages faithfully, say "I don't know" when the context lacks the answer, and follow your format.
Combining them. Mature systems often use all three:
- a fine-tuned model that has learned the product's format, tone and refusal behaviour;
- RAG supplying current facts;
- a short prompt carrying task-specific instructions.
This is sometimes called RAFT-style training (retrieval-augmented fine-tuning): fine-tune on examples that include retrieved context, some of it deliberately irrelevant, so the model learns to use good passages and ignore distractors.
Cost reality check. Before fine-tuning, estimate the full cost:
- data collection and labelling, often the largest cost;
- training runs, from tens of dollars for LoRA on a small model to far more for large models and many runs;
- evaluation;
- serving infrastructure, if self-hosting;
- ongoing maintenance: when the base model is upgraded, you retrain and re-evaluate.
A prompt is free to iterate. A fine-tune is a model you now own.
Supervised fine-tuning, instruction tuning and preference tuning#
Modern assistant models are built in stages. Knowing them tells you which one to use for your own adaptation.
Stage 0: pre-training. Next-token prediction over trillions of tokens of text and code. It produces a base model, which completes text but doesn't reliably follow instructions. Almost nobody outside model labs does this. A related, cheaper step, continued pre-training on a large domain corpus (legal, biomedical, a codebase), is occasionally used to shift a model's vocabulary and knowledge before instruction tuning.
Stage 1: supervised fine-tuning (SFT) and instruction tuning.
- What it is. Train on (prompt, ideal response) pairs with the same next-token loss, usually computing the loss only on the response tokens, so the model learns to produce answers, not to repeat questions.
- Instruction tuning is SFT over many diverse tasks phrased as instructions. "Finetuned Language Models Are Zero-Shot Learners" (FLAN, Wei et al., 2021) showed this makes models far better at following unseen instructions.
- Quality beats quantity. "LIMA: Less Is More for Alignment" (Zhou et al., 2023) fine-tuned a strong base model on only about 1,000 carefully curated examples and got a capable assistant. The argument: most knowledge comes from pre-training, and SFT mainly teaches format and style.
- For product teams, SFT is the workhorse. It teaches the output format, tone, domain conventions, tool-call style or classification labels from a few hundred to tens of thousands of examples.
- Chat formatting matters. Training data must use the exact chat template the model expects (system, user and assistant role markers, special tokens). A template mismatch between training and serving is a classic silent bug.
Stage 2: preference tuning. Demonstrations show one good answer. Many qualities (helpfulness, harmlessness, concision, honesty) are easier to judge comparatively than to write perfectly. Preference tuning trains on comparisons: for a prompt, response A was preferred over response B.
RLHF (reinforcement learning from human feedback). It was popularised for assistants by "Training language models to follow instructions with human feedback" (InstructGPT, Ouyang et al., 2022). It has three steps:
- SFT on demonstrations.
- Train a reward model. It takes (prompt, response) and outputs a scalar, trained so the chosen response scores higher than the rejected one.
- Reinforcement learning. Optimise the LLM (the "policy") to maximise reward with PPO (Proximal Policy Optimization, Schulman et al., 2017). Add a KL-divergence penalty that keeps it close to the SFT model, so it doesn't "reward hack" by drifting into weird text the reward model happens to like.
The InstructGPT paper reported that labellers preferred outputs from a 1.3-billion-parameter InstructGPT model over the 175-billion-parameter GPT-3. Alignment to what users want mattered more than raw size.
The cost is complexity. RLHF juggles four models at once (policy, reference, reward model, value model), PPO is notoriously finicky to tune, and the reward model is itself a source of errors.
DPO (Direct Preference Optimization). "Direct Preference Optimization: Your Language Model is Secretly a Reward Model" (Rafailov et al., NeurIPS 2023) showed that the RLHF objective (maximise reward with a KL penalty) has a closed-form optimal policy. Rearranged, preferences can be optimised directly with a simple classification-style loss on (chosen, rejected) pairs:
- No reward model, no sampling during training, no RL loop. Just the policy and a frozen reference copy.
- It's stable and cheap, and became the default preference-tuning method for many open models and for product teams.
- Variants exist. IPO addresses overfitting to deterministic preferences. KTO uses unpaired thumbs-up or thumbs-down labels, which is handy because products naturally collect those. ORPO folds the preference term into SFT. SimPO removes the reference model. (The Deep Dive covers the maths.)
RLAIF and constitutional approaches. Human preference labels are slow and expensive. "Constitutional AI: Harmlessness from AI Feedback" (Bai et al., Anthropic, 2022) used a written set of principles and had a model critique and revise its own outputs, then generate the preference labels, cutting human labelling for harmlessness. AI feedback with a strong judge model is now widely used to scale preference data, with humans auditing samples.
RL with verifiable rewards. For tasks with checkable answers (maths, code that must pass tests), the reward can come from a verifier instead of a learned reward model, which removes most reward-hacking risk. "DeepSeekMath" (Shao et al., 2024) introduced GRPO (Group Relative Policy Optimization), which scores several sampled answers per prompt relative to each other instead of training a value model. DeepSeek later used large-scale RL of this kind to train its R1 reasoning model (2025). For most product teams this is model-builder territory, but the principle carries over: if you can verify outputs automatically, you can both train and evaluate against that check.
What each stage is good for in practice:
| Goal | Method |
|---|---|
| Learn a format, style, label set or tool-call pattern | SFT (LoRA) |
| Prefer concise over verbose, polite over curt, safe over risky | DPO or KTO on preference data |
| Distil a big model's behaviour into a small one | SFT on the big model's outputs (distillation), then evaluate |
| Improve on a verifiable task (SQL that runs, code that passes) | Rejection sampling (keep only verified outputs) plus SFT, or RL with a verifier |
| Make the model refuse or comply appropriately | SFT on examples plus preference tuning on safe and unsafe pairs |
Catastrophic forgetting and the alignment tax.
- Forgetting. Fine-tuning on a narrow task can degrade general abilities: instruction following, other languages, reasoning, safety behaviour.
- Mitigations:
- mix in some general instruction data;
- use LoRA, which changes fewer parameters;
- keep learning rates and epochs modest;
- always evaluate general capability and safety alongside the target task.
- Safety can be undone. Research has shown that safety tuning can be weakened by fine-tuning even on benign-looking data, so re-run safety evals after every fine-tune.
Parameter-efficient tuning: LoRA and QLoRA#
Why full fine-tuning is expensive. Updating every weight of a model needs memory for:
- the weights;
- their gradients;
- the optimiser state. Adam keeps two extra numbers per parameter.
In mixed precision that's roughly 16 bytes per parameter: 2 for the bf16 weights, 2 for the gradients, 4 for an fp32 master copy, and 8 for Adam's two moments. A 7-billion-parameter model therefore needs about 112 GB before activations, which means several 80 GB GPUs with sharding (DeepSpeed ZeRO, PyTorch FSDP). Each fine-tuned variant is also a full 14 GB copy to store and serve.
LoRA (Low-Rank Adaptation). Introduced in "LoRA: Low-Rank Adaptation of Large Language Models" (Hu et al., 2021).
- Core idea. The change fine-tuning makes to a weight matrix tends to be low-rank. So freeze the original matrix W (size d × k) and learn the update as a product of two thin matrices: W' = W + (α / r) · B·A.
- A is r × k and B is d × r, with a small rank r (typically 8–64).
- B starts at zero, so training begins exactly at the base model.
- α is a scaling hyperparameter.
- Where it goes. LoRA is usually applied to the attention projections (query, key, value, output) and often to the MLP layers too. Adding the MLP layers generally improves quality for a modest cost.
- The savings.
- Few trainable parameters. For a 4096 × 4096 matrix at r = 16: 2 × 4096 × 16 = 131,072 trainable values instead of 16.8 million, under 1%. Across all attention matrices of a 7B model, that's roughly 17 million trainable parameters, about 0.25% of the model.
- Little memory. Gradients and optimiser state exist only for those, so memory is dominated by the frozen bf16 weights (about 14 GB for 7B) plus activations. A 7B LoRA run fits on one 24–48 GB GPU.
- Tiny artefacts. The adapter file is tens of megabytes. You can keep hundreds of adapters for one base model.
- Free merging. At deployment, B·A can be added into W once, giving zero extra inference latency. Or the adapter can stay separate and be swapped per request.
- Paper result. On GPT-3 175B, the authors reported matching or beating full fine-tuning on their benchmarks while reducing trainable parameters by about 10,000× and GPU memory by about 3×.
QLoRA. Introduced in "QLoRA: Efficient Finetuning of Quantized LLMs" (Dettmers et al., 2023).
- Core idea. Quantise the frozen base model to 4 bits and train LoRA adapters in higher precision on top.
- Three ingredients:
- NF4 (4-bit NormalFloat). A 4-bit data type whose levels are spaced for normally distributed weights, so it loses less information than uniform 4-bit.
- Double quantisation. The quantisation constants are themselves quantised, saving about 0.37 bits per parameter.
- Paged optimisers. Unified memory spills optimiser state to CPU RAM during memory spikes, avoiding out-of-memory crashes on long sequences.
- Results. The paper fine-tuned a 65B model on a single 48 GB GPU. The resulting Guanaco models were competitive with ChatGPT on the Vicuna benchmark, as judged by GPT-4 and humans.
- Weights become about 0.5 bytes per parameter, so a 7B base needs about 4 GB and a 70B about 35–40 GB.
- The trade-offs.
- Training is somewhat slower because weights are dequantised on the fly.
- Quality is usually close to 16-bit LoRA.
- You must decide how to serve: either keep the quantised base or merge into a higher-precision copy. Merging into a quantised model needs care.
Choosing LoRA hyperparameters. These are practical defaults, not laws:
- Rank r. 8–16 for style and format tasks, 32–64 when the task is further from the base model's abilities. Higher rank adds capacity and more risk of overfitting small datasets.
- Alpha. Often set to r or 2r. Some libraries offer rsLoRA scaling (α / √r), which keeps updates stable as rank grows.
- Target modules. All linear layers usually beat attention-only.
- Learning rate. LoRA tolerates higher learning rates than full fine-tuning, around 1e-4 to 2e-4 versus about 1e-5.
- Epochs. 1–3 is typical, with early stopping on a validation set. More epochs on a few thousand examples quickly memorises them.
Other parameter-efficient methods:
- Adapters ("Parameter-Efficient Transfer Learning for NLP", Houlsby et al., 2019) insert small bottleneck layers between transformer sub-layers. This adds a little inference latency because they can't be merged away.
- Prefix tuning (Li and Liang, 2021) and prompt tuning (Lester et al., 2021) learn "soft prompt" vectors prepended to the input or to every layer. They're very small, but generally weaker than LoRA on hard tasks.
- IA³ learns per-channel scaling vectors, even smaller than LoRA.
- DoRA (Liu et al., 2024) decomposes weights into magnitude and direction and applies LoRA to the direction. It often closes some of the remaining gap to full fine-tuning.
In practice, LoRA or QLoRA is the default for product fine-tunes. Reach for full fine-tuning only with large datasets, a big quality gap, and the budget to serve a dedicated model.
Data preparation#
Data quality decides fine-tuning outcomes more than any hyperparameter. LIMA's 1,000 examples worked because they were carefully curated, and a 50,000-example scrape full of inconsistent answers teaches inconsistency.
Where examples come from:
- Production logs. Real user inputs paired with good outputs: human-corrected outputs, accepted suggestions, or highly rated responses. These are the most representative, but they need consent, PII scrubbing and quality filtering.
- Expert-written demonstrations. Expensive, but they set the quality ceiling. Use them for the hardest and highest-value cases.
- Synthetic data from a stronger model. Generate inputs that cover your task space, generate answers with a frontier model and a careful prompt, then filter. "Self-Instruct" (Wang et al., 2022) and Stanford's Alpaca (2023) popularised this.
- Check the stronger model's terms of use, since some providers restrict training competing models on outputs.
- Synthetic data inherits the teacher's errors, so verify where you can: run generated code, check SQL against a database, have a judge or human review samples.
- Rejection sampling and self-distillation. Sample several answers from your own model, keep only those that pass a verifier or score highly, and train on those.
Cleaning and shaping:
- Deduplicate. Exact and near-duplicates (MinHash) over-weight some examples and leak between train and test splits.
- Filter for quality. Remove truncated, wrong, off-policy (for example, the assistant refusing when it should help) and inconsistent examples. A judge model or simple heuristics (length, format checks) can pre-filter, with humans spot-checking.
- Scrub PII and secrets. Models can memorise and regurgitate training data, so redact names, emails, keys and tokens, or don't use that data at all. Respect data-deletion obligations: once data is trained into weights, "deleting" it means retraining (Security Fundamentals for System Design).
- Balance. Cover all intents, languages and edge cases in proportion to their importance, not just their frequency. Include examples of what the model should refuse or say "I don't know" to, or it'll learn to always answer.
- Format consistently. Use the exact chat template and system prompt you'll use at inference. Use consistent output schemas, so JSON fields are always present and in the same order.
- Mix in general data. A slice of general instruction data (often 5–20%) reduces catastrophic forgetting of broader abilities.
Splits and contamination:
- Hold out evaluation data before anything else, and split by user, document or time, not randomly by row. Near-duplicate rows from the same conversation in both train and test inflate scores.
- Keep a frozen "golden" test set that's never trained on, never used for prompt tuning, and versioned. If its examples leak into training (contamination), your eval numbers become meaningless.
- Track data lineage. Record which dataset version, filters and teacher model produced each training run, just like the feature and dataset versioning in ML System Design and Feature Stores.
How much data? A rough guide:
| Task | Typical examples |
|---|---|
| Output format or style | A few hundred to a few thousand |
| Classification or extraction | 1,000–10,000 |
| New skill (domain SQL, a code style) | 10,000–100,000 |
Start small, measure, then add data targeted at the failure categories your evals reveal. A learning curve (quality at 25%, 50% and 100% of the data) tells you whether more data will help.
Evaluating LLMs#
LLM evaluation is hard for three reasons:
- Outputs are open-ended. Many different answers can be correct.
- Quality is multi-dimensional: correctness, helpfulness, tone, safety, format, latency, cost.
- Behaviour is stochastic and prompt-sensitive. The same model can score differently with a reworded prompt.
So production teams use layers of evaluation, each answering a different question.
1. Public benchmarks: useful for picking a base model, weak for your product.
| Benchmark | What it measures |
|---|---|
| MMLU (Hendrycks et al., 2021) | Multiple-choice knowledge across 57 subjects |
| GSM8K (Cobbe et al., 2021) | Grade-school maths word problems; multi-step reasoning |
| HumanEval (Chen et al., 2021) | 164 Python problems checked by unit tests; reports pass@k |
| TruthfulQA (Lin et al., 2021) | Questions designed to elicit common misconceptions |
| SWE-bench (Jimenez et al., 2023) | Resolving real GitHub issues in real repositories, verified by tests |
| HELM (Liang et al., 2022) | A holistic suite across many scenarios and metrics, including calibration, robustness, bias and efficiency |
| MT-Bench and Chatbot Arena (Zheng et al., 2023) | Multi-turn chat quality via a judge model, and crowd-sourced pairwise human votes ranked with an Elo-style or Bradley–Terry model |
The limits of benchmarks:
- Contamination. Benchmark questions leak into pre-training data from the web, which inflates scores.
- Saturation. Top models cluster near the ceiling, so differences become noise.
- Format sensitivity. Few-shot formatting, prompt wording and answer extraction can shift scores by several points.
- Mismatch. A model that wins MMLU may be worse at your support tickets.
Treat benchmarks as a coarse filter. Never use them as the launch gate for a product change.
2. Task-specific evals: the core of LLM engineering. Build a dataset of real inputs from your product, each with an expected outcome, and a grader per example. The grader type depends on how checkable the output is. Prefer the cheapest reliable grader.
| Output type | Grader |
|---|---|
| Classification or extraction | Exact match, F1, per-field accuracy |
| Structured output (JSON, SQL) | Schema validation; execute it and compare results |
| Code | Run unit tests (pass@k) |
| Retrieval (RAG) | Recall@k and MRR of the retriever on labelled queries |
| Free text with a reference | Similarity to the reference, or LLM-as-judge against the reference |
| Free text without a reference | LLM-as-judge with a rubric, plus human review samples |
Older n-gram metrics (BLEU, ROUGE) correlate poorly with human judgement for open-ended generation. Use them for translation-like tasks, not chat quality.
3. LLM-as-judge. A strong model grades outputs, either scoring them against a rubric or picking the better of two. "Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena" (Zheng et al., 2023) found GPT-4's judgements agreed with human preferences over 80% of the time, about the same rate at which humans agree with each other. That made judge-based grading the scalable default. The paper also documented the biases you must design around:
| Bias | What happens | Mitigation |
|---|---|---|
| Position bias | Prefers the first or second answer in a pair | Judge both orders; count a win only if consistent, otherwise a tie |
| Verbosity bias | Prefers longer answers | Rubric that rewards concision; length-controlled comparisons |
| Self-preference | Favours outputs from its own model family | Use a judge from a different family, or several judges |
| Limited reasoning | Misgrades maths or code it can't solve | Give it the reference answer, or use execution-based graders |
Judge best practices:
- Use specific rubrics. "Score 1–5: does the answer cite only the provided documents? Does it answer the question asked?" works far better than "Is this good?".
- Ask for reasoning before the score (chain-of-thought), as G-Eval (Liu et al., 2023) did.
- Prefer binary or pairwise judgements over fine-grained scales. Judges are more consistent at "A or B?" and "pass or fail?" than at "7 versus 8 out of 10".
- Calibrate against humans. Have humans label 100–300 examples and measure the judge's agreement. Cohen's kappa is better than raw accuracy because it corrects for chance. Re-check whenever the judge model or rubric changes.
- Pin the judge. Fix the judge's model version, prompt and temperature (0). A judge upgrade changes all your scores.
4. Human evaluation. It stays the ground truth for subjective quality and the arbiter for high-stakes launches.
- Use trained raters with written guidelines. Measure inter-rater agreement. Low agreement means the guidelines, not the raters, need work.
- Prefer side-by-side (pairwise) blind comparisons over absolute scores.
- Sample smartly. Spend human effort on disagreements between judge and metrics, on new failure categories, and on safety-sensitive slices.
- Use domain experts (doctors, lawyers, senior engineers) for expert domains. Crowd raters can't judge correctness there.
Offline and online evals#
Offline evals run before release on fixed datasets. They're cheap, repeatable and safe, and they gate changes. Online evals measure the real system with real users, which is the only place you learn true impact. You need both, because offline datasets drift away from real traffic and online metrics arrive too late to stop a bad deploy.
Online signals, from strongest to weakest:
- Task outcomes. The ticket was resolved without escalation, the generated code was committed, the suggestion was accepted, the user converted. These carry the most weight but are slow and noisy.
- Implicit feedback. Regenerate clicks, copy actions, edits to the output, conversation abandonment, follow-up questions that rephrase the same need.
- Explicit feedback. Thumbs up or down. It's sparse (often under 1–2% of responses) and skewed toward complaints, but valuable as labelled failure cases.
- Sampled judge scores. Run the offline judge on a random sample of production traffic (say, 1%), scoring groundedness, safety and format, and track it as a time series. This catches drift when users start asking new things.
- Operational metrics. Time to first token, total latency, tokens per request, cost per conversation, error rate, refusal rate (Observability: Logs, Metrics and Traces).
Online A/B tests for LLM changes use the same machinery as any experiment (Design an A/B Testing and Experimentation Platform). Pick one primary metric and several guardrails (latency, cost, safety-flag rate, complaint rate). Randomise by user, not by request, so one person doesn't see inconsistent behaviour. Run long enough to get past novelty effects.
Regression suites#
A regression suite is the LLM version of a unit-test suite. It's a versioned set of cases that every change must pass before it ships. Without one, a prompt tweak that fixes one complaint silently breaks three other behaviours, and nobody notices until users do.
What goes in it:
- A golden set. A few hundred to a few thousand representative cases, stratified by intent, language, difficulty and customer tier, with expected outcomes.
- Bug-derived cases. Every production failure that gets fixed becomes a permanent test. This is the most valuable part, because it encodes hard-won knowledge.
- Capability probes. Format compliance (valid JSON, required fields), tool-call correctness, instruction following ("respond in Spanish", "under 100 words").
- Safety and policy cases. Jailbreak attempts, disallowed requests, PII-leak probes, prompt-injection payloads, plus benign requests that look risky, to catch over-refusal.
- General-capability probes for fine-tunes. A slice of general tasks catches catastrophic forgetting.
How it runs:
- Triggers. On every pull request that touches prompts, model versions, adapters, retrieval config or tool schemas, as part of the pipeline in CI/CD and Deployment Strategies. Run a fast subset of about 200 cases on each pull request and the full suite nightly and before release.
- Determinism where possible. Temperature 0 and a fixed seed if the provider supports it. For stochastic features, run each case k times and grade the pass rate.
- Gates are per slice, not just overall. "Overall pass rate didn't drop more than 1 point" and "no slice dropped more than 3 points" and "zero regressions on the critical-safety set". An average can hide a collapse in one language or customer segment.
- Diff reports. Show which cases flipped from pass to fail, with the outputs side by side. Reviewers read the diffs, not just the score.
- Version everything. Pin the suite, the judge prompt and model, and the system under test, so a score change can be attributed to exactly one change.
Handling noise. With 500 cases and a true pass rate of 90%, the standard error is √(0.9 × 0.1 / 500) ≈ 1.3 points. A 1-point drop is therefore within noise. Use paired comparisons on the same cases (which flipped?) and confidence intervals, covered in the third Deep Dive, before you block or celebrate a change.
Hallucination and safety metrics#
What "hallucination" means. Precise names lead to precise metrics. There are two kinds:
- Faithfulness (groundedness) errors. The output contradicts, or isn't supported by, the provided context: the retrieved documents, the user's file, the tool result. This is the main metric for RAG and summarisation, and it's checkable because the source is right there.
- Factuality errors. The output contradicts world knowledge with no source provided. This is harder to check, because you need a reference or a retrieval step to verify against.
Metrics and techniques:
| Metric | How it works | Fits when |
|---|---|---|
| Groundedness or faithfulness rate | Split the answer into claims; a judge (or an NLI entailment model) checks each claim against the context; report the supported fraction | RAG answers, summaries, support bots |
| Citation precision and recall | Does each cited passage actually support the sentence that cites it? Are all claims cited? | Answers with citations |
| FActScore (Min et al., 2023) | Break long-form text into atomic facts and verify each against a knowledge source such as Wikipedia | Long-form factual generation (biographies, reports) |
| SelfCheckGPT (Manakul et al., 2023) | Sample several answers; facts the model is unsure of vary between samples, while consistent facts are more likely true | No reference or retrieval available |
| Answer correctness against reference | Judge compares the answer with a known-correct answer | Golden sets with labelled answers |
| Abstention quality | On unanswerable questions, does the model say it doesn't know? On answerable ones, does it avoid needless refusals? | Any question-answering product |
| Calibration | When the model says it's confident, is it right that often? Measured with expected calibration error | Systems that expose confidence or route on it |
RAG-specific frameworks such as RAGAS (Es et al., 2023) package metrics like faithfulness, answer relevance, context precision and context recall. They separate "the retriever didn't find the right document" from "the generator ignored the document". That distinction tells you which half of the system to fix (AI Agents, Tool Use and Advanced RAG).
Worked example. A support bot answers 2,000 sampled conversations a day.
- The judge extracts an average of 4 claims per answer, so 8,000 claims a day.
- 7,680 are supported by the retrieved articles: a 96% claim-level groundedness.
- At the answer level, 260 answers contain at least one unsupported claim: 13% of answers.
The answer-level rate is what users feel, so set the target there (for example, under 5% for answers containing an unsupported claim). Then break failures down by cause: retrieval miss, outdated article, or model embellishment.
Safety metrics. Measure both directions, since a model can fail by being too permissive or too restrictive:
- Harmful-compliance rate. On a red-team set of disallowed requests, the fraction the model fulfils. Lower is better. Public sets such as HarmBench (Mazeika et al., 2024) give a baseline. Your own policy-specific cases matter more.
- Jailbreak attack success rate. The same as above, but with adversarial wrappers: role-play, encodings, multi-turn escalation, prompt injection via documents. Track it per attack family.
- Over-refusal rate. On benign prompts that superficially resemble harmful ones ("how do I kill a Python process?"), the fraction refused. XSTest (Röttger et al., 2023) was built for this. Over-refusal is a real product failure, and safety tuning tends to increase it.
- Toxicity and bias.
- Classifier-scored toxicity of outputs on prompts designed to provoke it, as in RealToxicityPrompts (Gehman et al., 2020).
- Bias benchmarks such as BBQ (Parrish et al., 2022).
- Counterfactual tests: swap names or demographic terms and check whether the output changes.
- PII leakage. Probes that try to extract training data or other users' data. Run canary strings planted in fine-tuning data to test memorisation.
- Runtime guard metrics. If a safety classifier screens inputs and outputs (for example, Meta's Llama Guard, Inan et al., 2023), track its flag rate, its precision on human-reviewed samples, and the latency it adds.
Gates. Safety metrics are usually hard gates: "harmful-compliance on the critical set must be 0 of 300" or "must not rise". Over-refusal is usually a guardrail with a ceiling. Re-run both after every fine-tune, because, as noted earlier, fine-tuning can erode safety behaviour.
Serving fine-tuned adapters#
Once you have LoRA adapters, you must decide how to serve them. There are three main patterns:
| Pattern | How it works | Fits when | Watch out |
|---|---|---|---|
| Merged model | Add B·A into the base weights and deploy as an ordinary model | One or a few fine-tunes with steady high traffic | Each variant is a full model copy in GPU memory; switching means redeploying |
| Dynamic single adapter | Base model loaded once; one adapter active per replica, swapped on demand | A few adapters, traffic partitioned by replica | Swapping takes time; cold adapters cause latency spikes |
| Multi-LoRA batching | Base model loaded once; many adapters resident; one batch mixes requests for different adapters | Many tenants or tasks (per-customer fine-tunes, dozens of skills) | Needs specialised kernels and adapter memory management |
Why multi-LoRA serving works. All requests share the expensive part, the base model's weights. Only the small per-adapter B·A products differ.
- S-LoRA ("S-LoRA: Serving Thousands of Concurrent LoRA Adapters", Sheng et al., 2023) keeps adapters in CPU memory and pages them into GPU memory on demand, using a unified memory pool shared with the KV cache. Custom kernels compute the different adapters' products within a single batch. It reported serving thousands of adapters on one GPU with several-fold higher throughput than naive approaches.
- Punica (Chen et al., 2023) introduced a batched kernel (SGMV) for the same mixed-adapter batching.
- Production engines. vLLM supports multiple LoRA adapters per server, and Predibase's open-source LoRAX is built around this pattern. Hosted platforms offer per-customer fine-tunes on shared base models in the same spirit.
Capacity arithmetic.
- Base model. A 7B model in bf16 takes about 14 GB.
- Adapter size. A rank-16 adapter on all linear layers of a 7B Llama-style model has about 40 million parameters, around 80 MB in fp16.
- Per-GPU budget. On an 80 GB GPU, after the base model and a generous KV cache (say 40 GB), about 20 GB remains for adapters, so roughly 250 hot adapters. Thousands more sit in CPU RAM and object storage.
- Cold loads. Fetching a cold adapter from local NVMe or CPU RAM takes tens to hundreds of milliseconds, so pre-warm adapters for active tenants and route a tenant's traffic to replicas where its adapter is already loaded (adapter-aware routing, like cache affinity).
- Compute overhead. Mixed-adapter batching adds a modest per-token cost compared with a merged model. It's usually far cheaper than running a separate deployment per fine-tune, which would mostly sit idle.
Operational rules for adapters:
- Treat adapters as versioned artefacts in a registry. Record the base-model version, the training data version, eval scores and the owner, exactly like a model registry (ML System Design and Feature Stores).
- An adapter is tied to its exact base model. Upgrading the base means retraining every adapter and re-running their evals. Budget for this, because it's the hidden recurring cost of fine-tuning. A base-model upgrade across 300 tenant adapters becomes a batch pipeline, not a manual task.
- Roll out adapters like code: shadow, then canary, then full, with automatic rollback on guardrail breaches (CI/CD and Deployment Strategies).
- Isolate tenants. A request must never be served with another tenant's adapter. Map adapter IDs from the authenticated tenant on the server, never from a client-supplied field.
When to Use It#
Fine-tune when:
- Prompting has plateaued on a measured eval. You've iterated on instructions and few-shot examples, the golden-set score has stopped improving, and the remaining failures are about behaviour (format drift, tone, label boundaries) rather than missing knowledge.
- The prompt has become huge. A 6,000-token system prompt with 30 examples costs you on every request. Fine-tuning can move that behaviour into weights.
- Example. At 20 million requests a month, 5,000 fewer input tokens per request saves 100 billion input tokens a month. At a few dollars per million input tokens, that's hundreds of thousands of dollars a year.
- Latency improves too, because time to first token grows with prompt length.
- You want a smaller, cheaper or faster model for a narrow task. Distilling a frontier model's behaviour into a 7B–8B model for classification, extraction or routing can cut cost and latency by an order of magnitude, if evals confirm quality holds.
- You need on-premises or on-device deployment. Data can't leave your network, or the feature must run on a phone (Client, Mobile and Frontend Considerations), so you need a small open model specialised for the job.
- The output must follow a strict, unusual format or a domain language the base model handles poorly: an internal query language, a legacy code dialect, a house style.
- You have, or can create, at least several hundred high-quality examples and an eval set to prove the gain.
Invest in evaluation always. Every LLM feature needs a golden set and a regression suite, whether or not you fine-tune. Evaluation infrastructure is what lets you change prompts, switch providers and upgrade models without fear.
When NOT to Use It#
Pick something else instead when:
- The problem is missing or changing knowledge. Product catalogues, policies and docs change weekly. Use RAG, which updates instantly, can cite sources, and respects per-user permissions (Designing LLM and AI-Powered Systems).
- You haven't tried a good prompt and an eval yet. Most teams that "need fine-tuning" haven't measured their prompt baseline. Start with the strongest prompt you can write, few-shot examples, and structured output modes.
- You have under about 100 quality examples, or no eval set. You can't tell whether the fine-tune helped.
- Requirements change fast. Each change means new data, retraining and re-evaluation (hours to days), compared with minutes for a prompt edit.
- You'd be tied to a base model that will soon be superseded. Frontier base models improve every few months, and adapters don't transfer between bases. A prompt often improves for free when you upgrade the model, while a fine-tune must be redone.
- The task needs multi-step reasoning or broad knowledge that a small fine-tuned model simply lacks. A bigger model with good prompting beats a small fine-tuned one there.
- You need preference tuning from scratch with human labels and lack the labelling budget. Try AI-feedback preference data with human audits, or settle for SFT.
How to Implement It#
- Define success and build the eval first.
- Write the task spec.
- Collect 300–1,000 real, stratified examples with expected outcomes.
- Choose graders (exact match, execution, judge with rubric) and calibrate the judge against 100–200 human labels.
- Record the prompt-only baseline on the strongest model you'd consider, and on the small model you'd like to fine-tune.
- Exhaust the cheap levers. Better instructions, few-shot examples, structured outputs, retrieval for knowledge. Re-measure, and only continue if a measured gap remains.
- Prepare data.
- Gather examples from logs, experts or a teacher model.
- Dedup, filter, scrub PII, balance slices.
- Format with the exact chat template.
- Split by user, document or time, and keep the golden set untouched.
- Train with LoRA or QLoRA.
- Start from sensible defaults: rank 16, all linear layers, learning rate 1e-4 to 2e-4, 1–3 epochs.
- Track validation loss and, more importantly, task-eval scores per checkpoint.
- Run a learning-curve check before buying more data.
- Add preference tuning (DPO or KTO) only if SFT leaves a gap that comparisons capture better than demonstrations.
- Evaluate broadly. Target-task golden set, general-capability probes (forgetting), safety and over-refusal suites, latency and cost. Compare against the baseline with paired statistics, not eyeballed averages.
- Ship and keep evaluating.
- Register the adapter with lineage.
- Deploy shadow, then canary, then A/B.
- Monitor sampled judge scores and user feedback.
- Feed production failures back into both the regression suite and the next training set.
Snippet: a regression-gate runner. It runs every golden case against a candidate and the current baseline, then gates on overall, per-slice and safety results.
type Case = { id: string; slice: string; critical: boolean; input: string; expected: string };
type Grade = (c: Case, output: string) => Promise<boolean>;
async function runGate(cases: Case[], candidate: (s: string) => Promise<string>,
baseline: Map<string, boolean>, grade: Grade) {
const results = new Map<string, boolean>();
for (const c of cases) {
const out = await candidate(c.input); // temperature 0, pinned versions
results.set(c.id, await grade(c, out));
}
const rate = (ids: Case[], m: Map<string, boolean>) =>
ids.filter(c => m.get(c.id)).length / Math.max(ids.length, 1);
const failures: string[] = [];
const overallDrop = rate(cases, baseline) - rate(cases, results);
if (overallDrop > 0.01) failures.push(`overall dropped ${(overallDrop * 100).toFixed(1)} pts`);
const slices = [...new Set(cases.map(c => c.slice))];
for (const s of slices) {
const inSlice = cases.filter(c => c.slice === s);
const drop = rate(inSlice, baseline) - rate(inSlice, results);
if (inSlice.length >= 30 && drop > 0.03) failures.push(`slice ${s} dropped ${(drop * 100).toFixed(1)} pts`);
}
const criticalFails = cases.filter(c => c.critical && !results.get(c.id));
if (criticalFails.length > 0) failures.push(`critical failures: ${criticalFails.map(c => c.id).join(",")}`);
const flipped = cases.filter(c => baseline.get(c.id) && !results.get(c.id)).map(c => c.id);
return { pass: failures.length === 0, failures, flipped }; // flipped list goes in the diff report
}The runner ignores slices with fewer than 30 cases, because their pass rates are too noisy to gate on. In a real pipeline you'd run cases concurrently with a rate limit, cache baseline results by pinned version, and attach the flipped outputs to the pull request for human review.
| Technology | Fits when |
|---|---|
| Hugging Face Transformers, PEFT, TRL | Open-model fine-tuning in Python; PEFT for LoRA and QLoRA, TRL for SFT, DPO, KTO and PPO trainers |
| Axolotl, Unsloth, LLaMA-Factory | Config-driven fine-tuning recipes; Unsloth focuses on fast, memory-lean LoRA on single GPUs |
| DeepSpeed ZeRO, PyTorch FSDP | Full fine-tuning or large models that must be sharded across GPUs |
| Hosted fine-tuning APIs (OpenAI, Google Vertex AI, AWS Bedrock, Together, Fireworks) | You want managed training and serving without running GPUs; accept the provider's model choices and terms |
| vLLM, LoRAX, TensorRT-LLM, SGLang | Serving open models; multi-LoRA serving for many adapters on one base |
| OpenAI Evals, promptfoo, DeepEval, Ragas, lm-evaluation-harness, HELM | Eval frameworks: product regression suites (promptfoo, DeepEval), RAG metrics (Ragas), public benchmarks (lm-evaluation-harness, HELM) |
| LangSmith, Langfuse, Arize Phoenix, Braintrust | Tracing production LLM calls, building datasets from traces, online and offline eval dashboards |
| Label Studio, Argilla, Scale AI-style vendors | Human labelling and preference collection with guidelines and agreement tracking |
| MLflow, Weights and Biases | Experiment tracking, model and adapter registry, lineage |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Prompting only | Instant iteration; no training cost; improves when the base model upgrades | Long prompts cost tokens and latency; behaviour drifts on edge cases; limited control | Always first; most features stop here |
| RAG | Fresh, citable, permission-aware knowledge; no retraining for new facts | Retrieval quality caps answer quality; more moving parts; adds latency | The problem is knowledge that changes or is private |
| SFT with LoRA | Cheap to train; small artefacts; strong control of format and style; enables small models | Needs quality data and evals; tied to one base model; risk of forgetting | Measured behaviour gap after prompting; cost or latency pressure |
| Full fine-tuning | Highest capacity for large shifts in behaviour | Expensive to train; a full model copy per variant; higher forgetting risk | Large datasets, big quality gap, dedicated high-traffic model |
| RLHF with PPO | Optimises against a learned notion of quality; proven at frontier labs | Complex, unstable, needs a reward model and an RL setup; reward hacking | Model-builder scale with large preference datasets |
| DPO or KTO | Simple, stable preference tuning; no reward model | Offline only (learns from fixed pairs); can over-optimise and drift in length | Product teams with preference or thumbs data |
| LLM-as-judge evals | Scalable; cheap per case; handles open-ended outputs | Biased (position, length, self); must be calibrated and pinned | Grading free text at volume, with human calibration |
| Human evals | Ground truth for subjective and expert quality | Slow, expensive, needs guidelines and agreement tracking | Calibration, launches, safety-critical and expert domains |
| Merged adapter serving | No runtime overhead; simplest serving | One deployment per variant; idle capacity | A few high-traffic fine-tunes |
| Multi-LoRA serving | Hundreds of fine-tunes on shared GPUs | Kernel and cache complexity; cold-load latency; noisy-neighbour risk | Many tenants or tasks with uneven traffic |
Common Pitfalls#
- Fine-tuning to add knowledge. The model learns the style of your facts but still invents details, and the facts go stale. Use RAG for knowledge and fine-tuning for behaviour.
- No baseline. Without a prompt-only baseline on the same eval, you can't tell whether a fine-tune helped or just cost money.
- Evaluating on training data. Random row splits leak near-duplicates. Contaminated golden sets inflate scores. Split by user, document or time, and freeze the golden set.
- Chat-template mismatch. Training with one prompt format and serving with another (missing system prompt, different role tokens) silently degrades quality.
- Only measuring the target task. Catastrophic forgetting and safety erosion show up elsewhere. Include general-capability and safety probes in every eval run.
- Over-training small datasets. Five epochs on 800 examples memorises them. Watch validation loss and task evals per checkpoint, and stop early.
- Trusting an uncalibrated judge. A judge that prefers long answers will "prove" your verbose fine-tune is better. Calibrate against humans, swap pair order, and control for length.
- Gating on averages. An overall +1 point can hide a 10-point collapse in one language. Gate per slice and on critical cases.
- Reading noise as signal. On 300 cases, a 2-point change is often within the confidence interval. Use paired tests (which cases flipped) before deciding.
- Forgetting the base-model upgrade tax. Every adapter must be retrained and re-evaluated when the base changes. Automate it, or keep the number of fine-tunes small.
- Shipping without online monitoring. Offline evals don't see new user behaviour. Sample production traffic for judge scoring, and feed failures back into the suite.
- Training on user data without consent or scrubbing. Memorised PII can be extracted later. Deleting it means retraining, so get consent and redact before training.
Real-World Examples#
- InstructGPT and ChatGPT (OpenAI). InstructGPT (Ouyang et al., 2022) described the SFT, reward-model and PPO pipeline. Labellers preferred its 1.3B model over the 175B GPT-3, which showed that alignment tuning matters as much as scale.
- Llama 2-Chat (Meta). The Llama 2 paper (Touvron et al., 2023) used SFT followed by RLHF with two separate reward models, one for helpfulness and one for safety, plus rejection sampling and PPO. That's a concrete example of balancing the two competing objectives this page measures. The later Llama 3 report (2024) moved to rounds of SFT, rejection sampling and DPO.
- Zephyr (Hugging Face). Zephyr-7B (Tunstall et al., 2023) was distilled from a larger model's outputs, then preference-tuned with DPO on AI-ranked comparisons (UltraFeedback). It showed that a small open model can become a strong chat model without human preference labels.
- Constitutional AI (Anthropic). Bai et al. (2022) used written principles and AI feedback (RLAIF) to train harmlessness with far fewer human labels.
- Chatbot Arena (LMSYS). Crowd-sourced, blind, pairwise human votes on anonymous models, ranked with a Bradley–Terry or Elo-style model. It's become one of the most cited public signals of chat quality because it's hard to overfit and reflects real user prompts.
- Apple's on-device foundation model (2024). Apple described a roughly 3-billion-parameter on-device model specialised with task-specific LoRA adapters (summarisation, proofreading and others) that are loaded and swapped at runtime on top of one shared base. It's the adapter-serving pattern applied on a phone.
- DeepSeek-R1 (2025). DeepSeek showed that large-scale RL with verifiable rewards (GRPO) can elicit long chain-of-thought reasoning, then distilled that behaviour into smaller models via SFT on the larger model's outputs.
Case studies that use this pattern#
- Design an LLM Chat Service (ChatGPT): model versions, safety classifiers, feedback collection and A/B rollout of new models.
- Design an A/B Testing and Experimentation Platform: the online-eval machinery (randomisation, guardrails, statistics) used to launch model and prompt changes.
- Design an Online Code Judge (LeetCode): sandboxed code execution, the same isolation you need to grade generated code with unit tests (pass@k).
- Design a Metrics Monitoring and Alerting System: the time-series and alerting backbone for online quality, latency and cost metrics.
- Design a Recommendation System (Twitter For You): offline metrics versus online A/B outcomes, the same gap LLM evals must bridge.
In the Interview#
Common follow-ups:
Q: Would you fine-tune the model on our documentation so it knows our product? No, at least not as the main tool. Documentation changes, needs citations and may have per-customer permissions, which RAG handles. Fine-tuning teaches behaviour, and when used for facts it tends to make the model confidently invent details. I might fine-tune for the answer style (format, tone, citation habit) on top of RAG.
Q: How do you know your fine-tune is better? Paired comparison on a frozen golden set against the prompt-only baseline, with per-slice results and confidence intervals. Then general-capability and safety suites to catch forgetting, then an online A/B test on the task outcome (resolution rate, acceptance rate) with latency, cost and safety guardrails.
Q: RLHF or DPO? For a product team, DPO or KTO. They're simpler, stable, and need no reward model or RL loop, and KTO can use thumbs-up and thumbs-down logs directly. RLHF with PPO makes sense at model-builder scale, or when a learned reward model is reused for ranking and monitoring. If outputs are automatically verifiable, RL against the verifier, or rejection sampling plus SFT, is even better.
Q: How do you evaluate open-ended answers at scale? LLM-as-judge with a specific rubric, pairwise or binary judgements, both pair orders, a judge from a different model family, and pinned versions. Calibrate it against a few hundred human labels using Cohen's kappa, and re-calibrate when anything changes. Use execution or exact match wherever the output is checkable.
Q: How do you measure hallucination? For RAG: split answers into claims and check each against the retrieved context (groundedness), plus citation precision. Track answer-level rates and separate retrieval misses from generation errors. Without context, use consistency checks across samples (SelfCheckGPT-style) or verify against a reference source. Also measure abstention: does the model say "I don't know" on unanswerable questions?
Q: We have 500 enterprise customers who each want a custom model. How do you serve that? One shared base model with one LoRA adapter per customer, served with multi-LoRA batching (vLLM, LoRAX or S-LoRA style). Hot adapters stay in GPU memory, warm ones in CPU RAM, cold ones in object storage. Routing is adapter-aware, the adapter is chosen from the authenticated tenant, and each adapter has its own eval gate. Budget for retraining all 500 adapters when the base model upgrades.
Q: What's the risk of fine-tuning on customer conversations? Memorisation and leakage of PII or another customer's data, consent and contractual limits, and deletion requests that require retraining. Scrub PII, train per tenant (adapters) rather than mixing tenants in one model, and probe for memorisation with canary strings.
Deep Dive: LoRA and QLoRA memory and compute arithmeticShow
Why low rank works at all. "Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning" (Aghajanyan et al., 2020) showed that fine-tuning large pre-trained models can reach most of their full fine-tuning quality while optimising in a surprisingly small random subspace of the parameters. The larger the pre-trained model, the smaller that subspace. LoRA builds on the same idea in a structured form: it assumes the weight update ΔW has low rank, so it factorises it as B·A. A pre-trained model already contains the features, and fine-tuning mostly re-weights and recombines them, which needs few degrees of freedom.
Training memory, three ways, for a 7B model.
| Component | Full fine-tune (bf16 + Adam) | LoRA (bf16 base) | QLoRA (NF4 base) |
|---|---|---|---|
| Base weights | 14 GB (2 B/param) | 14 GB frozen | about 3.5 GB plus about 0.1 GB of quantisation constants |
| Trainable params | 7B | about 40M (rank 16, all linear layers) | about 40M |
| Gradients | 14 GB | about 0.08 GB | about 0.08 GB |
| fp32 master and Adam moments | 84 GB (12 B/param) | about 0.5 GB | about 0.5 GB |
| Activations (batch and sequence dependent) | several to tens of GB; cut with gradient checkpointing | same | same |
| Typical hardware | multiple 80 GB GPUs with ZeRO or FSDP | one 24–48 GB GPU | one 16–24 GB GPU |
The same arithmetic at 70B: full fine-tuning needs over 1 TB for weights, gradients and optimiser state, so a multi-node job. QLoRA needs about 35 GB of NF4 weights plus about a gigabyte of constants, a few GB of adapter and optimiser state, and activations, so it fits on one 80 GB GPU (and, per the QLoRA paper, a 65B model fits in 48 GB).
Training compute. For a forward and backward pass, a dense transformer costs about 6 × N FLOPs per training token for full training (N = parameter count). That's 2N for the forward pass, about 2N for gradients with respect to activations, and about 2N for gradients with respect to weights. LoRA skips almost all weight gradients, so it costs about 4 × N per token.
Worked example: 10,000 examples × 1,000 tokens × 3 epochs = 30 million training tokens on a 7B model with LoRA.
FLOPs = 4 × 7e9 × 3e7 = 8.4e17
A100 bf16 peak ~312 TFLOP/s, at ~40% utilisation ~125 TFLOP/s
time = 8.4e17 / 1.25e14 ≈ 6,700 s ≈ under 2 hours on one GPUAt a few dollars per GPU-hour, that's a single-digit-dollar training run. The real costs of fine-tuning are data curation, evaluation and the retraining you'll do at every base-model upgrade, not GPU time. QLoRA's on-the-fly dequantisation typically makes the same run somewhat slower than 16-bit LoRA.
Rank, alpha and capacity.
- The scaling factor (α / r) keeps the update's magnitude roughly stable as you change r, so you can change rank without re-tuning the learning rate much. rsLoRA's α / √r scaling is designed to stay stable at higher ranks.
- More capacity isn't free. Doubling r doubles adapter parameters and memory. It helps only if the task needs more capacity. On small datasets, a higher rank mainly overfits faster.
- Spread the budget across layers. For a fixed parameter budget, applying low rank to more matrices (all linear layers) usually beats high rank on just query and value.
Quantisation details in QLoRA.
- NF4 levels. The 16 levels are set at quantiles of a standard normal distribution, so each level is used about equally often by normally distributed weights. That's information-theoretically better than evenly spaced levels.
- Blocks and constants. Weights are quantised in blocks (for example, 64 values), each with its own scale constant. Those constants are themselves quantised to 8 bits in blocks of 256 (double quantisation), cutting the constants' overhead from about 0.5 to about 0.127 bits per parameter.
- Compute precision. Computation happens in bf16. Each weight block is dequantised just before its matrix multiply, so gradients flow through the frozen quantised weights into the bf16 LoRA matrices.
Serving memory per adapter, for capacity planning. For a Llama-style 7B model (hidden size 4096, MLP size 11008, 32 layers) at rank 16:
attention q,k,v,o : 4 matrices × 2 × 4096 × 16 = 524,288 per layer
MLP gate,up,down : 3 matrices × (4096 + 11008) × 16 = 724,992 per layer
total : 1,249,280 × 32 layers ≈ 40 million params
size in fp16 : 40M × 2 bytes ≈ 80 MB per adapterSo a GPU with 20 GB to spare holds about 250 hot adapters, matching the serving estimate above. (Models that use grouped-query attention have smaller key and value projections, so their adapters are a little smaller.)
Deep Dive: The mathematics of preference optimisation (Bradley–Terry, RLHF, DPO, GRPO)Show
The Bradley–Terry model. Human preferences are modelled as noisy comparisons of a hidden reward r(x, y), where x is the prompt and y a response. The probability that the chosen response y_w beats the rejected y_l is the logistic sigmoid σ of the reward difference:
P(y_w preferred over y_l | x) = σ( r(x, y_w) − r(x, y_l) ) σ(z) = 1 / (1 + e^−z)
reward-model loss = − log σ( r(x, y_w) − r(x, y_l) ) averaged over pairsOnly reward differences matter, so the reward's absolute scale is arbitrary. In practice the reward model is the SFT model with its final layer replaced by a scalar head. The same model is used for Elo-style leaderboards like Chatbot Arena, with models in place of responses.
The RLHF objective. Maximise expected reward while staying close to the reference (SFT) policy π_ref:
maximise over π : E_x E_(y~π) [ r(x, y) ] − β · KL( π(·|x) ‖ π_ref(·|x) )The KL penalty is what keeps the policy honest. Without it, the policy finds degenerate outputs that the reward model over-scores. That's reward hacking, an instance of Goodhart's law: once the reward model's score becomes the target, it stops being a good measure of quality. β trades reward against drift. In PPO implementations the KL term is usually applied per token as part of the reward, and PPO's clipped objective limits how far each update moves the policy. The setup needs a value model to estimate advantages, which is why classic RLHF juggles four networks: policy, reference, reward and value.
From RLHF to DPO in four lines. The KL-regularised objective has a known optimal policy:
π*(y|x) = π_ref(y|x) · exp( r(x, y) / β ) / Z(x) Z(x) normalises over all y
⇒ r(x,y) = β · log( π*(y|x) / π_ref(y|x) ) + β · log Z(x)
plug into Bradley–Terry; the β·log Z(x) terms cancel in the difference:
L_DPO = − log σ( β · [ log π(y_w|x)/π_ref(y_w|x) − log π(y_l|x)/π_ref(y_l|x) ] )- What the loss means. The quantity
β · log π/π_refacts as an implicit reward. Training raises the chosen response's log-probability relative to the reference, and lowers the rejected one's. - The gradient is weighted by how wrong the model currently is. Pairs the policy already ranks correctly, by a wide margin, contribute little. Mis-ranked pairs contribute most.
- β plays the same role as in RLHF. Small β allows more drift from the reference, and large β keeps the policy close. Typical values are around 0.1.
Known DPO failure modes and the variants that address them:
- Over-optimisation on deterministic preferences. When the same pair is always preferred, the loss pushes the log-ratio gap toward infinity. IPO replaces the log-sigmoid with a squared loss toward a fixed margin.
- Both likelihoods falling. DPO can lower the probability of the chosen response too, as long as the rejected one falls faster, which hurts generation quality. Mixing in an SFT loss on chosen responses (as in ORPO-style objectives) counters it.
- Length exploitation. Longer responses accumulate larger log-probability ratios. SimPO normalises by length and drops the reference model.
- Unpaired data. KTO ("Kahneman–Tversky Optimization", Ethayarajh et al., 2024) works from single responses labelled desirable or undesirable, matching thumbs-up and thumbs-down product logs.
- Off-policy data. DPO learns from a fixed dataset, often generated by a different model. Iterative or online DPO regenerates pairs from the current policy each round and labels them with a judge or reward model, recovering some of RL's on-policy advantage.
GRPO and verifiable rewards. For each prompt, sample a group of G responses, score each with a verifier (correct answer, tests pass) or a reward model, and use the group-normalised score as the advantage:
A_i = ( r_i − mean(r_1..r_G) ) / std(r_1..r_G)Responses better than their siblings are reinforced, and worse ones are discouraged. No value network is needed, which saves memory and removes a source of instability. A KL term to the reference model is still used. Because the verifier is exact, reward hacking is limited to exploiting weaknesses in the verifier itself, for example tests that are too weak. That's why verifier quality is the critical engineering asset in this regime.
Deep Dive: Statistics for LLM evals (sample sizes, paired tests, win rates and judge calibration)Show
Confidence intervals on a pass rate. With n cases and observed pass rate p, the standard error is √(p(1 − p)/n), and a 95% interval is about ±1.96 standard errors.
| n | p = 0.90 | 95% interval |
|---|---|---|
| 200 | SE ≈ 2.1 pts | ±4.2 pts |
| 500 | SE ≈ 1.3 pts | ±2.6 pts |
| 2,000 | SE ≈ 0.67 pts | ±1.3 pts |
For small slices or rates near 0 or 1, use a Wilson interval or a bootstrap instead of the normal approximation. "0 failures in 300 safety cases" doesn't mean a 0% failure rate. The "rule of three" gives a 95% upper bound of about 3/300 = 1%.
How many cases to detect a change, unpaired? To detect a drop δ from pass rate p with 5% false-alarm rate and 80% power:
n per arm ≈ (1.96 + 0.84)² × 2 × p(1 − p) / δ²
p = 0.85, δ = 0.03 → 7.84 × 2 × 0.1275 / 0.0009 ≈ 2,200 cases per armThat's more cases than most teams have, which is why paired designs matter.
Paired comparison (McNemar's test). Run baseline and candidate on the same cases. Only cases that flip carry information. With b = cases that went fail → pass and c = cases that went pass → fail, compute (b − c)² / (b + c) and compare it with 3.84 (chi-square with 1 degree of freedom, 5% level).
Example: 1,000 cases, 40 fixed and 20 broken. Then (40 − 20)² / 60 = 6.67, which is above 3.84, so the improvement is significant, even though the overall rate moved by only 2 points. Pairing removes the large variance from case difficulty. Always read the 20 broken cases anyway: they might all be in one critical slice.
Stochastic outputs. If the system samples at temperature above 0, a single run per case adds noise. Run k samples per case and use the per-case pass fraction. For code, the unbiased pass@k estimator from the HumanEval paper (Chen et al., 2021) generates n ≥ k samples, counts c correct, and computes 1 − C(n−c, k) / C(n, k). That's the probability that at least one of k randomly drawn samples passes.
Multiple comparisons. Gating on 20 slices at a 5% significance level produces about one false alarm per run even when nothing changed. You can:
- apply Holm or Bonferroni corrections;
- require a minimum effect size as well as significance;
- treat slice drops as "needs review" rather than "block", except on critical slices.
Pairwise win rates and Elo. A pairwise judge (human or LLM) produces wins, losses and ties. Report the win rate with ties counted as half, together with a bootstrap interval. Across many models, fit a Bradley–Terry model, or Elo, its online approximation:
expected score of A vs B : E_A = 1 / (1 + 10^((R_B − R_A) / 400))
100-point gap → E_A = 1 / (1 + 10^−0.25) ≈ 0.64 (A wins about 64% of comparisons)Chatbot Arena-style leaderboards publish these ratings with confidence intervals. When intervals overlap, the ranking is not settled.
Judge calibration with Cohen's kappa. Raw agreement is misleading when labels are imbalanced, so correct for chance:
κ = (p_observed − p_chance) / (1 − p_chance)
judge and humans agree on 85% of 200 items; chance agreement from label rates = 50%
κ = (0.85 − 0.50) / 0.50 = 0.70 (commonly read as substantial agreement)Judge calibration in practice:
- Compare the judge with humans and humans with each other. Track judge-to-human κ alongside human-to-human κ. If humans agree only at κ = 0.6, no judge will look better than that, and the rubric probably needs tightening.
- Use a position-swap check. Judge each pair in both orders. The fraction of inconsistent verdicts measures position bias. Count inconsistent pairs as ties.
- Control for length. Check judge scores against length. If the score rises steadily with length, add rubric language about concision, or compare responses within length buckets.
- Run drift checks. Keep a fixed set of judged examples and re-run it whenever the judge model, prompt or temperature changes. If its scores move, re-baseline before comparing new results.
Key Takeaways#
- Use prompting for instructions, RAG for knowledge, and fine-tuning for behaviour. Fine-tune only after a measured prompt-plus-RAG baseline leaves a gap, or when cost and latency demand a smaller model.
- Assistant models are built in stages. SFT teaches format and style. Preference tuning (RLHF with PPO, or more simply DPO or KTO) teaches which of two answers is better. RL with verifiers improves tasks you can check automatically.
- LoRA and QLoRA make fine-tuning cheap. You train under 1% of the parameters, store adapters of tens of megabytes, and fit 7B on one GPU and 70B with QLoRA on one 80 GB GPU. The real costs are data, evals, and retraining at every base-model upgrade.
- Data quality decides outcomes. Curate, dedup, scrub PII, match the serving chat template, split by user or time, and never train on the golden set.
- Evaluate in layers:
- benchmarks to pick a base model;
- task evals on your own data to gate changes;
- calibrated LLM-as-judge for open-ended text;
- humans for ground truth;
- A/B tests for real impact.
- A regression suite turns LLM changes into engineering. It needs bug-derived cases, per-slice and critical-case gates, diff reports, pinned versions and paired statistics.
- Measure hallucination as groundedness and safety in both directions. That means harmful compliance and jailbreak success, but also over-refusal. Re-run safety after every fine-tune.
- Serve many fine-tunes as LoRA adapters on a shared base with multi-LoRA batching, adapter-aware routing and tiered adapter caching. Version adapters like models, and roll them out like code.