PEFT, LoRA and QLoRA in depth
- Production
- 45 min
- Lesson 3 of 7 in Fine-tuning
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:Data engineering for fine-tuning
- Completed:Fine-tuning methods: SFT, LoRA, QLoRA and DPOEvaluation and model adaptation
You will be able to
- Derive why a low-rank update is cheap and what it cannot do, and explain why B starts at zero while A starts random and what the alpha/r factor scales.
- Count the trainable parameters of a LoRA setup across a whole model from its rank and target modules, and turn the count into optimiser-state memory.
- Choose target modules, rank, alpha and learning rate for a first run, and name the evidence that would make you change each.
- Explain what NF4, double quantisation and paged optimisers each do, what they cost, and which parts of a QLoRA step stay in 16-bit.
- Decide between LoRA, QLoRA and full fine-tuning for a task, and between merging an adapter and keeping it swappable.
The team has one small GPU, and the model is far bigger than it. Retraining every number in it would not even fit in memory.
Kavya shows a small add-on that attaches to a few layers and learns the changes, leaving the rest as it was. “It cannot hold much,” she says.
How small can the add-on be before it stops changing what Aarav says?
Concept
The add-on in the story stands for a parameter-efficient fine-tuning (PEFT) method: leave the pretrained weights alone and train a small add-on. The best known is LoRALoRALow-rank adaptation: freeze the base weights and train a small low-rank update, a tiny fraction of the parameters. Adapters are small, swappable and mergeable.Open the glossary entry. Its memory-saving cousin is QLoRAQLoRALoRA on top of a base model held in 4-bit precision, which cuts memory a lot at the cost of slower steps. Check quality on your task.Open the glossary entry. In practice you reach for them through the Hugging Face PEFT library, whose configuration object appears at the end of this lesson.
Fine-tuning methods already gave you the basics: LoRA freezes a weight matrix and learns , and a rank-8 adapter on one layer is about 0.39 percent of that layer. When to tune, and what it costs gave the memory rule of 16 bytes per trained parameter. This lesson goes underneath: why a low rank works, how the adapter starts and scales, what a whole model’s count looks like, how to set the knobs, and what QLoRA does to fit a big base on a small card.
Why It Matters
LoRA is the default way teams tune open models, so “explain LoRA” is a standard question, and the follow-ups are where answers split: why is B zero, why alpha over r, which layers, which rank, what does QLoRA add, and when would you not use any of it. A candidate who can derive the parameter count on a whiteboard, and say honestly what the papers did and did not show, is easy to trust. In production the same knowledge decides whether a tune fits the GPU you have and whether you can serve fifty customers from one base model.
Mental Model
Think of the base model as a printed script and the adapter as a card clipped to each page. The card does not replace the page. At every page the reader reads the page, then the card, and adds the two together. Because the cards are small, you can keep a drawer of them, and you can glue one onto the page for good (merging) when you are done.
Where the analogy breaks: the adapter is numbers added into the matrix arithmetic, so it changes how every input passes through that layer, and its size is a dial you set, the rank.
Why a low-rank update works
Full fine-tuning learns an update with the same shape as . For a layer with outputs and inputs that is numbers. LoRA constrains the update to a product of two thin matrices:
with of shape and of shape . The count falls from to .
Take a layer of (an illustrative shape). A full update is numbers. At rank 16 the adapter is , about 1.07 percent of the layer. The saving comes from the thin shape, and it grows as and grow while stays put.
| Update | Parameters | Share of the layer |
|---|---|---|
| Full update () | 11,534,336 | 100% |
| LoRA rank 16: | 122,880 | about 1.07% |
What do you give up? A product has rank at most . It can only move the layer’s output within an -dimensional family of directions, however many examples you train on. That is a real limit, and the reason LoRA is good at narrow changes (format, tone, a routine) and weaker at big new skills.
Why believe a small r is enough? The LoRA paper states a hypothesis, not a proof: that the change in weights during adaptation has a low “intrinsic rank”. Its evidence is empirical. On GPT-3 175B with both the query and value projections adapted, WikiSQL accuracy was 73.4 at rank 1 and 73.5 at rank 64, and the authors note that a rank as small as one sufficed for those datasets. They also report that the learned update does not repeat the strongest directions already in ; it amplifies directions that does not emphasise. Treat these as results on those tasks and models, not a law for yours.
Setting to the rank of the original matrix gets you back to a fully expressive update, which is why full fine-tuning can be seen as the high-rank end of the dial.
Initialisation and scaling
The adapted layer computes:
Two choices keep training sane.
Initialisation. The paper initialises with random Gaussian values and with zeros, so and the model starts exactly as the base. PEFT’s default also sets to 0 (its documentation says the adapter is then a no-op before training), though it draws from a Kaiming-uniform distribution rather than a Gaussian.
Why not start both at zero? Write the scale . For a loss and layer output , the gradient with respect to is
and the gradient with respect to is
If both start at zero, both gradients are zero and nothing ever moves. If only is zero, the first gradient is non-zero, so moves first and then starts receiving signal. If both were random, would be non-zero from the start, so the model would already differ from the base before any training step. Zero on one side, random on the other, is the smallest setup that starts at the base and still learns.
| Initialisation | Gradient for B | Gradient for A | What happens |
|---|---|---|---|
| Both zero | Zero ( is zero) | Zero ( is zero) | Nothing ever moves |
| A random, B zero | Non-zero | Zero at first | B moves first, then A starts to receive gradient |
Scaling. The factor sets how loudly the adapter speaks relative to . With rank 8 and alpha 32 the scale is 4; with rank 32 and the same alpha it is 1. The paper sets to the first it tries and does not tune it, and describes as a scaling of the update. In PEFT’s LoraConfig the defaults are r=8, lora_alpha=8 and dropout 0.0, which gives a scale of 1. One option, use_rslora, changes the scale to instead.
| Rank | Alpha | Scale |
|---|---|---|
| 8 | 32 | 4 |
| 32 | 32 | 1 |
| 8 | 8 (PEFT default) | 1 |
| 16 | 32 | 2 |
The practical reading: alpha and the learning rate both control how far the adapter moves per step, so changing one without the other changes the experiment. Change one thing at a time, and write down both.
Counting a whole model
A per-layer count is not a plan. A plan needs the total across layers and matrices. The recipe is one line: for every adapted matrix add , then sum.
Here is a made-up decoder to work through (illustrative, not any real model): hidden size , 24 layers, a gated MLP with intermediate size , and full multi-head attention, so the query, key, value and output projections are each . Ignore embeddings and norm layers.
Base linear parameters per layer: attention , plus MLP , which is 51,380,224. Over 24 layers that is 1,233,125,376, about 1.23 billion.
Rank 16, two target choices:
| Adapted matrices | Per layer | 24 layers | Share of base |
|---|---|---|---|
| Query and value only | 3,145,728 | about 0.26% | |
| All linear layers | 15,138,816 | about 1.23% |
Memory follows from the rule in the previous lesson. Training the 15.1 million adapter parameters at 16 bytes each costs about 0.24 GB of states. The whole job in states only (activations excluded, as before):
| Method | Formula | Total |
|---|---|---|
| Full fine-tune | about 19.7 GB | |
| LoRA, 16-bit base | about 2.7 GB | |
| QLoRA, 4-bit base | (+ constants, next section) | about 0.9 GB |
Two things to notice. Doubling the rank doubles the adapter and barely moves the total, because the frozen base dominates. And the trainable share is a poor guide to quality: the choice of matrices changed the count fivefold here, while the paper’s rank sweep showed almost no accuracy change.
One shape detail for interviews: with grouped-query attention the key and value projections map inputs to a smaller output. The count then shrinks for those two matrices, because is smaller. The formula does the work; you do not need to memorise a model.
Choosing targets, rank and learning rate
Start from evidence, not from habit.
Target modules. The original LoRA study adapted only the attention weights and left the MLP frozen. With a fixed budget of 18 million parameters on GPT-3 175B, adapting both the query and value projections matched or beat putting the whole budget into one matrix type (adapting all four scored higher still on MultiNLI, and the paper reports query plus value as best overall). The QLoRA paper later reported that matching full fine-tuning required LoRA on all linear transformer-block layers. So both papers are true together: attention-only is the cheapest start, and when quality lags full fine-tuning, widening the targets is the first lever. In PEFT, target_modules accepts a list of names, a pattern, or "all-linear"; if you leave it unset, PEFT chooses by model architecture, and raises an error if it does not know the architecture.
Rank. The LoRA paper saw almost no gain from rank 1 to 64 on its tasks with query and value adapted. QLoRA reported that rank was unrelated to final performance when LoRA was applied on all layers. Both findings point the same way: more rank is not the first fix. A fair test: train two ranks with everything else fixed, compare a held-out score, and raise rank only if the gap is real. The “LoRA Learns Less and Forgets Less” study is a reason for care on hard domains, covered below.
Learning rate. The QLoRA paper used 2e-4 for the 7B and 13B models and 1e-4 for 33B and 65B, with a larger batch for the bigger ones. Those are one team’s values, on one setup, not defaults for you. Adapter runs are usually given a larger learning rate than full fine-tuning, because the adapter starts from nothing and has few parameters. Sweep it on a small run and watch the held-out metric, not only the training loss.
Dropout and epochs. lora_dropout defaults to 0.0 in PEFT. A small value is a regulariser for small datasets; check it on your validation set. Stop on the validation curve, not on a fixed epoch count.
| Knob | Starting point | Change it when |
|---|---|---|
| Targets | attention first, or all linear | Held-out quality is below a full tune |
| Rank | A small value such as 8 or 16 | A two-rank test shows a real gap |
| Alpha | Fixed value, noted next to rank | You change rank and want to keep the scale |
| Learning rate | A short sweep around your reference | Loss flat (too low) or spikes (too high) |
QLoRA and its three memory tricks
QLoRA keeps the frozen base in 4 bits and trains 16-bit LoRA adapters on top. Three ideas make that work, and each has a cost.
NF4 (4-bit NormalFloat). Four bits give 16 levels. Pretrained weights are mostly zero-centred and bell-shaped, so the paper builds a 4-bit data type that is information-theoretically optimal for normally distributed values, instead of spacing the 16 levels evenly. Weights are quantised in blocks of 64, each block with its own scaling constant, so one outlier cannot ruin the whole matrix. Cost: rounding error in the base weights, which you must check on your task.
Double quantisation. Those per-block constants are themselves numbers to store. With 32-bit constants and a block of 64, they add 0.5 bits per parameter. The paper quantises the constants to 8 bits with a block size of 256, which brings the overhead down to 0.127 bits per parameter, a saving of 0.373 bits. For a 7-billion-parameter base that is about 0.11 GB of constants instead of 0.44 GB; for 70 billion, about 1.1 GB instead of 4.4 GB. This is the number the previous lesson’s table left out. Cost: slightly more dequantisation work.
| Per-block constants | Overhead per parameter |
|---|---|
| 32-bit constants, block of 64 | 0.5 bits |
| Constants quantised to 8 bits, block of 256 | 0.127 bits |
| Saving | 0.373 bits |
Paged optimisers. Training memory is spiky: a long batch can push the optimiser state over the edge of the GPU for a moment. The paper uses NVIDIA unified memory so optimiser state can move between GPU and CPU memory automatically when the GPU runs out. It prevents the out-of-memory crash on a spike. Cost: when paging happens, steps slow while pages move.
What stays in 16-bit: the adapters, their gradients and their optimiser state, and the matrix multiply itself. The paper says that whenever a quantised weight is used, it is dequantised to BFloat16 and the multiply runs in 16-bit. Storage is 4-bit; compute is not.
Net effect on speed: the extra dequantisation makes QLoRA steps slower than 16-bit LoRA, which is the price of the memory.
LoRA, QLoRA or full fine-tuning
Choose on the constraint you actually have.
- LoRA, 16-bit base. You have the memory for the base and want the fastest, simplest adapter run. Narrow changes: format, tone, routines. Many adapters per base.
- QLoRA. The base does not fit at 16 bits. You accept slower steps and a small quantisation risk to fit a bigger model on a smaller GPU. The authors report that it fine-tunes a 65B model on a single 48 GB GPU and keeps 16-bit performance in their experiments; check it on your task.
- Full fine-tuning. The change is large and you have data and GPUs for it. The study “LoRA Learns Less and Forgets Less” compared the two on programming and mathematics with both instruction tuning and continued pretraining on 20 billion tokens. In the standard low-rank settings LoRA substantially underperformed full fine-tuning on those domains. It also forgot less of the base model’s abilities elsewhere and kept more diverse outputs. The authors suggest the full-tune update has a rank 10 to 100 times higher than typical LoRA settings.
The trade-off, stated plainly: LoRA buys memory and lower forgetting and pays in the size of change it can learn. A cheap ladder follows: LoRA on all linear layers first, a higher rank if the held-out gap persists, and full fine-tuning only if the gap still justifies its cost.
Merging or swapping
After training you have a base and an adapter file. You can serve them in two ways.
Merge. Compute once and serve . The LoRA paper states that this adds no inference latency compared with a fully tuned model. In PEFT, merge_and_unload() merges and drops the adapter weights; it is not in-place, so you must use the returned model. If you want to undo it, merge_adapter() and unmerge_adapter() keep that option open.
Swap. Keep the adapter separate and attach different ones to one base: for the made-up model above, 15,138,816 numbers at 2 bytes is about 30 MB per adapter, against about 2.5 GB for a 16-bit copy of the base. The paper notes that after merging, batching inputs for different tasks with different A and B in one forward pass is not straightforward, which is the case for keeping them apart when you serve many tenants.
| Need | Choose |
|---|---|
| One adapter dominates traffic, lowest latency | Merge |
| Many tenants or tasks on one base | Swap |
| A/B test or fast rollback | Swap, or merge reversibly |
If the base was 4-bit during training, merge into a 16-bit copy of the base, not into the 4-bit weights, because the small must be added at a precision that can hold it. Then re-run your evaluation, since the merged and quantised model is not the same model you trained.
# Illustrative sketch, not run here. Field names follow the PEFT LoraConfig page.
from peft import LoraConfig, get_peft_model
config = LoraConfig(
r=16,
lora_alpha=32, # scale = 32 / 16 = 2
lora_dropout=0.05,
target_modules="all-linear",
)
model = get_peft_model(base_model, config) # base_model: your loaded model
# ... train, then either keep the adapter separate or:
merged = model.merge_and_unload() # returns the merged modelReal-World Application
A team serves a house-format summariser for 40 customers on one open model. They use LoRA on all linear layers at a small rank, one adapter per customer, kept separate so one base serves all. The base fits their 24 GB card only at 4 bits, so they train with QLoRA and accept slower steps. For the one customer who needs a deep new capability on a large code-heavy dataset, they run a full fine-tune and compare it with the adapter on a held-out set first.
Interview Perspective
Expect: “Explain LoRA”, “Why is B initialised to zero?”, “Which layers would you adapt, and what rank?”, “What does QLoRA add?”, “LoRA or full fine-tuning?”.
A strong answer gives , the count, why zero on one side only, what alpha over r scales, the targets-before-rank point with the papers behind it, the three QLoRA parts and what remains 16-bit, and the limit of low rank on large new skills. Common mistakes: claiming rank is the main quality lever, saying QLoRA computes in 4-bit, and claiming LoRA is a hundredfold saving in compute (it saves memory far more than compute).
Provenance: Common industry pattern. These are questions this topic tends to draw; none is verified for a named company.
Practice Questions
Provenance: generated practice.
- Basic: What do
AandBrepresent, and why doesBstart at zero? - Intermediate: Count the trainable parameters for rank 8 on all linear layers of a model of your choice, and state the optimiser-state memory.
- Advanced: Your QLoRA run is slower than 16-bit LoRA and scores a point lower on your evaluation. When do you accept that, and when do you move to 16-bit LoRA or a full tune?
- Product: A customer wants a private tune of a shared base model. Do you merge or keep an adapter, and what does each cost you?
Activity
Do, notice, apply.
- Do. Pick a model with published layer shapes. Count the adapter parameters at rank 8 for attention only, then for all linear layers.
- Notice. Which choice changed the count more: doubling the rank or adding the MLP matrices? What did you leave out of the memory estimate?
- Apply. Write the two-rank experiment you would run to decide whether to raise the rank: what you hold fixed, what you measure, and what difference would make you act.
Homework
Work on the LoRA fine-tune vs prompt baseline project. Before training, write the configuration note: targets, rank, alpha, learning rate, the adapter parameter count and its optimiser-state memory, and the single change you will try first if the held-out score lags. Record real measurements only.
Quick Revision
- LoRA learns , so numbers instead of ; the update has rank at most .
- and random: starts as the base and still has a non-zero gradient to learn from.
- The update is scaled by alpha over r; change one of rank, alpha or learning rate at a time.
- Targets before rank: both papers point there. Rank was close to flat in their tests.
- QLoRA: NF4 base in blocks of 64, constants quantised again (0.5 to 0.127 bits per parameter), paged optimisers; the multiply is in 16-bit.
- Full fine-tuning can learn more on hard domains; LoRA forgets less. Merge for one hot adapter, swap for many.
Check yourself
- Checkpoint (answer aloud, no notes): Explain LoRA and QLoRA to a backend engineer: the maths, the memory, and what they cannot do.
- Re-test (nearby variant): Your adapter fixed the tone but accuracy on rare intents fell. What do you check first, and what do you change?
- Misconception to avoid: “A higher rank always means a better model.”
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
LoRA (PEFT conceptual guide) (opens in a new tab)Essential
The conceptual guide to LoRA in PEFT, the natural next page after the configuration reference.
Further reading
LoRA Without Regret (opens in a new tab)Essential
Experiments on when LoRA matches a full tune, which layers to adapt and how learning rate relates to rank.
Practical Tips for Finetuning LLMs Using LoRA (Low-Rank Adaptation) (opens in a new tab)
An experimenter's account of rank, alpha and target choices that is worth comparing against the papers.
Research papers
LoRA Learns Less and Forgets Less (opens in a new tab)
The evidence for when low-rank adaptation is the wrong tool, with its best-practice section.
Hands-on
How to load a 4-bit NF4 base with double quantisation and a bfloat16 compute type in the Hugging Face stack, with a link to a training notebook.
More for this module: Fine-tuning resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Fine-tuning.
Check yourself17 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.