Loading lesson...
Loading lesson...
All three branches leave the same root, so the tagged reason a case failed is what picks between them, and fine-tuning a gap that retrieval would close buys a training run and a rollback plan for a problem the adapter was never going to fix.
Fine-tuning fixes style, format, and specialised behaviour. Retrieval fixes facts. Hugging Face PEFT and the OpenAI fine-tuning guide name the gates that hold every branch safe.
In February 2023, Meta released LLaMA ( Meta AI), a family of open-source language models ranging from 7 billion to 65 billion parameters. Unlike GPT-4 or Claude, these weights were publicly available. Anyone with internet access could download them.
Within weeks, the open-source community demonstrated something remarkable. Stanford researchers released Alpaca, a fine-tuned version of LLaMA-7B trained on 52,000 instruction-following examples generated by GPT-3.5. The fine-tuning cost roughly $600 in cloud compute. Vicuna followed, trained on 70,000 user conversations from ShareGPT. WizardLM demonstrated that evolving simple instructions into complex ones dramatically improved instruction-following ability.
The explosion happened because of two techniques: LoRA (Low-Rank Adaptation), published by Hu et al. in 2021, and (Quantised LoRA), published by Dettmers et al. in May 2023. These reduced the memory required to fine-tune a 7-billion-parameter model from over 100 GB to under 8 GB. A single consumer GPU could now do in hours what previously required a data centre.
If a PhD student with a single GPU and a weekend can fine-tune a capable language model, what does that mean for the cost and accessibility of custom AI?
The Security and Ethics stage ensured your agents are safe and responsible. This stage pushes capability further. Fine-tuning lets you specialise a model for your domain using your data, without sending that data to a third-party API.
Next: When Prompting Is Not Enough.
Prompt engineering is fast, cheap, and reversible. For most tasks it is the right starting point. Fine-tuning is slower, more expensive, and harder to reverse. It addresses the specific problems prompting cannot solve: consistent output formats without multi-hundred-token instructions, specialised domain knowledge not present in the base model, dramatically reduced inference costs at high volume, and fully local deployments with no API dependency.
The key word is "cannot." If a well-crafted prompt reliably produces the output you need, fine-tuning adds cost and complexity without benefit. Exhaust prompting first. Fine-tuning is the answer when you have tried and the model demonstrably fails on your specific task distribution.
The decision between fine-tuning and prompting is primarily economic: compare the one-time cost of fine-tuning and against the ongoing cost of larger prompts and more capable models at your request volume.
Next: Full Fine-tuning Versus Parameter-efficient Fine-tuning.
Full fine-tuning updates every weight in the model. A 7-billion-parameter model requires approximately 28 GB of GPU memory to store weights at FP32 (32-bit floating point) precision, plus additional memory for activations, gradients, and optimiser states. Total memory requirement: over 100 GB. This demands expensive multi-GPU clusters.
PEFT (Parameter-Efficient Fine-Tuning) methods update only a small fraction of weights while keeping the vast majority frozen. The most widely used PEFT technique is LoRA (Low-Rank Adaptation). Instead of updating the full weight matrix W, LoRA inserts two small trainable matrices A and B alongside it. During the forward pass, the effective weight becomes W + AB. Only A and B are updated during training.
At rank r=8, the number of trainable parameters drops by roughly 1,750x compared to full fine-tuning. For a 7B model: instead of 7 billion trainable parameters, you update roughly 4 million. Memory requirement: around 16 GB with standard LoRA, and under 8 GB with QLoRA.
QLoRA (Quantised LoRA), published by Dettmers et al. in 2023, adds one more step: it compresses the frozen base model weights to 4-bit precision before training. This reduces memory by roughly 4x compared to standard LoRA. The trainable adapter matrices still operate in higher precision (bfloat16), so training quality is maintained. QLoRA brings a 7B fine-tuning run under 8 GB, which puts it within reach of a single consumer GPU such as the NVIDIA RTX 3090 or 4090, or of a free Google Colab session with a T4 GPU.
Next: Dataset Preparation.
Dataset quality determines fine-tuning quality more than any hyperparameter or architecture choice. The model can only learn patterns present in the training data. Garbage in, garbage out applies with particular force to fine-tuning, because the model will faithfully reproduce not just the style but the errors and inconsistencies in your examples.
The standard format for instruction fine-tuning pairs each example with an instruction, optional input, and the desired output. The model learns to follow the instruction pattern rather than the specific content. Training on 500 diverse, high-quality examples consistently outperforms training on 5,000 low-quality ones.
Before training, audit your dataset for these critical properties. Every example should have an instruction that is specific and consistent in format. Outputs must be correct and ideally reviewed by a domain expert. No example should contain personally identifiable information (PII). Edge cases and failure modes should be explicitly represented, not just easy, clean examples. Split the dataset into training, validation, and test sets at an 80/10/10 ratio minimum.
The gates run in this order because a failure at any one of them returns the work to the data and not to the hyperparameters, so a run launched on an unaudited set pays for the compute twice.
The training set clears five checks before the run, in this order. Every failure sends the work back to the data, never to the hyperparameters, and the score only counts when base model, best prompt and tuned adapter meet the same held-out split.
Common misconception
“Using a more powerful model to generate training data automatically produces a high-quality dataset.”
Generating training data via distillation from a stronger model (for example, using GPT-4o to create examples for training a 7B model) is a legitimate and often effective technique. However, generated data contains errors. If you do not review a sample before training, the fine-tuned model learns those errors confidently. Always sample and human-review generated training data. Automated generation accelerates data collection; it does not replace quality control.
Next: Running a QLoRA Fine-tuning Job.
The Hugging Face ecosystem provides the standard Python libraries for LoRA and QLoRA fine-tuning. You need four packages: transformers (model loading and tokenisation), peft (the PEFT library, which implements LoRA),trl (the TRL library, which provides SFTTrainer for supervised fine-tuning), and bitsandbytes (4-bit for QLoRA).
The training configuration involves three key choices. First, the LoRA rank (r): higher rank means more trainable parameters and potentially higher quality, but more memory and slower training. Rank 8 to 16 is typical for most tasks. Second, the target modules: which layers to add adapters to. The query and value projection layers (q_proj, v_proj) are standard choices. Third, the learning rate: 2e-4 is a common starting point for LoRA fine-tuning.
After training, evaluate on your held-out test set using task-specific metrics. Training loss decreasing is necessary but not sufficient. For extraction tasks, measure precision, recall, and F1 score. For generation, use ROUGE-L (overlap with reference outputs) and human evaluation. For JSON output tasks, measure schema validity rate and field-level accuracy. Compare the fine-tuned model against the base model and against prompting on the same test set.
Next: Fine-tuning Versus Prompting: the Decision Framework.
Use prompting when your volume is low to medium, the base model can produce acceptable outputs with detailed instructions, and you need results immediately. Choose fine-tuning when you face high request volume (10,000 or more calls per day), the model fails consistently even with careful prompting, you need exact and consistent output formats, inference latency must decrease, or data privacy requirements prevent use of external APIs.
One common confusion: fine-tuning is not a cure for hallucination. A fine-tuned model can produce confident, well-formatted, completely incorrect output. Fine-tuning teaches style, format, and domain conventions. For factual accuracy, combine fine-tuning with , which provides the model with retrieved evidence at inference time rather than baking facts into weights.
EU AI Act Article 53 imposes baseline obligations on all providers of general-purpose AI (GPAI) models, and Article 55 adds further obligations for providers of GPAI models with systemic risk. If you fine-tune an open-source model and offer it to third parties, assess whether these obligations apply. Hugging Face model card standards require documenting training data, intended use, and known limitations before publishing a fine-tuned model to the Hub.
Common misconception
“Fine-tuning makes a model more accurate and trustworthy by teaching it facts.”
Fine-tuning adjusts style, format, and behavioural patterns. It does not give a model new factual knowledge in a reliable, retrievable way. Weights encode statistical associations, not structured facts. A fine-tuned model will confidently generate outputs that look like your training examples, including plausible-sounding but fabricated ones. Retrieval-augmented generation (RAG) is the correct tool for factual grounding.
Your company processes 50,000 support tickets per day through an LLM that extracts issue category and urgency using a 2,000-token prompt with GPT-4o. You want to reduce costs by 90%. Which approach is most justified?
What does 'trainable params: 0.056%' mean in a QLoRA fine-tuning run output?
Your fine-tuned extraction model achieves 92% accuracy on held-out test cases. You want to reach 95%. Which intervention is most likely to be effective?
A colleague says your fine-tuned customer support model is now 'more factually reliable' because it was trained on verified company documentation. What is the most accurate response?
Hu, E. et al. (2021). LoRA: Low-Rank Adaptation of Large Language Models
arXiv:2106.09685
The original LoRA paper. Quoted in Section 19.2 to explain the low-rank decomposition mechanism and why it achieves comparable quality to full fine-tuning.
Dettmers, T. et al. (2023). QLoRA: Efficient Finetuning of Quantized LLMs
arXiv:2305.14314
The QLoRA paper. Quoted in Section 19.4 to explain NF4 quantisation and why it enables fine-tuning on consumer hardware.
github.com/huggingface/peft
The standard Python library implementing LoRA, QLoRA, and other PEFT methods. The SFTTrainer and LoraConfig APIs referenced in this module come from this library.
Taori, R. et al. (2023). Stanford Alpaca: An Instruction-following LLaMA model
crfm.stanford.edu/2023/03/13/alpaca.html
The Alpaca model demonstrating that instruction fine-tuning a 7B open-source model on 52,000 examples produces competitive quality. Referenced in the opening case study.
General-purpose AI model obligations
Establishes transparency, documentation, and copyright obligations for providers of GPAI models. Referenced in Section 19.5 in the context of publishing fine-tuned models to third parties.
Module 27 of 40 · Advanced Mastery