6.6Fine-tuning: LoRA & QLoRA
Adapt a billion-parameter model by training less than one percent of it. When to fine-tune, how low-rank adapters work, and how QLoRA fits it all on one GPU.
First: should you fine-tune at all?
Fine-tuningFine-tuningContinuing to train a pretrained model on a narrower dataset to specialize it. means continuing to train a pretrained model on your own examples. It is powerful, but it is the third tool to reach for, not the first. A rough ladder:
- Prompting (see prompting): instructions, examples and output formats. Minutes to iterate, nothing to train. Try this first, always.
- Retrieval (see RAG): when the model lacks knowledge, especially private, fresh or citable facts.
- Fine-tuning: when the model has the knowledge but not the behavior, and prompting can’t reliably get it there.
Good reasons to fine-tune include a consistent output format or style across millions of calls, a specialized task where a small fine-tuned model can match a big prompted one at a fraction of the cost and latency, a domain dialect (legal, medical, an internal DSL), or teaching a smaller model to imitate a larger one (distillation). Poor reasons include “teach it our product catalog”, which changes weekly and needs citations (use retrieval), or “make it smarter”, which fine-tuning on a few thousand examples won’t do.
Why full fine-tuning is expensive
Updating every weight with Adam means storing, for each parameter, the weight itself, its gradient and two optimizer statistics (see optimizers and mixed precision). A common mixed-precision rule of thumb is about 16 bytes per parameter before activations. For a 7-billion-parameter model that is roughly 112 GB, more than a single 80 GB GPU holds, and you also get a full 14 GB copy of the model for every task you fine-tune. LoRA attacks both problems.
Suppose you want to adapt a huge printed atlas for cyclists. Reprinting every page is the expensive way. Instead you lay a thin transparent sheet over each page and draw a few strokes: a bike lane here, a closed road there. The original atlas is untouched, the overlays are cheap to make, and you can keep a stack of them (cyclists, hikers, delivery drivers) for the same book.
The atlas is the frozen pretrained weights . The overlay is the LoRA adapter, and the rule that you may only draw a few broad strokes is its low rank . Swapping overlays is switching adapters, and printing an overlay permanently into a copy of the atlas is merging: , after which reading the map costs nothing extra.
LoRA: learn the change, not the weights
LoRA (Low-Rank Adaptation, Hu et al., 2021) starts from an empirical observation: the change a fine-tune makes to a weight matrix tends to be highly structured. Earlier work had found that fine-tuning can succeed even when restricted to a surprisingly small subspace of parameters. So instead of learning a full update, LoRA constrains it to be low-rankLow-rank matrixA matrix that can be written as the product of a tall thin matrix and a short wide one, so it carries far fewer independent numbers than its size suggests.:
- is frozen: no gradients, no optimizer state.
- Only and are trained: numbers instead of . For a matrix at that is 65,536 instead of 16.8 million, about 0.4%.
- starts at zero and starts random, so at the start of training. The adapted model begins exactly equal to the pretrained one, and training moves it away smoothly.
- is a constant scale. Dividing by keeps the update’s typical size from changing much when you try a different rank, so you don’t have to retune the learning rate each time.
In a forward pass, the layer computes : the input is squeezed down to numbers by , then expanded back by . That extra path is tiny next to .
Trained factors (taken from the best rank-4 fit below, learned at α = 16). ‖ΔW‖ = 7.70, exactly the fitted update. ΔW has rank ≤ 4 no matter how big d is. Blue = negative, orange = positive.
32 layers × 2 matrices × 2·4,096·4 = 2,097,152 trainable parameters, about 0.031% of the ~6.7 billion weights a full fine-tune would update (shape of Llama 2 7B).
The target has 5 strong directions plus noise. Its singular values (bars) drop sharply after the 5th, so error falls fast up to r = 5 and slowly after: the remaining rank only fits noise. By the Eckart–Young theorem, no rank-r matrix fits better than this truncated SVD.
Things to try:
- At initialization, is blank, so is zero and looks identical to . This is why LoRA training starts from the pretrained behavior rather than from a random perturbation.
- After training, change α. The pattern of stays the same while its strength scales. At inference, the scale is literally a dial on how strongly the adapter applies.
- Parameter counts. At , every step of adds 8,192 parameters per matrix. Even is under 1% of the full matrix.
- Fit the target. The target update has 5 strong directions plus noise. The error falls steeply up to , then flattens: extra rank only fits noise. Raise the noise and the curve flattens more; set it to zero and rank 5 is nearly perfect. Real fine-tuning updates seem to behave more like the low-noise case, which is why small ranks work.
Which matrices to adapt
The original paper adapted only the attention projections, mainly and , and found this worked well for GPT-3. Later practice, reinforced by the QLoRA paper, usually adapts all linear layers (attention projections and the MLP), which tends to match full fine-tuning more closely for little extra cost. Typical ranks are 8 to 64. If quality saturates at low rank, your task is “small”; if it keeps improving with rank, the task needs a richer update, or full fine-tuning.
Merging and serving adapters
Because is just a matrix of the same shape as , after training you can compute once and merge it: the result is an ordinary model with zero added latency. Alternatively, keep adapters separate: one base model in GPU memory can serve many tasks or customers by applying a different small adapter per request, and an adapter file of a few to a few hundred megabytes is cheap to store and ship.
QLoRA: fine-tuning a quantized model
LoRA removes the gradient and optimizer costs for , but the frozen weights still have to sit in GPU memory, 2 bytes per parameter in BF16. QLoRA (Dettmers et al., 2023) shrinks that too: the frozen base model is stored in 4-bit precision while the LoRA adapters train in 16-bit. Gradients flow through the dequantized 4-bit weights into the adapters; the base never changes. Three ingredients made it work without losing quality:
- NF4NF4 (4-bit NormalFloat)The 4-bit data type introduced by QLoRA, whose 16 levels are placed at quantiles of a normal distribution to suit normally distributed weights. (4-bit NormalFloat). Pretrained weights are roughly normally distributed. NF4 places its 16 levels at quantiles of a normal distribution, so each level is used about equally often, after scaling each small block of weights (64 in the paper) by its largest absolute value. See quantization for the general idea.
- Double quantization. Each block’s scale factor is itself a number to store. Quantizing those constants too saves roughly a third of a bit per parameter, which matters at tens of billions of parameters.
- Paged optimizers. Optimizer state can be paged between GPU and CPU memory, smoothing out the memory spikes that would otherwise crash a run on long sequences.
The headline result: a 65-billion-parameter model fine-tuned on a single 48 GB GPU, with quality matching 16-bit full fine-tuning on the paper’s benchmarks.
DoRA, briefly
DoRA (Weight-Decomposed Low-Rank Adaptation, Liu et al., 2024) splits each weight matrix into a magnitude (the length of each column) and a direction, applies LoRA to the direction only, and trains the magnitudes directly. The authors argue this mimics how full fine-tuning changes weights more closely and report consistent gains over LoRA at the same rank. Like LoRA, it can be merged after training.
A practical recipe
Most successful LoRA runs look similar. Start with a few hundred to a few thousand high-quality examples in exactly the format you’ll use at inference, including the chat template (see SFT); quality and consistency matter far more than volume. Adapt all linear layers at a modest rank (8–32) with around to . Use a learning rate roughly an order of magnitude higher than you would for full fine-tuning (around is a common starting point), since the adapters start from zero and must move quickly. Train for a small number of epochs and watch a held-out set: with tiny datasets, adapters overfit fast. Finally, evaluate against the un-tuned model with a good prompt on your own test set (see evaluation). If the fine-tune doesn’t clearly win, the prompt was the better tool.
MATH CORNER · optionalThe low-rank forward pass and the memory arithmetic
Forward pass. For input :
Computing costs multiply-adds and costs , versus for . Gradients are needed only for and :
At initialization , so but : moves first, and starts learning once is nonzero.
Worked example with , , :
The second row of is exactly twice the first, so has rank 1. For : , , , so .
Memory for a 7B-class model (32 layers, ), ignoring activations:
| setup | frozen weights | trainable params | weights + grads + Adam for trainable (≈16 B/param) | total |
|---|---|---|---|---|
| full fine-tune | — | 6.7 B | ≈ 108 GB | ≈ 108 GB |
| LoRA, BF16 base, , | 13.5 GB | 16.8 M | ≈ 0.27 GB | ≈ 14 GB |
| QLoRA, NF4 base, same adapters | ≈ 3.5 GB | 16.8 M | ≈ 0.27 GB | ≈ 4 GB |
The trainable count is . The NF4 estimate is 0.5 bytes per parameter plus a little for the block scales.
In code
A LoRA layer from scratch is a dozen lines; in practice you’d use Hugging Face PEFT, shown below it.
import torch, torch.nn as nn
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r=8, alpha=16):
super().__init__()
self.base = base.requires_grad_(False) # freeze W
self.A = nn.Parameter(torch.randn(r, base.in_features) / base.in_features**0.5)
self.B = nn.Parameter(torch.zeros(base.out_features, r)) # zero init: ΔW = 0
self.scale = alpha / r
def forward(self, x):
return self.base(x) + self.scale * (x @ self.A.T) @ self.B.T
# With PEFT + bitsandbytes (QLoRA):
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, quantization_config=bnb)
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM"))
model.print_trainable_parameters() # well under 1% trainable
- “LoRA makes training much faster per step.” It slashes memory and checkpoint size, but each step still runs the full model forward and backward. The speedups come mostly from fitting on fewer or smaller GPUs and larger batches.
- “A LoRA adapter adds inference latency.” Only if you keep it separate. Merged into , the adapted model has exactly the original architecture and speed.
- “Higher rank is always better.” Past the task’s effective rank, extra capacity mostly fits noise, as the demo’s error curve shows. Many tasks saturate at small ranks.
- “QLoRA produces a 4-bit fine-tuned model.” The base is stored in 4-bit during training, but the adapters are 16-bit. After training you can merge into a 16-bit copy of the base or keep the adapter alongside the quantized base.
- “Fine-tuning is the way to add new facts.” It can, unreliably, and the facts then go stale. Retrieval is usually the better tool for knowledge; fine-tuning shines for behavior, format and style.
Check your understanding
Q1.Why is LoRA's B matrix initialized to zero?
Q2.For a 4096 × 4096 weight matrix and rank r = 8, how many parameters does LoRA train for that matrix?
Q3.What does QLoRA store in 4-bit NF4?
Q4.In the demo, the target update has 5 strong directions plus noise. Why does the error curve flatten after rank 5?
Q5.Your team needs the model to answer questions about a product catalog that changes weekly, with sources. What's the best first approach?
Further reading
- paperLoRA: Low-Rank Adaptation of Large Language Models — Hu et al., 2021: the original method and its GPT-3 experiments.
- paperQLoRA: Efficient Finetuning of Quantized LLMs — Dettmers et al., 2023: NF4, double quantization and paged optimizers.
- paperDoRA: Weight-Decomposed Low-Rank Adaptation — Magnitude/direction decomposition on top of LoRA.
- paperLoRA Learns Less and Forgets Less — Biderman et al., 2024: a careful LoRA vs full fine-tuning comparison.
- paperIntrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning — Aghajanyan et al.: the low-dimensional view that motivated LoRA.
- docsPEFT documentation — Hugging Face's library for LoRA, QLoRA, DoRA and other adapters.