Slides · Fine-tuning
PEFT, LoRA and QLoRA in depth
1 / 35
PEFT, LoRA and QLoRA in depth
Teach a large model something new while training only a sliver of it.
By the end you can derive the adapter size from a matrix shape, count parameters across a whole model, set the main knobs from evidence, explain what QLoRA stores in 4 bits and what it still computes in 16, and choose between LoRA, QLoRA, a full tune, a merged adapter and a swappable one.
Concept
The model will not fit, so change less of it
- The team has one small GPU and a base model far larger than it. Training every weight needs gradients and optimiser state for every weight, on top of the weights themselves.
- Parameter-efficient fine-tuning (PEFT) freezes the pretrained weights and trains a small add-on instead.
- The best-known add-on is LoRA. Its memory-saving cousin is QLoRA.
- The question this lesson answers: how small can the add-on be before it stops changing the model’s behaviour?
Concept
Mental model: a card clipped to each page
- The base model is a printed script. The adapter is a small card clipped to each page.
- At every page the reader reads the page, then the card, and adds the two readings together.
- Cards are small, so a drawer of them is cheap. A card can also be glued onto the page for good, which is merging.
- Where it breaks: the card is numbers added inside the matrix arithmetic, so it changes how every input flows through that layer. Its size is a dial, called the rank.
Math
Replace one big update with two thin ones
full update: ΔW has d×k numbersLoRA update: ΔW=BA(B is d×r, A is r×k)trainable: r⋅(d+k)| Symbol | Meaning |
|---|---|
| d | Outputs of the frozen weight matrix W |
| k | Inputs of W |
| r | The rank: the shared inner width of the two thin matrices |
| r⋅(d+k) | What the adapter trains: the sum of the two sides, times the rank |
- The count falls from d⋅k to r⋅(d+k). The saving grows as d and k grow while r stays fixed.
- The original paper frames the update as a product of two low-rank matrices added to the frozen weight.
Source[1] LoRA: Low-Rank Adaptation of Large Language Models
Worked example
Worked example: one 2,048 by 5,632 layer
An illustrative shape, rank 16.
| Update | Parameters | Share of the layer |
|---|---|---|
| Full update (2,048×5,632) | 11,534,336 | 100% |
| LoRA, rank 16: 16×(2,048+5,632) | 122,880 | about 1.07% |
- The thin factors hold 16×2,048=32,768 and 16×5,632=90,112 numbers, which add up to 122,880.
- The exact share is 1.065 percent.
Code
What a thin product cannot do
Python
import torch
for r in (2, 4, 8):
A = torch.randn(r, 64); B = torch.randn(64, r)
print(r, torch.linalg.matrix_rank(B @ A).item(), r * 128, 64 * 64)| Test (torch 2.14.1, 2026-10-24) | Rank of BA | Adapter numbers | Full update |
|---|---|---|---|
| r=2 | 2 | 256 | 4,096 |
| r=4 | 4 | 512 | 4,096 |
| r=8 | 8 | 1,024 | 4,096 |
- The product never exceeds rank r, however long training runs. The layer’s output can shift along at most r independent directions.
- This ceiling is consistent with LoRA suiting narrow changes such as format, tone or a routine, and being weaker for broad new skills. That reading is this lesson’s interpretation. The LoRA-versus-full study only says the rank gap may explain some of LoRA’s shortfall on code and mathematics.
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[2] LoRA Learns Less and Forgets Less
Concept
Why believe a small rank is enough
- The paper states a hypothesis, not a proof: the change in weights during adaptation has a low intrinsic rank.
- Its evidence is empirical. On a very large model with the query and value projections adapted, a WikiSQL result of 73.4 at rank 1 sat next to 73.5 at rank 64.
- Those are results on that model and those tasks. They license trying a small rank first, not assuming it works on your data.
- Full fine-tuning is the other end of the dial: an update with the full rank of the matrix.
Source[1] LoRA: Low-Rank Adaptation of Large Language Models
Check yourself
Check: size one adapter
An MLP up-projection takes 4,096 inputs and produces 11,008 outputs. A rank-32 adapter is attached to it. How many parameters does the adapter add, and what fraction of the full update is that?
Answer
32×(4,096+11,008)=483,328 trainable numbers. The full update would be 4,096×11,008=45,088,768, so the adapter is about 1.07 percent of it.
Diagram
The adapted layer, drawn
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[3] LoRA (PEFT package reference: LoraConfig and merging)
Worked example
Why one side zero and the other random
Tested on a small randomly initialised decoder with PEFT 0.21.2. The magnitudes below belong to that test model; the zero-versus-non-zero pattern is the lesson.
| Start | Output equals the base? | Gradient on A at step 0 | Gradient on B at step 0 |
|---|---|---|---|
| B zero, A random (default) | yes | 0 | non-zero (about 2.8e-3) |
| Both zero | yes | 0 | 0 (every adapter gradient was exactly 0) |
| Both random | no, logits differ by up to 1.4 | non-zero | non-zero |
- Each factor’s gradient is multiplied by the other factor. If both are zero, nothing can ever start moving.
- In a second test, B took a first step and the gradient on A then became non-zero (7e-7 at step 1, 1.4e-6 at step 2).
- The paper uses a Gaussian for A and zeros for B. The PEFT reference says the default leaves the adapter a no-op before training.
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[3] LoRA (PEFT package reference: LoraConfig and merging)
Worked example
What alpha over r scales
The adapter term is multiplied by α/r before it is added to the frozen output.
| Rank r | α | Scale read from PEFT |
|---|---|---|
| 8 | 32 | 4.0 |
| 32 | 32 | 1.0 |
| 8 | 8 | 1.0 |
| 16 | 32 | 2.0 |
16, with use_rslora=True | 32 | 8.0 |
- Tested on PEFT 0.21.2 by reading the scaling value off an adapted layer.
- The
LoraConfigdefaults on that version arer=8,lora_alpha=8and dropout 0.0, a scale of 1. The rsLoRA option divides by the square root of r instead. - The paper set alpha to the first rank it tried and did not tune it. Alpha and learning rate both change how far the adapter moves, so change one and record both.
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[3] LoRA (PEFT package reference: LoraConfig and merging)
Check yourself
Check: hold the scale
A run used r=64 and α=128. You want to try r=16 and keep the same scale. What α do you set, and what would the scale be if you left α at 128?
Answer
The original scale is 128/64=2. To keep 2 at rank 16, set α=32. Leaving α at 128 gives 128/16=8, four times louder. Any change to the scale also changes the effective learning behaviour, so note it next to the learning rate.
Concept
Counting a whole model
- A per-layer count is not a plan. The plan needs a total.
- The recipe is one line: each adapted matrix contributes r×(inputs+outputs), and the plan is the sum across matrices and layers.
- Narrow matrices add less. A key projection with fewer outputs than inputs costs less than a square one at the same rank.
- This count ignores embeddings and norm layers, so the totals below are for the adapted linear layers only.
Worked example
Worked example: a made-up 24-layer decoder
Illustrative, not any real model. Hidden size 2,048, MLP width 5,632 with three matrices, four square attention matrices, 24 layers, rank 16.
| Adapted matrices | Per layer | 24 layers | Share of base |
|---|---|---|---|
| Query and value only | 2×16×4,096=131,072 | 3,145,728 | 0.26% |
| All linear layers | 630,784 | 15,138,816 | 1.23% |
- Base linear weights: 24×(4×2,0482+3×2,048×5,632)=1,233,125,376.
- Per layer, all linear: 4×65,536+3×122,880=630,784.
- The target choice changed the count about fivefold. The rank sweep in the paper barely moved accuracy, so the share of trainable weights is a poor guide to quality.
Code
The formula against the library
Python
from peft import LoraConfig, get_peft_model
cfg = LoraConfig(r=8, lora_alpha=16, target_modules="all-linear")
model = get_peft_model(base_model, cfg)
print(sum(p.numel() for p in model.parameters() if p.requires_grad))| Test: small grouped-query decoder, 4 layers (PEFT 0.21.2) | PEFT count | Formula |
|---|---|---|
| Query and value only, rank 8 | 26,624 | 26,624 |
| Query and value only, rank 16 | 53,248 | 53,248 |
| All linear layers, rank 8 (MLP width 704) | 145,408 | 145,408 |
| All linear layers, rank 16 (MLP width 704) | 290,816 | 290,816 |
- The test model had hidden size 256, MLP width 704, 8 heads and 2 key-value heads, so its key and value projections were narrower than its query projection. The formula still matched.
- With
"all-linear"the output head was left out, as the PEFT reference describes.
Source[3] LoRA (PEFT package reference: LoraConfig and merging)
Worked example
From count to memory
Training states cost about 16 bytes per trained parameter (Adam, mixed precision, from the previous lesson). A frozen weight pays only for its storage.
| Method for the 1.233B decoder | Formula | States only |
|---|---|---|
| Full fine-tune | 16×1.233B | about 19.7 GB |
| LoRA, 16-bit base | 2×1.233B+0.24 GB | about 2.7 GB |
| QLoRA, 4-bit base | 0.5×1.233B+0.24 GB | about 0.9 GB |
- The 0.24 GB is the 15,138,816 adapter parameters at 16 bytes each.
- Doubling the rank doubles that adapter term and barely moves the total, because the frozen base dominates.
- These are floors: activations and the quantisation constants come on top.
Check yourself
Check: the plan on paper
Using the made-up decoder, you raise the rank from 16 to 64 on all linear layers with a 16-bit base. How many adapter parameters, how much adapter state memory, and what happens to the total?
Answer
Rank scales the count linearly: 4×15,138,816=60,555,264 parameters. At 16 bytes each that is about 0.97 GB of adapter states. The total grows from about 2.7 GB to about 3.4 GB, so a fourfold rank increase adds roughly a quarter to the total. The frozen base still takes most of the memory.
Concept
Targets come before rank
- The original study adapted only attention weights. With a fixed budget on a very large model, splitting it across the query and value projections scored 73.7 on WikiSQL. The single matrices scored 70.4 (query), 70.0 (key), 73.0 (value) and 73.2 (output), and the benchmark’s own noise is about 0.5, so the pair led mainly by avoiding the weak single choices.
- The QLoRA authors later reported that LoRA had to cover every linear layer in the transformer blocks to match a full tune, rather than only query and value.
- A later write-up of LoRA experiments also recommends all layers, and reports that attention-only adapters trailed MLP-only ones at a matched parameter count.
- In PEFT,
target_modulestakes a list of names, a regex, or"all-linear". If it is unset, PEFT picks by architecture and raises an error when it does not know the architecture. - Start with all linear layers. Narrow the targets only to save memory you can show you need.
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[4] QLoRA: Efficient Finetuning of Quantized LLMs[5] LoRA Without Regret[3] LoRA (PEFT package reference: LoraConfig and merging)
Concept
Rank and learning rate are not the first fix
- Rank. The original paper saw almost no gain from rank 1 to 64 on its tasks. The QLoRA paper reported no clear effect of rank once all layers were adapted.
- A fair rank test trains two ranks with everything else fixed and compares a held-out score. Raise rank only if the gap is real.
- Learning rate. The QLoRA paper used 2e-4 for its 7B and 13B models and 1e-4 for its 33B and 65B ones. That is one team’s setup on one recipe.
- A write-up of LoRA experiments found the best adapter rate near ten times the full fine-tuning rate, and nearly independent of rank. Treat that as a place to start a sweep, not a rule.
- Judge every sweep on a held-out metric, not on training loss alone.
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[4] QLoRA: Efficient Finetuning of Quantized LLMs[5] LoRA Without Regret
Compare
Knobs and the evidence that moves them
| Knob | Starting point | Change it when |
|---|---|---|
| Targets | All linear layers | Memory, not quality, is the problem |
| Rank | A small value such as 8 or 16 | A two-rank test shows a real held-out gap |
| Alpha | A fixed value written beside rank | You change rank and want the same scale |
| Learning rate | A short sweep around a reference | Loss is flat (too low) or spikes (too high) |
| Dropout | PEFT default of 0.0 | A small dataset overfits on the validation curve |
- Change one knob per experiment and log all of them.
Check yourself
Check: read a sweep
A short learning-rate sweep on an all-linear rank-8 adapter gives these held-out scores (illustrative numbers, one seed each): 5e-5 scores 58, 1e-4 scores 66, 2e-4 scores 71, and 4e-4 scores 63 with loss spikes near step 40. Which rate do you carry forward, and what do you do before trusting it?
Answer
Carry 2e-4 forward: it has the best held-out score and sits below the rate where training became unstable. The spikes at 4e-4 mark the upper edge. Before trusting the winner, repeat it with a second seed, because a few points can be run-to-run noise, and only then spend effort on other knobs. Do not choose by training loss, and do not change rank at the same time.
Diagram
QLoRA: a 4-bit base under a 16-bit adapter
Concept
NF4: levels placed where the weights are
- Four bits give 16 levels. Evenly spaced levels waste resolution, because pretrained weights are mostly near zero and roughly bell-shaped.
- The paper defines a 4-bit NormalFloat type, which it describes as optimal in an information-theoretic sense when weights follow a normal distribution.
- Weights are grouped 64 to a block and each block keeps its own scaling constant, so an outlier only distorts its own group.
- Cost: rounding error in the base weights. Check the tuned model on your own task.
Worked example
Double quantisation: shrink the constants too
Each block of 64 carries a 32-bit constant, which is 0.5 bit per parameter. The paper stores those constants as 8-bit values, grouped 256 per block.
| Per-block constants | Overhead per parameter |
|---|---|
| 32-bit constants, block of 64 | 0.5 bits |
| 8-bit constants, block of 256 | 0.127 bits |
| Saving | 0.373 bits |
- For a 7-billion-parameter base the constants fall from about 0.44 GB to 0.11 GB. For 70 billion, from about 4.4 GB to 1.1 GB.
- Cost: a little more dequantisation work.
Concept
Paged optimisers, and what stays in 16 bits
- Paged optimisers use NVIDIA unified memory so optimiser state can move between GPU and CPU memory when the GPU runs out. A short memory spike no longer ends the run. The paper measured the same training speed as regular optimisers at batch size 16 for a 65B model on a 48 GB card, and left slowdowns during paging for future work.
- Stays in 16-bit: the adapters, their gradients and the matrix multiply itself. The paper does not say what precision the optimiser state uses; the memory count earlier in this deck assumes the usual 16 bytes per trained parameter.
- Stored in 4-bit: only the frozen base weights.
- The paper says a stored weight is dequantised to BFloat16 and the multiply runs in 16-bit. Storage is small, compute is not.
- Likely cost: the extra dequantisation work probably makes QLoRA steps slower than 16-bit LoRA steps. That is this lesson’s inference. The paper does not report this comparison, so time it on your own hardware.
Check yourself
Check: size the constants
A 13-billion-parameter base is stored in NF4 with blocks of 64. How much memory do the per-block constants take with 32-bit constants, and how much after double quantisation? What is the saving?
Answer
Without double quantisation: 13×109×0.5 bits/8≈0.81 GB. With it: 13×109×0.127 bits/8≈0.21 GB. The saving is about 0.61 GB, on top of roughly 6.5 GB for the 4-bit weights themselves.
Diagram
A cheap ladder of choices
Sources[4] QLoRA: Efficient Finetuning of Quantized LLMs[2] LoRA Learns Less and Forgets Less
Compare
What the evidence says about each option
| Option | Fits when | Watch for |
|---|---|---|
| LoRA, 16-bit base | The base fits; narrow changes such as format, tone or routines | A ceiling on how much new behaviour it learns |
| QLoRA | The 16-bit base does not fit | Probably slower steps (not measured in the paper) and rounding in the base; check your task |
| Full fine-tune | Large change, plenty of data and GPUs | Cost, and more forgetting of the base model |
- The QLoRA authors report that a 65-billion-parameter model can be fine-tuned on one 48 GB card.
- The LoRA-versus-full study compared both on programming and mathematics. It reports that LoRA usually underperformed full fine-tuning there, forgot less of the base abilities, and that the full update had a rank 10 to 100 times above typical LoRA settings.
- LoRA trades the size of change it can learn for memory and less forgetting.
Sources[2] LoRA Learns Less and Forgets Less[4] QLoRA: Efficient Finetuning of Quantized LLMs
Diagram
Merge it or keep it swappable
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[3] LoRA (PEFT package reference: LoraConfig and merging)
Code
Merging, tested
Python
model.merge_adapter() # fold in; keep the adapter weights
model.unmerge_adapter() # undo it
merged = model.merge_and_unload() # fold in and drop the adapter weights| Test (PEFT 0.21.2, random non-zero adapter) | Result |
|---|---|
Logits after merge_adapter() vs before | max difference 1.8e-6 (float32 noise) |
Logits after unmerge_adapter() vs before | max difference 1.2e-6 |
merge_and_unload() return type | the base model class, no adapter parameters |
The adapter wrapper after merge_and_unload() | no longer holds adapter parameters either |
- The PEFT reference says to use the returned model. The last row shows why: save the adapter files before you merge, because the wrapper does not keep them.
- The paper notes that after merging, batching inputs for different tasks with different adapters in one pass is not straightforward.
Sources[1] LoRA: Low-Rank Adaptation of Large Language Models[3] LoRA (PEFT package reference: LoraConfig and merging)
Worked example
Worked example: twelve tenants, one base
The made-up decoder, a rank-8 all-linear adapter per tenant, stored in 16-bit.
| Setup | Calculation | Storage |
|---|---|---|
| One shared 16-bit base | 1.233B×2 bytes | about 2.47 GB |
| One adapter | 7,569,408×2 bytes | about 15 MB |
| Twelve adapters on one base | 2.47 GB+12×15 MB | about 2.65 GB |
| Twelve merged copies | 12×2.47 GB | about 29.6 GB |
- Swapping wins on storage and on serving many tenants from one base. Merging wins when one adapter takes nearly all the traffic and latency matters most.
- If the base was 4-bit during training, fold the adapter into a 16-bit version of the base, then evaluate again. The merged model differs from the one you trained.
Check yourself
Check: choose the delivery
A product has one default adapter serving 95 percent of requests and three rarely used customer adapters. Latency matters most for the default. What do you merge and what do you keep separate? What do you re-run before launch?
Answer
Merge the default adapter into a 16-bit version of the base for the lowest latency, and keep the three rare adapters as small separate files that attach to an unmerged copy of the base. That costs a second base copy in storage and in serving memory, so if that is too much, keep all four adapters separate and accept the default’s small extra latency. Re-run the evaluation on the merged model and on each separate adapter, because the merged weights are not the ones you trained. Keep the saved adapter files as the rollback path.
Code
A first configuration, as code
Python
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)
# train, then keep the adapter or call model.merge_and_unload()| Test (PEFT 0.21.2) | Result |
|---|---|
Config accepted by get_peft_model on a small decoder | yes |
| Scale read from an adapted layer | 2.0 |
| Values here | examples for a first run, not defaults or recommendations |
- Write the config, the adapter parameter count and its state memory in the run note before you train.
Source[3] LoRA (PEFT package reference: LoraConfig and merging)
Summary
Recap
- LoRA learns
B @ A, which isr * (d + k)numbers instead ofd * k. The update has rank at mostr. Bstarts at zero withArandom: the model begins as the base and still gets a learning signal. Starting both at zero never moves.- The adapter is scaled by alpha over r. Change one of rank, alpha and learning rate at a time, and log all three.
- Count a model by summing r×(inputs+outputs) over every adapted matrix. Frozen weights cost storage only.
- Targets before rank: all linear layers first. Rank was nearly flat in the reported tests.
- QLoRA stores the base in NF4 with blocks of 64, quantises the constants again (overhead falls from 0.5 to 0.127 bits per parameter), and pages optimiser state. The multiply runs in 16-bit.
- Full fine-tuning can learn more on demanding domains; LoRA forgets less. Merge for one dominant adapter, swap for many.
References
References & Sources
LoRA: Low-Rank Adaptation of Large Language Models (opens in a new tab)
Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, et al.2022ICLR 2022Paper
arXiv 2106.09685 (opens in a new tab)https://iclr.cc/virtual/2022/poster/6319
Used for The low-rank update B times A, the Gaussian-A and zero-B start, the alpha over r scaling, the rank and target-matrix results on one large model, merging without extra latency, and the batching limitation.
LoRA Learns Less and Forgets Less (opens in a new tab)
Dan Biderman, Jacob Portes, Jose Javier Gonzalez Ortiz, Mansheej Paul, et al.2024TMLR 2024 (Featured Certification)Paper
arXiv 2405.09673 (opens in a new tab)https://openreview.net/forum?id=aloEru2qCG
Used for LoRA usually underperforming full fine-tuning on code and mathematics, forgetting less, and full-tune updates having a rank 10 to 100 times higher.
LoRA (PEFT package reference: LoraConfig and merging) (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/peft/package_reference/lora
Used for LoraConfig defaults, target_modules including all-linear, the no-op start, the rsLoRA scale, and merge_adapter, unmerge_adapter and merge_and_unload.
QLoRA: Efficient Finetuning of Quantized LLMs (opens in a new tab)
Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, Luke Zettlemoyer2023NeurIPS 2023Paper
arXiv 2305.14314 (opens in a new tab)https://proceedings.neurips.cc/paper_files/paper/2023/hash/1feb87871436031bdc0f2beaa62a049b-Abstract-Conference.html
Used for NF4, blocks of 64, double quantisation from 0.5 to 0.127 bits, paged optimisers, 16-bit compute, adapters on all linear layers, the learning rates used, and the 65B-on-48-GB result.
LoRA Without Regret (opens in a new tab)
John Schulman2025Article
https://thinkingmachines.ai/blog/lora/
Used for A later set of experiments recommending adapters on all layers and a learning rate near ten times the full fine-tuning rate.
Keys: ← → move, Home End first and last, F full screen.