◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

LoRA and Parameter-Efficient Fine-Tuning

Fine-tune a huge model by freezing it and training a tiny add-on instead. LoRA learns each weight change as the product of two thin matrices, cutting trainable parameters by a factor of hundreds or thousands.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Fine-TuningEigenvectors and SVD

This leads to

Fine-Tuning an Open Model in Practice
The full path from zero — 45 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Tensors and Shapes
  15. Eigenvectors and SVD
  16. NumPy and Array Thinking
  17. Language Modeling and Next-Token Prediction
  18. Supervised Learning
  19. Linear Regression
  20. Training, Validation and Test Sets
  21. The Perceptron
  22. Logistic Regression
  23. Overfitting and the Bias–Variance Tradeoff
  24. Regularization: L1 and L2
  25. Neural Networks
  26. Recurrent Neural Networks
  27. Backpropagation
  28. Activation Functions
  29. Dropout and Regularizing Neural Networks
  30. PyTorch
  31. Vanishing and Exploding Gradients
  32. Normalization Layers: BatchNorm and LayerNorm
  33. Optimizers: SGD, Momentum and Adam
  34. LSTMs and GRUs
  35. Residual Connections
  36. Training Neural Networks in Practice
  37. Sequence-to-Sequence Models
  38. Transfer Learning
  39. Attention
  40. Self-Attention and Multi-Head Attention
  41. Positional Encodings
  42. The Transformer
  43. GPT and Decoder-Only Models
  44. Pretraining Large Language Models
  45. Fine-Tuning
  46. LoRA and Parameter-Efficient Fine-Tuning

Read them roughly in this order. See it on the concept map →

Why it matters

Full fine-tuning updates every weight of a model. For a 7-billion-parameter model that means about 112 GB of GPU memory for the weights, gradients and optimizer state, several high-end GPUs, and a fresh 14 GB copy of the model for every task you fine-tune it for. For a 70-billion-parameter model, multiply by ten.

Parameter-efficient fine-tuning (PEFT) is the family of methods that freeze the original model and train only a small number of new or selected parameters, usually well under 1% of the total. The results are often close to full fine-tuning, while:

  • Memory drops enough to fine-tune a 7B model on one consumer GPU, and with QLoRA a 65B model on a single 48 GB GPU.
  • Storage drops from gigabytes to megabytes per task. The LoRA paper reports shrinking a GPT-3 175B checkpoint from 350 GB to about 35 MB.
  • Serving gets flexible: one copy of the base model can host hundreds of small task-specific add-ons, swapped per request.

The most popular PEFT method by far is LoRA (low-rank adaptation). If you fine-tune an open model today, on Hugging Face, in a cloud fine-tuning service, or to make a custom image style for Stable Diffusion, you are very likely using LoRA or one of its descendants.

The intuition

Imagine a large, finished painting that you want to adjust for a new client: warmer light, a different mood. You could repaint every square centimetre. Or you could lay a thin transparent sheet over it and paint only the changes on that sheet. The original stays untouched; remove the sheet and it is back. Keep several sheets and you can switch between versions instantly.

LoRA is the transparent sheet. The pretrained weight matrix W0\mathbf{W}_0 stays frozen, and we learn a separate change ΔW\Delta\mathbf{W} that is added on top.

The second idea is what makes the sheet cheap. A weight matrix in a large model might be 4096×40964096 \times 4096, about 16.8 million numbers. A full ΔW\Delta\mathbf{W} would be just as big. But the change needed to adapt a model to one task seems to be simple: it lives in only a few directions. A matrix built from only a few directions is called low-rank, and it can be written as the product of two thin matrices that together hold far fewer numbers.

x input length d W₀ frozen d × d = 4096 × 4096 16.8 million numbers A r × d (r = 8) random start Ax only r numbers B d × r starts at 0 × α / r h output h = W₀x + (α/r)·B(Ax) trainable: A and B, 8 × 4096 + 4096 × 8 = 65,536 numbers (0.39% of W₀)
Fig. 1 LoRA: the frozen pretrained weight W₀ (a big square) is left alone. The update is the product of two thin trainable matrices, B (d × r) and A (r × d). The input x goes through both paths and the outputs are added.

Key idea LoRA freezes each weight matrix W0\mathbf{W}_0 and learns its change as ΔW=BA\Delta\mathbf{W} = \mathbf{B}\mathbf{A}, two thin matrices of rank rr. With r=8r = 8 on a 4096×40964096 \times 4096 layer that is 65,536 trainable numbers instead of 16.8 million, 256 times fewer.

How it works

Rank in one paragraph

The rank of a matrix is the number of independent directions it can produce: the number of linearly independent columns. A d×dd \times d matrix can have rank up to dd. A rank-1 matrix is the simplest kind: every row is a multiple of the same row. Any rank-1 matrix is a column vector times a row vector, and any rank-rr matrix is a d×rd \times r matrix times an r×dr \times d matrix. The singular value decomposition makes this precise: keeping the top rr singular values of any matrix gives the closest possible rank-rr approximation to it.

Here is a rank-1 example with real numbers. A column (1,2,0,−1)(1, 2, 0, -1) times a row (3,0,1,2)(3, 0, 1, 2):

(120−1)(3012)=(301260240000−30−1−2)\begin{pmatrix}1\\2\\0\\-1\end{pmatrix} \begin{pmatrix}3 & 0 & 1 & 2\end{pmatrix} = \begin{pmatrix}3 & 0 & 1 & 2\\ 6 & 0 & 2 & 4\\ 0 & 0 & 0 & 0\\ -3 & 0 & -1 & -2\end{pmatrix}

Sixteen numbers, described by eight. For a 4096×40964096 \times 4096 matrix of rank 8, the saving is far larger.

The LoRA update

A linear layer in a The Transformer computes h=W0x\mathbf{h} = \mathbf{W}_0 \mathbf{x}, where x\mathbf{x} is the input vector (length dind_{in}) and W0\mathbf{W}_0 is a dout×dind_{out} \times d_{in} weight matrix. LoRA replaces it with

h=W0x+αr BAx\mathbf{h} = \mathbf{W}_0 \mathbf{x} + \frac{\alpha}{r}\, \mathbf{B} \mathbf{A} \mathbf{x}

where:

  • W0\mathbf{W}_0 is frozen: it gets no gradient and never changes.
  • A\mathbf{A} is r×dinr \times d_{in} and B\mathbf{B} is dout×rd_{out} \times r. These are the only trainable weights.
  • rr is the rank, a small number you choose, typically 4 to 64.
  • α\alpha ("alpha") is a scaling constant. Dividing by rr means that when you change rr you don't have to retune the learning rate as much. A common choice is α=2r\alpha = 2r.

Two details make it work well:

  1. Initialisation. A\mathbf{A} starts with small random values and B\mathbf{B} starts at zero. So BA=0\mathbf{B}\mathbf{A} = 0 at the start and the model behaves exactly like the pretrained one. Training begins from the pretrained model, not from a random perturbation of it.
  2. Merging. After training you can compute W=W0+αrBA\mathbf{W} = \mathbf{W}_0 + \frac{\alpha}{r}\mathbf{B}\mathbf{A} once and use it as an ordinary weight matrix. The merged model is exactly as fast as the original. This is a real advantage over adapters, which add extra layers to every forward pass.

Note that BAx\mathbf{B}\mathbf{A}\mathbf{x} is computed as B(Ax)\mathbf{B}(\mathbf{A}\mathbf{x}): first squeeze x\mathbf{x} down to rr numbers, then expand back up. That is cheap.

The arithmetic for a real layer

Take Llama 2 7B, a widely used open model with hidden size d=4096d = 4096, 32 layers, and MLP inner size 11,008. One attention projection, say the query matrix Wq\mathbf{W}_q, is 4096×40964096 \times 4096:

Formula Parameters
Full Wq\mathbf{W}_q 4096×40964096 \times 4096 16,777,216
LoRA, r=8r = 8 8×4096+4096×88 \times 4096 + 4096 \times 8 65,536 (0.39%)
LoRA, r=64r = 64 64×4096+4096×6464 \times 4096 + 4096 \times 64 524,288 (3.1%)

Now apply LoRA with r=8r = 8 to every linear layer in every Transformer block. Each block has four attention projections (4096×40964096 \times 4096 each) and three MLP projections (two 4096→110084096 \to 11008 and one 11008→409611008 \to 4096):

  • Attention: 4×8×(4096+4096)=262,1444 \times 8 \times (4096 + 4096) = 262{,}144
  • MLP: 3×8×(4096+11008)=362,4963 \times 8 \times (4096 + 11008) = 362{,}496
  • Per block: 624,640624{,}640. Times 32 blocks: 19,988,480, about 20 million.

Against the model's roughly 6.74 billion parameters that is about 0.3%. The original LoRA paper went further and adapted only the query and value matrices: 2×32×65,536≈4.22 \times 32 \times 65{,}536 \approx 4.2 million, about 0.06%.

Memory follows. The frozen weights still have to sit on the GPU (14 GB in 16-bit), but gradients and Adam state are needed only for the 20 million LoRA parameters: about 20M×16 bytes≈0.320\text{M} \times 16 \text{ bytes} \approx 0.3 GB instead of 112 GB.

GPU memory to fine-tune a 7B model (before activations) Full fine-tuning16-bit weights + Adam ≈ 112 GB LoRA (r = 8)frozen 16-bit weights ≈ 14 GB + the LoRA matrices with their gradients and Adam state: ≈ 0.3 GB in both LoRA rows QLoRA (r = 8)frozen 4-bit weights ≈ 4 GB 0 20 40 60 80 100 120 gigabytes weights gradients Adam state + fp32 copy
Fig. 2 Rough GPU memory to fine-tune a 7-billion-parameter model, ignoring activations. Full fine-tuning needs about 112 GB, LoRA about 14 GB because the frozen weights dominate, and QLoRA about 4 GB because it stores those frozen weights in 4 bits.

Why does low rank work?

It isn't obvious that a rank-8 change could match a full fine-tune. The evidence is empirical. Before LoRA, Aghajanyan and colleagues (2020) showed that fine-tuning can be done well inside a surprisingly small random subspace of the weights, which they called a low intrinsic dimension. The LoRA authors then found that for GPT-3, even ranks 1 to 8 on the attention weights matched full fine-tuning on several benchmarks, and that the learned ΔW\Delta\mathbf{W} amplified directions that were already present but weak in W0\mathbf{W}_0. Fine-tuning mostly re-weights existing features rather than building new ones.

This also tells you when LoRA struggles: tasks that need lots of genuinely new knowledge or skill, such as a new language or heavy continued pretraining. Later studies found LoRA "learns less and forgets less" than full fine-tuning in those settings. Higher ranks and adapting every linear layer narrow the gap.

QLoRA: shrink the frozen part too

Once the trainable part is tiny, the frozen weights dominate memory. QLoRA (Dettmers et al., 2023) stores them in 4 bits instead of 16:

  • NF4 ("4-bit NormalFloat"), a 4-bit number format whose 16 levels are spaced to suit the roughly bell-shaped distribution of trained weights.
  • Double quantization: the scaling constants used by the quantization are themselves quantized, saving about another 0.4 bits per parameter.
  • Paged optimizers that spill optimizer state to CPU memory during spikes instead of crashing.

During the forward and backward pass each 4-bit weight block is converted back to 16-bit on the fly, and gradients flow through it into the 16-bit LoRA matrices. The paper fine-tuned a 65B model on one 48 GB GPU. See Quantization for how 4-bit formats work.

The rest of the PEFT family

  • Adapters (Houlsby et al., 2019) insert a small bottleneck MLP (shrink d→md \to m, nonlinearity, expand m→dm \to d, plus a residual connection) after the attention and MLP sublayers. They reached close to full fine-tuning on the GLUE benchmark while adding about 3.6% parameters per task, but they add a little latency at inference because they can't be merged away.
  • Prefix tuning (Li and Liang, 2021) learns a few vectors that are prepended to the keys and values in every attention layer, like a learned, invisible instruction.
  • Prompt tuning (Lester et al., 2021) is the simplest version: learn a few "soft prompt" embedding vectors added in front of the input only. It works well for very large models and poorly for small ones.
  • BitFit trains only the bias terms.
  • DoRA (2024) splits each weight into a length (magnitude) and a direction, and applies LoRA to the direction only.

LoRA won in practice because it is simple, has no inference overhead after merging, and works across model types.

In code

LoRA from scratch is about 20 lines. Here a "pretrained" 512×512512 \times 512 layer must adapt to a task whose ideal weights differ by a rank-4 change. We freeze the layer and train only A\mathbf{A} and B\mathbf{B}.

import torch, torch.nn as nn
torch.manual_seed(0)

class LoRALinear(nn.Module):
    """A frozen nn.Linear plus a trainable low-rank update (alpha/r) * B @ A."""
    def __init__(self, base: nn.Linear, r=4, alpha=8):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad = False                                   # freeze W0 and bias
        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: starts as a no-op
        self.scale = alpha / r

    def forward(self, x):
        return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale

    def merge(self):                                                  # fold BA into W0
        merged = nn.Linear(self.base.in_features, self.base.out_features)
        merged.weight.data = self.base.weight + self.scale * self.B @ self.A
        merged.bias.data = self.base.bias.clone()
        return merged

d = 512
pretrained = nn.Linear(d, d)
delta = torch.randn(d, 4) @ torch.randn(4, d) * 0.05                 # the change the task needs
x = torch.randn(4096, d)
with torch.no_grad():
    y = x @ (pretrained.weight + delta).T + pretrained.bias

layer = LoRALinear(pretrained, r=4, alpha=8)
trainable = sum(p.numel() for p in layer.parameters() if p.requires_grad)
total = sum(p.numel() for p in layer.parameters())
print(f"trainable {trainable:,} of {total:,} ({100*trainable/total:.2f}%)")

opt = torch.optim.Adam([layer.A, layer.B], lr=1e-2)
for step in range(201):
    loss = ((layer(x) - y) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 50 == 0:
        print(f"step {step:3d}  loss {loss.item():.5f}")

merged = layer.merge()
print("merged layer gives same output:", torch.allclose(merged(x), layer(x), atol=1e-4))

# trainable 4,096 of 266,752 (1.54%)
# step   0  loss 5.19241
# step  50  loss 0.06637
# step 100  loss 0.00044
# step 150  loss 0.00000
# step 200  loss 0.00000
# merged layer gives same output: True

With 1.5% of the parameters trainable, the layer learns the change exactly, because the change really is rank 4. Try r=2 and the loss stalls above zero: two directions can't express a rank-4 change.

In practice you use Hugging Face's PEFT library, which wraps the right layers of any model for you. This downloads a model, so it is not run here:

from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B")
config = LoraConfig(
    r=8, lora_alpha=16, lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],   # which linear layers get LoRA
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, config)
model.print_trainable_parameters()     # about 1.1M trainable of about 0.5B, roughly 0.2%
# ... train with the Trainer or TRL's SFTTrainer as usual ...
model.save_pretrained("my-lora")       # saves only the adapter: a few megabytes
merged = model.merge_and_unload()      # optional: fold LoRA into the base weights

For QLoRA, load the base model in 4 bits by passing quantization_config=BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16) to from_pretrained (this needs the bitsandbytes package and an NVIDIA GPU), then add LoRA the same way.

Common pitfalls

  • Rank too low for the task. r=8r = 8 is fine for style and format. For harder domain shifts try 32 to 128 and adapt all linear layers, not just attention.
  • Learning rate copied from full fine-tuning. LoRA usually wants a higher one, often around 10−410^{-4} to 2×10−42 \times 10^{-4}, because the update starts at zero and has few parameters.
  • Changing r without alpha. The effective step size depends on α/r\alpha / r. If you double rr, keep the ratio in mind.
  • Forgetting which base model an adapter belongs to. A LoRA adapter is only meaningful on the exact base weights it was trained on. Loading it on a different version silently gives garbage.
  • Merging into a quantized model. Folding a LoRA update into 4-bit weights loses precision. Merge into a 16-bit copy of the base model instead.

Watch out LoRA saves memory on gradients and optimizer state, not on activations. Long sequences and big batches can still run you out of memory. Use gradient checkpointing and smaller batches with gradient accumulation.

Variations

  • QLoRA: LoRA on a 4-bit base model, described above.
  • DoRA: separate magnitude and direction; LoRA on the direction.
  • LoRA+ and rsLoRA: tweaks to the learning rates of A\mathbf{A} and B\mathbf{B}, and to the α/r\alpha/r scaling for large ranks.
  • Multi-LoRA serving: serving systems such as vLLM can hold one base model and many adapters, applying the right one per request (Serving LLMs at Scale).
  • LoRA beyond text: the same trick fine-tunes diffusion image models on a handful of pictures of a person or style.
  • For when to fine-tune at all, and how to prepare data and evaluate, see Fine-Tuning an Open Model in Practice.

A bit of history

Adapters for NLP were introduced by Neil Houlsby and colleagues at Google in 2019, building on earlier adapter work in computer vision. In 2021 came a burst of alternatives: prefix tuning (Xiang Lisa Li and Percy Liang), prompt tuning (Brian Lester and colleagues) and, in June 2021, LoRA, from Edward Hu and colleagues at Microsoft, demonstrated on GPT-3. LoRA's simplicity and zero inference cost made it the default.

The open-model boom of 2023 made PEFT essential. When Meta's LLaMA weights became available, hobbyists used LoRA to make chat models on a single GPU, and in May 2023 QLoRA from Tim Dettmers and colleagues at the University of Washington pushed this to 65B models on one card. Hugging Face's PEFT library, released in early 2023, made all of these a few lines of code.

Try it

  1. In the from-scratch code, set r=2, then r=8. How does the final loss change? Explain using the rank of delta.
  2. Work out the number of LoRA parameters for Llama 2 7B with r=16r = 16 applied to all seven linear layers in all 32 blocks. What percentage of 6.74 billion is it?
  3. Harder: train full fine-tuning (unfreeze pretrained.weight) on the same data and compare the number of trainable parameters and the final loss.

Hint for 2: the count is linear in rr, so you can reuse the r=8r = 8 total.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. LoRA with rank r = 8 on a 4096 × 4096 weight matrix trains how many parameters for that matrix?

  2. Why is LoRA's matrix B initialised to zero?

  3. What advantage does LoRA have over classic adapter layers at inference time?

  4. In the from-scratch experiment the needed change is rank 4. You train LoRA with r = 2. What happens?

  5. You want to fine-tune a 65B model on a single 48 GB GPU. Which method makes that possible?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

PEFT documentation

Hugging Face · Intermediate · Free

The standard library for LoRA, QLoRA, prefix tuning, prompt tuning and other parameter-efficient methods, with conceptual guides and runnable examples.

Paper

QLoRA: Efficient Finetuning of Quantized LLMs

Dettmers et al. (University of Washington) · 2023 · Advanced · Free

LoRA on top of a 4-bit quantized frozen model, with the NF4 data type and paged optimizers. Made fine-tuning a 65B model possible on a single 48 GB GPU.

Book

Build a Large Language Model (From Scratch)

Sebastian Raschka · 2024 · Intermediate · code free, book paid

Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.

Paper

DoRA: Weight-Decomposed Low-Rank Adaptation

Liu et al. (NVIDIA) · 2024 · Advanced · Free

Splits each weight into a magnitude and a direction and applies LoRA to the direction only, often closing part of the gap to full fine-tuning.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/lora-and-peft.md