LLM Fine-Tuning in Practice
When to fine-tune vs RAG vs prompt. Full LoRA fine-tuning walkthrough on a real dataset using HuggingFace Transformers and PEFT.
Fine-tuning is not always the answer. Most production LLM applications are better served by prompt engineering or RAG. Fine-tune only when you have labelled data, a specific behaviour to change, and evidence that prompting cannot get you there.
This is the question every ML engineer at a startup faces when building an LLM-powered feature: should we fine-tune a model or can we get there with prompting and retrieval? Fine-tuning is expensive — data collection, training compute, evaluation, deployment — and it is irreversible. A fine-tuned model that learned the wrong behaviour is worse than a base model.
The answer depends on what you are trying to change. If the base model already knows how to do the task but needs domain-specific facts — use RAG. If it knows how to do the task but needs a specific output format or tone — use prompting. If it genuinely cannot do the task reliably even with perfect prompts and all context in window — then fine-tune. The bar for fine-tuning should be high.
Hiring an expert consultant vs training a new employee. A consultant (prompting) is fast, flexible, and immediately available — give them the context they need and they will do good work. A trained employee (fine-tuned model) internalises your company's way of doing things, does not need context each time, is faster at inference, but costs significant upfront investment. You hire a consultant first, hire full-time only when the work is consistent, high-volume, and the consultant approach is insufficient.
Stripe's payment dispute classifier: prompting GPT-4 worked at 80% accuracy. Fine-tuned LLaMA-3-8B reached 94% at 10× lower cost per query. The volume justified the training investment. Volume and consistency are the two conditions that make fine-tuning worth it.
Prompt vs RAG vs fine-tune — a decision framework with real examples
Data preparation — the format that makes or breaks fine-tuning
The quality of fine-tuning data matters far more than the choice of model or hyperparameters. 500 high-quality, diverse examples consistently outperform 5,000 mediocre examples. Every example must follow the exact same chat template the base model was trained with. Mismatched templates are the most common silent failure — the model trains without error but produces garbage at inference.
QLoRA fine-tuning — 4-bit quantisation + LoRA on a 7B model
QLoRA (Module 51) combines 4-bit quantisation of the frozen base model with LoRA adapters that train in fp16. This makes fine-tuning a 7B model possible on a single 16GB GPU — a Google Colab T4 or a local RTX 4090. The TRL library (from HuggingFace) wraps SFTTrainer — a Trainer specifically designed for supervised fine-tuning that handles chat template formatting, packing short sequences together, and gradient checkpointing automatically.
Evaluating fine-tuned LLMs — beyond perplexity
Training loss and perplexity tell you the model is learning but not whether it will perform well in production. For task-specific fine-tuning, evaluate on task metrics: exact match accuracy for classification, ROUGE for summarisation, code execution rate for code generation. Always hold out a test set that the model never sees during training. Always compare against the base model and a prompting baseline — if fine-tuning does not beat prompting by a meaningful margin, the fine-tuning is not worth the cost.
Deploying fine-tuned LLMs — serving, versioning, and monitoring
Every common LLM fine-tuning mistake — explained and fixed
How teams actually arrive at "yes, fine-tune it"
In practice, the decision in Section 2 is not made once in a meeting — it is arrived at through a cheap, sequenced experiment. A team ships a prompted feature first because it costs an afternoon, not a sprint. They watch two numbers: accuracy against a hand labelled sample, and dollar cost per thousand calls at current volume. If accuracy is the problem and it is a knowledge gap, they add RAG next — a one-to-two week investment. Only when volume is high enough that per-call API cost is a real budget line item, and the failure mode is clearly about consistency of behaviour rather than missing facts, does fine-tuning enter the conversation at all. Most LLM features at most companies never reach that third stage, and that is the intended outcome of a good decision process, not a failure to be ambitious.
When a team does cross that threshold, they rarely stand up their own GPU training infrastructure first. Hosted fine-tuning products — OpenAI's fine-tuning API, Together AI, Fireworks AI, and Amazon Bedrock's custom model import — let a small team upload a dataset and get back a hosted fine-tuned endpoint without owning a training cluster. Self-hosted, open-weight fine-tuning with QLoRA on a rented GPU only becomes worth the extra engineering once the volume is large enough that inference cost, not training cost, dominates the budget — self-hosting an open model can be an order of magnitude cheaper per call than a hosted proprietary model once volume is high enough to amortise the fixed setup cost.
| Path | Who owns it | Setup time | Best fit |
|---|---|---|---|
| Hosted fine-tuning API | One ML engineer, no infra team | Days | Validating the idea, moderate volume |
| Self-hosted QLoRA (open weights) | ML engineer + MLOps/platform | 2–4 weeks | High volume, cost-sensitive, data-sensitive |
| Full fine-tuning / foundation model | Dedicated research + infra org | Months | Building a genuine domain foundation model |
Slack message from the PM, three months after the prompted classifier shipped: "We're at 40,000 dispute classifications a day now and the GPT-4 bill is becoming a real line item. Support says accuracy is fine but slow at peak load. Can we bring the cost down without hurting quality?" That is the actual trigger for fine-tuning in most organisations — not a technical ceiling on what prompting can do, but a volume and cost inflection point. The response is rarely "train from scratch": it is "export three months of logged predictions and corrections as training data, fine-tune an open-weight model with QLoRA, and put it behind the same API contract so nothing else in the product has to change."
Five things people get wrong about LLM fine-tuning
Fine-tuning is genuinely reliable at teaching behaviour — output format, tone, exact label names, task-specific style — because those are patterns repeated consistently across the training examples. Teaching a model a large number of new declarative facts is a different problem: a fact seen a handful of times during fine-tuning gets blended statistically with everything else the model already believes, the model cannot cite where a fine-tuned fact came from, and there is no way to update or remove a single fact without retraining. This is exactly why RAG, not fine-tuning, is the standard answer whenever the need is specific, current, or citable knowledge — fine-tuning and knowledge injection solve different problems even though both sound like "the model learned something new."
LoRA is not a compromise forced by limited compute — it is built on the empirical observation that the weight update needed to adapt a large pretrained model to a new task is itself low-rank, meaning most of the update can be captured by a small number of trainable parameters without meaningfully sacrificing quality. In practice LoRA reaches quality close to full fine-tuning on the overwhelming majority of real tasks, while producing a small, portable adapter file that is far easier to version, combine with other adapters, and roll back. Reaching for full fine-tuning by default, treating LoRA as the fallback, gets the actual trade-off backwards for almost every production use case.
LoRA freezing the base weights reduces the risk of catastrophic forgetting, it does not eliminate it. A high LoRA rank, too many training epochs on a small dataset, or a learning rate that is too aggressive can still push the adapted model to lose general capabilities it had before fine-tuning, especially on tasks unrelated to the fine-tuning data. The overfitting error covered earlier in this module — training loss collapsing while validation loss rises — is a direct symptom of this same failure mode. Always evaluate a fine-tuned model on general capability benchmarks, not just the target task, to catch this regardless of which fine-tuning method was used.
Production LLM systems almost always combine all three rather than picking one and discarding the others. A fine-tuned model still needs a system prompt to set context for the specific deployment, still benefits from RAG for any information that changes after the fine-tuning snapshot was taken, and the fine-tuning itself is usually targeted narrowly at consistent behaviour — like producing an exact label format — rather than trying to internalise the entire knowledge base. Treating fine-tuning as a replacement for the other two techniques, instead of one more layer alongside them, is a common design mistake that leads to a model that is confidently wrong about anything that changed after training.
As this module's data preparation section covers, 500 high-quality, diverse examples routinely outperform 5,000 mediocre ones — the quality and diversity of examples matters far more than raw count. LoRA in particular, with its small number of trainable parameters, can show meaningful task-specific improvement from a few hundred carefully chosen examples, especially for a narrow task like consistent classification labels. Waiting to "collect enough data" by volume alone, without checking whether the existing smaller set is clean, diverse, and correctly labelled, routinely delays a fine-tuning effort that would already have worked.
LLM fine-tuning — 5 questions interviewers actually ask
Fine-tuning wins when the problem is about consistent behaviour rather than missing knowledge — enforcing an exact output format or label set that a downstream system depends on, matching a specific tone or style reliably across thousands of calls, or reducing per-call cost at high volume by moving from an expensive hosted model to a smaller self-hosted one. RAG wins when the problem is that the model does not have access to specific, current, or citable information — content that changes often, proprietary documents, or anything where the answer needs a traceable source. If the failure mode is "the model does not know X," that is a RAG problem; if it is "the model knows how to do this but will not do it the exact way we need every time," that is a fine-tuning problem.
There is no fixed universal number, but a reasonable starting point for LoRA on a narrow task is a few hundred to a couple thousand examples, and quality matters more than quantity at any scale. I would rather have 500 examples that are correctly labelled, diverse in phrasing, and cover the edge cases the model actually sees in production, than 5,000 examples generated quickly or scraped from a single source. In practice I would start by manually reading a random sample of the available data before committing to a training run — labelling inconsistencies found there are almost always more valuable to fix first than adding more raw volume.
I would build a held-out test set the model never saw during training, and compare against at least three baselines on the same set: the base model with no prompt engineering, the base model with an optimised prompt, and a stronger proprietary model with an optimised prompt. The metric has to match the task — exact match accuracy for classification, something like ROUGE for summarisation, execution success rate for code. If the fine-tuned model does not clearly beat the optimised-prompt baseline by a meaningful margin, that is a sign the investment was not worth it, and I would ship the simpler prompting or RAG approach instead rather than defend the fine-tune out of sunk cost.
Full fine-tuning updates every parameter in the model, requiring memory and compute proportional to the entire model size and carrying the highest risk of catastrophic forgetting. LoRA freezes the base weights and trains a small pair of low-rank matrices injected into specific layers, updating a tiny fraction of total parameters while reaching comparable quality on most tasks. I would only reach for full fine-tuning when the goal is building a genuine foundation model for a domain so specialised that the base model's existing knowledge is closer to random than useful — something like BloombergGPT trained on decades of financial documents — which is a fundamentally different scale of investment than adapting an existing capable model to a specific application.
Prevention starts with the training setup: use a lower LoRA rank and fewer target modules when the dataset is small, limit training to one or two epochs, add dropout, and always select the checkpoint by validation loss rather than training loss. Detection requires evaluating on more than just the fine-tuning task — I would run the fine-tuned model against a general capability benchmark or a handful of unrelated prompts it should still answer well, and compare that against the base model's performance on the same prompts before and after fine-tuning. A model that improved on the target task but visibly degraded on unrelated general prompts is showing catastrophic forgetting, even if the target-task metric alone looks like a clean win.
You can fine-tune any LLM. Next: models that see and understand both images and text simultaneously.
Fine-tuning adapts a model to a specific task using labelled examples. The next frontier is multimodal models — models that jointly understand images and text. CLIP encodes images and text in a shared embedding space. LLaVA connects a vision encoder to an LLM decoder, enabling visual question answering. Module 66 covers how these architectures work and how to use them for tasks that require understanding both what is written and what is shown.
Models that see and understand images and text together. CLIP for zero-shot image classification, LLaVA for visual question answering.
🎯 Key Takeaways
- ✓Fine-tune only when prompting and RAG cannot get you there. The decision hierarchy: prompt engineering first (1 day, flexible, no training cost) → RAG for knowledge gaps (1-2 weeks) → LoRA fine-tuning for consistent behaviour change on high-volume tasks (2-4 weeks) → full fine-tuning almost never for applications. The bar for fine-tuning must be justified by volume and a clear quality gap over prompting.
- ✓Data quality trumps data quantity. 500 high-quality, diverse, correctly-labelled examples beat 5,000 mediocre ones every time. Evaluate your data before training: read 50 random examples manually. If you find labelling inconsistencies, fix the data first. The most impactful ML work is data cleaning, not model architecture.
- ✓Chat template format must match the base model exactly. LLaMA-3, Mistral, Phi-3, and Gemma all use different special tokens. Apply the template with tokenizer.apply_chat_template() — never hardcode template strings manually. Template mismatches are the most common silent failure in LLM fine-tuning.
- ✓Use DataCollatorForCompletionOnlyLM to compute loss on assistant tokens only. Training on prompt tokens wastes compute and teaches the model the wrong thing — it should learn to generate responses, not re-generate inputs. Verify by printing token labels: prompt positions must be -100 (ignored).
- ✓QLoRA (4-bit quantisation + LoRA, rank 16, all projection layers) on a 7B model fits in 16GB VRAM with batch_size=4 and gradient_accumulation=4. Use paged_adamw_32bit optimiser, gradient_checkpointing=True, and packing=True in SFTTrainer. Training 3 epochs on 2,000 examples takes approximately 30-60 minutes on a T4.
- ✓Always compare fine-tuned model against: base model with no prompt, base model with optimised prompt, and a stronger model API (GPT-4) with optimised prompt. If GPT-4 with a good prompt beats your fine-tuned model, you have a data or training problem, not a capability gap. Ship the simpler approach until fine-tuning genuinely wins on your evaluation set.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.