Skip to content
LearnAI
PART 6 · USING LLMS IN PRACTICE/ Adapting & evaluating

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.

⏱ 13 minAdvanced

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:

  1. Prompting (see prompting): instructions, examples and output formats. Minutes to iterate, nothing to train. Try this first, always.
  2. Retrieval (see RAG): when the model lacks knowledge, especially private, fresh or citable facts.
  3. 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.

ANALOGY· A transparent overlay on a printed atlas

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 WW. The overlay is the LoRA adapter, and the rule that you may only draw a few broad strokes is its low rank rr. Swapping overlays is switching adapters, and printing an overlay permanently into a copy of the atlas is merging: W′=W+ΔWW' = W + \Delta W, 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 d×kd \times k 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.:

W′=W+αr BA,B∈Rd×r,  A∈Rr×k,  r≪min⁡(d,k).W' = W + \frac{\alpha}{r}\, B A, \qquad B \in \mathbb{R}^{d \times r},\; A \in \mathbb{R}^{r \times k},\; r \ll \min(d, k).
  • WW is frozen: no gradients, no optimizer state.
  • Only BB and AA are trained: r(d+k)r(d + k) numbers instead of dkdk. For a 4096×40964096 \times 4096 matrix at r=8r = 8 that is 65,536 instead of 16.8 million, about 0.4%.
  • BB starts at zero and AA starts random, so BA=0BA = 0 at the start of training. The adapted model begins exactly equal to the pretrained one, and training moves it away smoothly.
  • α\alpha is a constant scale. Dividing by rr 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 Wx+αrB(Ax)Wx + \frac{\alpha}{r}B(Ax): the input is squeezed down to rr numbers by AA, then expanded back by BB. That extra path is tiny next to WxWx.

INTERACTIVELoRA visualizer
Adapter
W (frozen) 24×24
α/r = 4.00
B 24×4
A 4×24
ΔW = (α/r)·B·A
W′ = W + ΔW

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.

Trainable parameters at rank r = 4
Matrix size d×d
full update d²
16,777,216
LoRA 2·d·r
32,768
LoRA / full
0.20%
Whole 7B-class model (32 layers, d = 4,096), adapt

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).

Fit a target update with rank r (truncated SVD via power iteration)
rank 4: relative error 30.1%
target ΔW
best rank-4 fit
residual
singular values σ₁…σ₁₆
100%0116rank rrank 1: 68.1% errorrank 2: 47.9% errorrank 3: 35.9% errorrank 4: 30.1% errorrank 5: 26.9% errorrank 6: 24.6% errorrank 7: 22.5% errorrank 8: 20.5% errorrank 9: 18.4% errorrank 10: 16.3% errorrank 11: 14.5% errorrank 12: 12.7% errorrank 13: 11.0% errorrank 14: 9.5% errorrank 15: 8.0% errorrank 16: 6.5% error
‖ΔW − fit‖ / ‖ΔW‖ vs rank

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.

Top: a 24×24 weight matrix W plus a low-rank update. Switch between initialization (B = 0) and trained factors, and change r and α. Middle: parameter counts at real-model scale. Bottom: approximate a target update with the best rank-r matrix and watch the error curve.

Things to try:

  1. At initialization, BB is blank, so ΔW\Delta W is zero and W′W' looks identical to WW. This is why LoRA training starts from the pretrained behavior rather than from a random perturbation.
  2. After training, change α. The pattern of ΔW\Delta W stays the same while its strength scales. At inference, the scale is literally a dial on how strongly the adapter applies.
  3. Parameter counts. At d=4096d = 4096, every step of rr adds 8,192 parameters per matrix. Even r=16r = 16 is under 1% of the full matrix.
  4. Fit the target. The target update has 5 strong directions plus noise. The error falls steeply up to r=5r = 5, 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 WqW_q and WvW_v, 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 ΔW\Delta W is just a matrix of the same shape as WW, after training you can compute W′=W+αrBAW' = W + \frac{\alpha}{r}BA 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 WW, 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:

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 α\alpha around rr to 2r2r. Use a learning rate roughly an order of magnitude higher than you would for full fine-tuning (around 10−410^{-4} 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 x∈Rkx \in \mathbb{R}^{k}:

h=W′x=Wx+αr B (Ax).h = W'x = Wx + \frac{\alpha}{r}\,B\,(A x).

Computing AxAx costs rkrk multiply-adds and B(Ax)B(Ax) costs drdr, versus dkdk for WxWx. Gradients are needed only for AA and BB:

∂L∂B=αr ∂L∂h (Ax)⊤,∂L∂A=αr B⊤∂L∂h x⊤.\frac{\partial L}{\partial B} = \frac{\alpha}{r}\,\frac{\partial L}{\partial h}\,(Ax)^\top, \qquad \frac{\partial L}{\partial A} = \frac{\alpha}{r}\,B^\top \frac{\partial L}{\partial h}\,x^\top .

At initialization B=0B = 0, so ∂L/∂A=0\partial L/\partial A = 0 but ∂L/∂B≠0\partial L/\partial B \neq 0: BB moves first, and AA starts learning once BB is nonzero.

Worked example with d=k=2d = k = 2, r=1r = 1, α=1\alpha = 1:

W=(1001),B=(0.51),A=(2−1),BA=(1−0.52−1).W = \begin{pmatrix}1&0\\0&1\end{pmatrix},\quad B = \begin{pmatrix}0.5\\1\end{pmatrix},\quad A = \begin{pmatrix}2 & -1\end{pmatrix},\quad BA = \begin{pmatrix}1&-0.5\\2&-1\end{pmatrix}.

The second row of BABA is exactly twice the first, so BABA has rank 1. For x=(1,1)x = (1, 1): Wx=(1,1)Wx = (1, 1), Ax=2−1=1Ax = 2 - 1 = 1, B(Ax)=(0.5,1)B(Ax) = (0.5, 1), so h=(1.5,2)h = (1.5, 2).

Memory for a 7B-class model (32 layers, d=4096d = 4096), ignoring activations:

setupfrozen weightstrainable paramsweights + grads + Adam for trainable (≈16 B/param)total
full fine-tune—6.7 B≈ 108 GB≈ 108 GB
LoRA, BF16 base, r=16r=16, Wq,k,v,oW_{q,k,v,o}13.5 GB16.8 M≈ 0.27 GB≈ 14 GB
QLoRA, NF4 base, same adapters≈ 3.5 GB16.8 M≈ 0.27 GB≈ 4 GB

The trainable count is 32×4×2⋅4096⋅16=16,777,21632 \times 4 \times 2 \cdot 4096 \cdot 16 = 16{,}777{,}216. 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
COMMON MISCONCEPTIONS
  • “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 WW, 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

0/5 answered
  1. Q1.Why is LoRA's B matrix initialized to zero?

  2. Q2.For a 4096 × 4096 weight matrix and rank r = 8, how many parameters does LoRA train for that matrix?

  3. Q3.What does QLoRA store in 4-bit NF4?

  4. Q4.In the demo, the target update has 5 strong directions plus noise. Why does the error curve flatten after rank 5?

  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

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.