Guide / AI engineering Fundamentals
Model adaptation: prompting, RAG, fine-tuning, LoRA, RLHF and distillation
A decision tree for adapting an LLM to your task, how supervised fine-tuning, LoRA/QLoRA, preference tuning (RLHF, DPO) and distillation work, data requirements, and how to evaluate the result.
Fundamentals#
A.1 Decision tree: what to try first#
Not good enough with a basic prompt?
├─ Missing knowledge (private/changing facts)? → RAG (retrieval) ──────────── RAG page
├─ Wrong format/instructions followed? → better prompt, examples, structured output
├─ Needs consistent style/behaviour at scale,
│ or latency/cost too high with big model? → fine-tune (SFT/LoRA) or distil into a small model
├─ Prefers certain outputs (tone, safety, rank)?→ preference tuning (DPO/RLHF)
└─ Reasoning too weak? → stronger model, tools, step-by-step, test-time compute
Rule: prompting → RAG → fine-tuning, in increasing cost and decreasing flexibility. RAG for facts, fine-tuning for behaviour. Fine-tuning does not reliably add new knowledge and bakes in stale facts; it is best for format, tone, domain jargon, tool-calling reliability, classification and shrinking a prompt.
A.2 Supervised fine-tuning (SFT)#
Train on (input, ideal output) pairs so the model imitates them. Data: hundreds to a few thousand high-quality examples often beat tens of thousands of noisy ones. Sources: curated human examples, logged production outputs that were approved, synthetic data from a stronger model (check licensing and quality, deduplicate, filter). Hold out an eval set before training; watch for contamination and catastrophic forgetting (general ability drops; mix in general data, use lower learning rates and LoRA).
A.3 LoRA and QLoRA#
Full fine-tuning updates all weights (costly: weights + gradients + optimizer states ≈ 12–16 bytes per parameter). LoRA freezes the base model and trains small low-rank matrices added to selected layers: W' = W + B·A where A and B have rank r (4–64), so only ~0.1–1% of parameters train. Benefits: far less memory, small adapter files (MBs) that can be swapped per customer or task on one base model (multi-LoRA serving), easy rollback. QLoRA does LoRA on a 4-bit quantised base so a 7–70B model fine-tunes on one or a few GPUs. Trade-off: slightly lower ceiling than full fine-tuning on hard tasks; hyperparameters to tune: rank, alpha, target modules, learning rate, epochs (1–3).
A.4 Preference tuning#
| Method | How | When |
|---|---|---|
| RLHF | Train a reward model on human preference pairs, then optimise the policy with RL (PPO) against it with a KL penalty | Frontier-lab scale alignment; complex and unstable |
| DPO (direct preference optimisation) | Optimise directly on (prompt, chosen, rejected) pairs without a separate reward model or RL loop | Practical default for teams: simpler and stable |
| RLAIF / constitutional methods | AI-generated preferences following written principles | Scale feedback cheaply |
| RL with verifiable rewards | Reward from automatic checks (unit tests, math answers) | Reasoning and code improvement |
Use for tone, helpfulness trade-offs, safety refusals, ranking quality. Needs quality preference data; risk of reward hacking (optimising the proxy: verbosity, sycophancy).
A.5 Distillation#
Train a small student on outputs (answers, rationales, logits) of a large teacher. Typical use: a task-specific small model that matches the big model on your narrow task at 10–50× lower cost and latency. Steps: define the task and eval, generate teacher outputs on a diverse input set (include hard and edge cases), filter with verifiers or a judge, fine-tune the student, compare on the held-out eval, and monitor drift. Check the teacher provider’s terms of use.
A.6 Data and evaluation discipline#
- Quality over quantity; consistent labelling guidelines; deduplicate; balance classes; include negative and refusal examples.
- Separate train/validation/test; evaluate on real production-like inputs, not only synthetic data.
- Compare against the baseline you actually have (a good prompt on the best model) on accuracy, format validity, latency and cost; only ship if it wins on the metric that matters (Evals).
- Regression suite to catch lost general abilities; red-team for safety changes.
- Version everything: dataset, base model, adapter, hyperparameters, eval results.
- Plan re-training: base model upgrades invalidate adapters; keep the pipeline automated.
A.7 Costs and operations#
Training cost scales with tokens × epochs × model size; a LoRA run on thousands of examples is usually hours on one GPU. Serving: merge or hot-swap adapters; hosted fine-tuning (provider APIs) removes infrastructure but locks you to the provider and its model lifecycle. Self-hosting needs a serving stack with multi-LoRA support (LLM serving).
Most asked questions#
1. RAG vs fine-tuning? RAG injects current, citable knowledge at query time; fine-tuning changes behaviour, style and format. Often combined.
2. What is LoRA? Training small low-rank adapter matrices on a frozen base model, cutting memory and enabling swappable adapters.
3. What is DPO and why use it instead of RLHF? It optimises directly on preference pairs with a simple loss, avoiding a reward model and RL instability.
4. When would you fine-tune? Stable task with enough labelled data where prompting is inconsistent, latency/cost needs a smaller model, or you need strict style/format.
5. How much data do you need? Often a few hundred to a few thousand high-quality examples for SFT/LoRA; more for broad behaviour changes.
6. What is distillation? Training a small model to imitate a larger one on a task.
Senior-level questions#
1. “The fine-tuned model scores better on the eval but worse in production.” Eval distribution mismatch or leakage, overfitting to synthetic style, lost general ability, prompt/format drift in production, or metric not capturing user value. Rebuild the eval from real traffic, run online A/B tests, add guardrail regressions.
2. “Fine-tuning made the model confidently wrong about facts.” SFT teaches style, and unfamiliar facts increase hallucination; keep facts in retrieval, include “I don’t know” examples, and train on answers grounded in provided context.
3. “Design a pipeline to continuously improve a support model.” Log interactions with feedback signals, human review queue, curate approved examples, periodic LoRA retrain, automated eval gate, canary rollout, rollback, and privacy controls (PII removal, consent).
4. “How do you serve 500 customer-specific adapters?” Multi-LoRA serving on a shared base (adapters loaded on demand, cached by popularity), routing by tenant, per-adapter eval and versioning, and quotas.
5. “When is full fine-tuning justified over LoRA?” Large domain shifts with lots of data, maximum quality needs, and budget for training and serving separate full models.
Quiz#
1. Which is better for adding last week's product facts: RAG or fine-tuning?
RAG: facts change and need citations; fine-tuning is slow to update and unreliable at adding facts.
2. What do A and B represent in LoRA?
Low-rank matrices whose product B·A is added to a frozen weight matrix, trained instead of the full matrix.
3. What is QLoRA?
LoRA fine-tuning on a 4-bit quantised base model to reduce memory.
4. DPO inputs?
Prompts with a preferred (chosen) and a dispreferred (rejected) response.
5. Name two risks of fine-tuning.
Catastrophic forgetting of general capabilities and overfitting or data contamination; also stale baked-in facts and lock-in to a base model version.