Courses / GenAI & LLM / Module 9
Module 9: Fine-tuning: LoRA/QLoRA, SFT, preference tuning
14 h · theory 4 · hands-on 6 · project 3 · revision 1
You will be able to
- Decide between prompting, RAG and fine-tuning with evidence
- Prepare an instruction dataset from your own labelled data
- Fine-tune a small open model with QLoRA (TRL + PEFT)
- Evaluate the tuned model against the baseline on quality, latency and cost
Capstone increment: A fine-tuned small model for one extraction task, compared with the prompted baseline and wired in behind a flag.
Job-description skills: Fine-tuning, PEFT/LoRA, Hugging Face Transformers · Lab tools: transformers, peft, trl, unsloth, datasets
1. Prompt, retrieve or fine-tune?
Fine-tuning changes the model's weights using your examples. It is the right tool for teaching behaviour: a strict output format, a house style, a narrow classification, or getting a small cheap model to match a large one on one task. It is the wrong tool for teaching facts: knowledge that changes or must be cited belongs in retrieval.
Earn the right to fine-tune. First get the best result you can with prompting and RAG, measured on your golden set. Fine-tune when the gap is clear and the payoff is real: lower latency, lower cost per call, data that can't leave your servers, or quality the prompted model can't reach.
2. LoRA and QLoRA
Full fine-tuning updates every weight and needs several times the model's size in GPU memory. LoRA (Hu et al., 2021) freezes the pretrained weights and learns a small low-rank update for chosen layers: two thin matrices A and B whose product is added to the frozen weight. B starts at zero, so training starts exactly at the base model, and you ship a small adapter file.
QLoRA (Dettmers et al., 2023) also stores the frozen weights in 4-bit NF4, cutting memory again so an 8B model can be tuned on a single consumer or free-tier GPU. Quality is usually close to 16-bit LoRA; measure it on your task.
Deep dive
Deep dive: the maths of LoRA, with real numbers
Fine-tuning turns a frozen weight matrix W into W + ΔW. LoRA doesn’t learn ΔW directly. It learns two thin matrices, B (d_out × r) and A (r × d_in), and uses ΔW = (α / r) · B A. With r much smaller than d, the update can only point in r directions. That is the bet, and the LoRA paper found real fine-tuning updates have a low “intrinsic rank”.
A starts random and B starts at zero, so at step 0 the model is exactly the base model and training starts from a safe place. After training you can merge B A into W, so inference costs nothing extra, or keep adapters separate and swap them per customer or task.
QLoRA stores the frozen W in 4-bit NormalFloat (NF4), a format whose 16 levels are placed where normally distributed weights are densest. It also quantizes the quantization constants (double quantization) and pages optimizer state to CPU memory when it spikes. The adapters still train in 16-bit; only the frozen base is compressed.
Worked example: LoRA on the attention projections of Llama 3 8B, r = 16, α = 32
q and o projections (4,096 → 4,096): 4,096×16 + 16×4,096 = 131,072 numbers each k and v projections (4,096 → 1,024): 1,024×16 + 16×4,096 = 81,920 numbers each per layer: 2 × 131,072 + 2 × 81,920 = 425,984 32 layers: 425,984 × 32 = 13.6 million (0.17% of 8 billion) scale α / r = 32 / 16 = 2, so B A’s output is doubled Adam keeps 2 extra numbers per trainable weight: 27 million instead of 16 billion
Strength of each direction: 6 · 3 · 1.2 · 0.5 · 0.25 · 0.12 · 0.06 · 0.03 (green = kept)
Approximation error 19.5% of the update’s size.
The same idea at real size
One d × d projection: full fine-tuning trains 1,67,77,216 numbers; LoRA trains B (d × r) + A (r × d) = 1,31,072, which is 0.78%. The adapter output is scaled by α / r, so if you change r, keep α in proportion or retune the learning rate.
Guided experiments
- Typical fine-tune, r = 1, 2, 3. How fast does the error fall? The LoRA paper found real fine-tuning updates behave like this: a few directions carry most of the change.
- Switch to the flat update. What rank do you need now for under 10% error? What kind of fine-tune might look like this (a new language, a big new skill), and what does it mean for LoRA?
- Real size: d = 4096, r = 16. What fraction of the matrix do you train? Why does this cut optimizer memory far more than it cuts the forward pass?
- B starts at zero. What does that mean for the model’s outputs at step 0, and why is it a safe way to start training?
3. Will it fit on my GPU?
Memory goes to four places: the frozen weights, the trainable adapter with its gradients and optimizer states, activations for the tokens in each step, and framework overhead. Use the calculator to see which one dominates for each model and setting before you rent a GPU.
Trainable 41.9 M parameters = 0.522% of 8.0 B · adapter file ≈ 84 MB · estimated GPU memory 7.7 GB
| T4 16 GB (free Colab) | fits |
| L4 24 GB | fits |
| A100 40 GB | fits |
| A100 / H100 80 GB | fits |
Estimates assume gradient checkpointing and keep 10% of GPU memory free. Measure on your hardware before you book a large GPU.
Guided experiments
- 8B model, r = 16, all linear layers. Turn QLoRA off and on. Which GPU do you need in each case? Where did the saving come from?
- Double the rank from 16 to 32. How much does the adapter grow, and how much does total memory grow? Why is rank rarely the thing that makes you run out of memory?
- Keep the 8B QLoRA setup and raise tokens per step to 32,768. What now dominates memory, and what two settings could you change to fit back on the free T4?
- Can you fine-tune the 70B model on one 80 GB GPU with QLoRA? What would you try first if a 14B model already meets your quality bar?
4. Data is the real work
For a narrow task, a few hundred to a few thousand high-quality examples usually beat tens of thousands of noisy ones. Your best source is reviewed production data: the corrections people made in the capstone's review queue are exactly the hard cases.
Format examples in the chat template the model expects, deduplicate, balance the cases, and keep your golden set completely out of training data. Leakage makes your evaluation meaningless, and it is the most common fine-tuning mistake.
Supervised fine-tuning (SFT) teaches the model to imitate good answers. Preference tuning such as DPO (Rafailov et al., 2023) teaches it to prefer a better answer over a worse one, which helps for tone and judgement calls. Most extraction tasks only need SFT.
5. Prove it beat the baseline
Evaluate the tuned model on the same golden set as the prompted baseline and compare accuracy, latency and cost per document. Check it didn't get worse at things you didn't train for (a small general test set catches this).
Ship it behind a feature flag with the baseline as fallback, and keep the dataset, config, base model version and eval scores together so the run can be reproduced. A fine-tuned model is only as good as your ability to rebuild it when the base model is updated.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 9.1: QLoRA on a free GPU
Fine-tune a 1B-3B instruct model with QLoRA (Unsloth or TRL + PEFT) on 500 extraction examples in a free Colab or Kaggle notebook. Log training and validation loss.
Expected: A saved adapter (tens of MB), loss curves, and sample outputs before and after tuning.
Lab 9.2: Tuned versus prompted (capstone increment)
Evaluate the tuned small model and the prompted baseline on the extraction golden set. Wire the tuned model into the capstone behind a flag with the baseline as fallback.
Expected: A table of field accuracy, p95 latency and cost per document for both; the flag switches models without code changes.
Lab 9.3: Find the leak
Deliberately include 20 golden-set documents in the training data, retrain, and re-evaluate. Then remove them and evaluate again.
Expected: Two scores showing how leakage inflates results, and a data-prep check that now prevents it.
Go deeper
Videos
- LoRA: Low-Rank Adaptation of Large Language Models - Explained visually + PyTorch code from scratch · Umar Jamil · ~26 min. The maths of LoRA made visual, then implemented in PyTorch.
- LoRA & QLoRA Fine-tuning Explained In-Depth · Mark Hennings · ~14 min. A practical guide to rank, alpha and target modules, and what QLoRA adds.
- What is Low-Rank Adaptation (LoRA) | explained by the inventor · Edward Hu · ~7 min. LoRA explained in seven minutes by the person who invented it.
- What is LoRA? Low-Rank Adaptation for finetuning LLMs EXPLAINED · AI Coffee Break with Letitia · ~8 min. A clear visual explanation of low-rank matrices and why the update can be small.
Further reading
- Paper LoRA: Low-Rank Adaptation of Large Language Models · Hu et al., 2021. Section 4 explains B, A, α and the zero init; section 7 shows the low intrinsic rank of real updates.
- Paper QLoRA: Efficient Finetuning of Quantized LLMs · Dettmers et al., 2023. NF4, double quantization and paged optimizers, and the finding that LoRA on all linear layers matters.
- Article Practical Tips for Finetuning LLMs Using LoRA · Sebastian Raschka. Many LoRA experiments summarised: what r, α, learning rate and target layers actually change.
- Docs PEFT documentation · Hugging Face. The library you will use for LoRA adapters: configs, merging and loading many adapters.
- Paper LoRA Learns Less and Forgets Less · Biderman et al., 2024. When LoRA matches full fine-tuning and when it doesn't (large new domains like code).
- Paper Direct Preference Optimization · Rafailov et al., 2023. Preference tuning without a reward model or RL loop; the method behind most open preference-tuned models.
GitHub repositories
- huggingface/peft: LoraConfig options (r, lora_alpha, target_modules) and merging an adapter into the base model.
- huggingface/trl: SFTTrainer and DPOTrainer examples, including the expected dataset formats.
- unslothai/unsloth: The free notebooks for QLoRA on small Llama, Qwen and Gemma models.
- rasbt/LLMs-from-scratch: Chapters 6-7 and the LoRA appendix: fine-tuning for classification and instructions, step by step.
Checkpoint quiz
Interview questions
- When would you fine-tune instead of using RAG or better prompting? Give a real example.
- Explain LoRA to a backend engineer. Why does it use so little memory?
- How do you build a fine-tuning dataset from production data safely?
- How do you prove a fine-tuned model is better than the prompted baseline?
- What does it cost to maintain a fine-tuned model over a year?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).