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
- Builds on
- 45 concepts →
- Quiz
- 5 questions ↓
This leads to
Fine-Tuning an Open Model in PracticeThe full path from zero — 45 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Eigenvectors and SVD
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Dropout and Regularizing Neural Networks
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Optimizers: SGD, Momentum and Adam
- LSTMs and GRUs
- Residual Connections
- Training Neural Networks in Practice
- Sequence-to-Sequence Models
- Transfer Learning
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Pretraining Large Language Models
- Fine-Tuning
- 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 stays frozen, and we learn a separate change that is added on top.
The second idea is what makes the sheet cheap. A weight matrix in a large model might be , about 16.8 million numbers. A full 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.
Key idea LoRA freezes each weight matrix and learns its change as , two thin matrices of rank . With on a 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 matrix can have rank up to . 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- matrix is a matrix times an matrix. The singular value decomposition makes this precise: keeping the top singular values of any matrix gives the closest possible rank- approximation to it.
Here is a rank-1 example with real numbers. A column times a row :
Sixteen numbers, described by eight. For a matrix of rank 8, the saving is far larger.
The LoRA update
A linear layer in a The Transformer computes , where is the input vector (length ) and is a weight matrix. LoRA replaces it with
where:
- is frozen: it gets no gradient and never changes.
- is and is . These are the only trainable weights.
- is the rank, a small number you choose, typically 4 to 64.
- ("alpha") is a scaling constant. Dividing by means that when you change you don't have to retune the learning rate as much. A common choice is .
Two details make it work well:
- Initialisation. starts with small random values and starts at zero. So 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.
- Merging. After training you can compute 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 is computed as : first squeeze down to 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 , 32 layers, and MLP inner size 11,008. One attention projection, say the query matrix , is :
| Formula | Parameters | |
|---|---|---|
| Full | 16,777,216 | |
| LoRA, | 65,536 (0.39%) | |
| LoRA, | 524,288 (3.1%) |
Now apply LoRA with to every linear layer in every Transformer block. Each block has four attention projections ( each) and three MLP projections (two and one ):
- Attention:
- MLP:
- Per block: . 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: 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 GB instead of 112 GB.
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 amplified directions that were already present but weak in . 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 , nonlinearity, expand , 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" layer must adapt to a task whose ideal weights differ by a rank-4 change. We freeze the layer and train only and .
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. 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 to , because the update starts at zero and has few parameters.
- Changing
rwithoutalpha. The effective step size depends on . If you double , 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 and , and to the 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
- In the from-scratch code, set
r=2, thenr=8. How does the final loss change? Explain using the rank ofdelta.- Work out the number of LoRA parameters for Llama 2 7B with applied to all seven linear layers in all 32 blocks. What percentage of 6.74 billion is it?
- 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 , so you can reuse the total.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
PEFT documentation
The standard library for LoRA, QLoRA, prefix tuning, prompt tuning and other parameter-efficient methods, with conceptual guides and runnable examples.
LoRA: Low-Rank Adaptation of Large Language Models
Fine-tuning by learning small low-rank updates instead of all weights.
QLoRA: Efficient Finetuning of Quantized LLMs
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.
Build a Large Language Model (From Scratch)
Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.
Parameter-Efficient Transfer Learning for NLP (adapters)
Introduced adapter layers: small bottleneck MLPs inserted into a frozen Transformer, so each new task trains only a few per cent of the parameters.
Prefix-Tuning: Optimizing Continuous Prompts for Generation
Freezes the model and learns a few trainable vectors prepended to the keys and values of every layer.
DoRA: Weight-Decomposed Low-Rank Adaptation
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