Skip to content

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.

Common misconception: “Fine-tune the model on our documents so it knows them.” It will half-remember them and still hallucinate. Use RAG for knowledge; use fine-tuning for behaviour.

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.

Input xhidden stateW (frozen)d × d, 4-bit in QLoRAW·xoriginal outputSumW·x + (α/r)·B·A·xAr × d, rank r ≈ 8–64Bd × r, starts at 0Adapter filetens of MBFrozen path (billions of parameters, unchanged)Trainable path (millions of parameters)xB·A·x
Because B starts at zero, training begins exactly at the base model. You ship a small adapter, not a new model.

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
Why a low-rank update is enoughΔW is the change fine-tuning makes to one weight matrix. LoRA stores it as B × A with rank r instead of a full matrix.
The update:

Strength of each direction: 6 · 3 · 1.2 · 0.5 · 0.25 · 0.12 · 0.06 · 0.03 (green = kept)

Full ΔW (64 numbers)
Rank-2 B × A (32 numbers)
What rank r misses

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
  1. 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.
  2. 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?
  3. 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?
  4. 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?
Tip: A good first run: r = 16, α = 32, LoRA on all linear layers (attention and MLP), learning rate around 2e-4, then change one thing at a time. Raising r rarely fixes a data problem.

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.

LoRA / QLoRA memory calculatorPick a model and adapter settings. See how few parameters you actually train, and whether it fits your GPU.
Adapt:

Trainable 41.9 M parameters = 0.522% of 8.0 B · adapter file ≈ 84 MB · estimated GPU memory 7.7 GB

Frozen weights: 4.4 GB
Adapter + grads + optimizer: 0.7 GB
Activations: 1.6 GB
Framework overhead: 1.0 GB
T4 16 GB (free Colab)fits
L4 24 GBfits
A100 40 GBfits
A100 / H100 80 GBfits

Estimates assume gradient checkpointing and keep 10% of GPU memory free. Measure on your hardware before you book a large GPU.

Guided experiments
  1. 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?
  2. 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?
  3. 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?
  4. 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?
Tip: Run out of memory? Shorten sequences, lower the batch size and use gradient accumulation, turn on gradient checkpointing, then try a smaller model. Lowering the rank barely helps.

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.

In production: The maintenance cost is real: every new base model release means re-running data prep, training and evaluation. Budget for it before you commit.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

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

Further reading

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

1. Your support bot must answer from a policy manual that changes monthly. Best approach?
2. Why does LoRA initialise B to zero?
3. What does QLoRA change compared with LoRA?
4. Golden-set examples ended up in the training data. The likely effect?
5. Which is a good reason to fine-tune?
6. Why is B initialised to zero in LoRA?

Interview questions

  1. When would you fine-tune instead of using RAG or better prompting? Give a real example.
  2. Explain LoRA to a backend engineer. Why does it use so little memory?
  3. How do you build a fine-tuning dataset from production data safely?
  4. How do you prove a fine-tuned model is better than the prompted baseline?
  5. 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).