LoRA freezes a language model and trains two thin matrices beside each weight. It trains 4.7M parameters where full fine-tuning trains 175,000M, matches its accuracy, and adds no inference latency.
Pick a method and watch the three bars move: parameters trained, accuracy, and extra latency. Then we build, piece by piece, why a tiny low-rank update is enough.
You need matrix multiplication, the idea of fine-tuning and the Transformer. We build the rest from zero. Paper: Hu, Shen, Wallis et al. (Microsoft), ICLR 2022.
Full fine-tuning trains every weight.
The numbers are the paper’s own for GPT-3 175B (the comparison table in Chapter 5): trainable parameters, WikiSQL accuracy, and the 20 to 30% inference latency of adapters. Nothing on this instrument is simulated.
Chapter 0
See why one full copy of a 175-billion-parameter model per task costs terabytes, and what a cheaper answer must look like
You have GPT-3 with 175 billion parameters. You want to fine-tune it for customer service chatbot, legal document review, and medical QA. The naive approach: make three copies of the full model and fine-tune each one.
The problem? Each copy is ~350 GB in float16. Three copies = 1.05 TB of GPU memory just for the weights. Plus optimizer states (2x for Adam), plus gradients, you're looking at ~4 TB total. This is economically and practically insane.
| Resource | Full Fine-Tuning (GPT-3) | Cost |
|---|---|---|
| Model weights | 175B × 2 bytes = 350 GB | Per task copy |
| Adam optimizer | 175B × 8 bytes = 1.4 TB | Per training run |
| Gradients | 175B × 2 bytes = 350 GB | Per training step |
| Total per task | ~2.1 TB | Per task |
| 3 tasks | ~6.3 TB + 3 separate training runs | Impractical |
Several approaches existed before LoRA:
| Method | Approach | Problem |
|---|---|---|
| Adapters (Houlsby 2019) | Insert small modules between layers | Adds inference latency (extra layers) |
| Prefix Tuning (Li 2021) | Prepend learnable tokens to keys/values | Reduces usable context length |
| Prompt Tuning (Lester 2021) | Learn soft prompts prepended to input | Hard to optimize, unstable |
LoRA's insight was different: don't add new layers or tokens. Instead, decompose the weight update itself into a low-rank form. This adds zero inference latency (the low-rank matrices can be merged into the original weights) and doesn't reduce context length.
Drag the model size. The two bars show the rough GPU memory needed to train, on one shared scale. Full fine-tuning climbs fast. LoRA climbs far more slowly.
Toy estimate, not the paper’s measurement: full fine-tuning is counted at 8 bytes per parameter, and LoRA at 2 bytes per parameter for the frozen weights plus 0.05 GB of adapters. For GPT-3 the paper’s own figures are in Chapter 5: about 1.2 TB against 350 GB.
Here is where each part of the instrument at the top is explained.
Chapter 1
Write the weight update as the product of two thin matrices, and see how few numbers it needs
During fine-tuning, each weight matrix W changes by some amount ΔW. Full fine-tuning learns ΔW directly, a dense matrix with the same dimensions as W. For GPT-3's attention layers, W is 12288 × 12288, so ΔW has 150 million entries. Per layer. Times 96 layers.
But Aghajanyan et al. (2021) showed something remarkable: the intrinsic dimensionality of fine-tuning is very low. When you project the weight updates into a random low-dimensional subspace, you can match 90% of full fine-tuning performance with only a few thousand trainable parameters. This means the actual "useful" information in ΔW is far lower-dimensional than its matrix size suggests.
Here's the key equation. Instead of:
LoRA computes:
Where W is frozen (no gradients), B is d × r (initialized to zeros), and A is r × d (initialized from a Gaussian). The product B·A has rank at most r, so the update is inherently low-rank.
python import torch import torch.nn as nn class LoRALinear(nn.Module): def __init__(self, original_linear, r=8, alpha=16): super().__init__() d_in = original_linear.in_features # e.g., 12288 d_out = original_linear.out_features # e.g., 12288 # Freeze the original weight self.W = original_linear self.W.weight.requires_grad = False # LoRA matrices — ONLY these are trained self.A = nn.Parameter(torch.randn(r, d_in) * 0.01) # [r, d_in] self.B = nn.Parameter(torch.zeros(d_out, r)) # [d_out, r] self.scaling = alpha / r # scaling factor def forward(self, x): # Original: W·x, shape [batch, seq, d_out] base = self.W(x) # LoRA: B·A·x, same shape lora = (x @ self.A.T) @ self.B.T * self.scaling return base + lora # h = Wx + BAx
The beauty of this design:
1. At training time: Only A and B receive gradients. W is frozen. Memory for optimizer states drops from O(d²) to O(2·d·r).
2. At inference time: You can merge: W' = W + B·A. The merged weight has exactly the same shape as the original, so there's zero additional latency. LoRA literally disappears at inference.
3. For multiple tasks: Store one base model + a tiny LoRA file per task. Swap LoRA modules to switch tasks. Each LoRA file is ~1-10 MB instead of 350 GB.
See a d×d weight update ΔW written as B (d×r) times A (r×d). Drag the rank slider and watch how few numbers B and A need. At rank 8 with d = 12,288, the compression ratio is 768×.
The matrices are drawn with a stand-in size of 64 so they fit on the screen. The counts below them use the real GPT-3 width, d = 12,288.
Chapter 2
Count the parameters exactly, set the scale alpha, and see why training starts from zero
Let's derive LoRA's parameter savings precisely and understand the scaling factor.
For a single weight matrix W ∈ Rd×d:
For GPT-3's attention weights (d = 12288, r = 8):
python d = 12288 # hidden dim r = 8 # LoRA rank full_params = d * d # 150,994,944 lora_params = 2 * d * r # 196,608 ratio = full_params / lora_params # 768× compression # Applied to all attention Wq and Wv across 96 layers: total_lora = 2 * lora_params * 96 # 37.7M params total_full = 175e9 # 175B params print(f"LoRA trains {total_lora/total_full*100:.4f}% of params") # LoRA trains 0.0215% of parameters → ~4650x reduction
LoRA introduces a hyperparameter α (alpha) that controls the magnitude of the update:
Why α/r and not just α?
When you change r, the magnitude of B·A changes (more columns in A means a larger product). Dividing by r normalizes this: the update magnitude stays roughly constant regardless of r. This means you can tune α once and then change r freely without retuning the learning rate.
LoRA initializes B to zeros and A from a Gaussian. This means at initialization, ΔW = B·A = 0, the model starts exactly as the pre-trained model. Training only moves the weights away from the pre-trained solution as needed.
This is crucial for stability: the model doesn't "forget" its pre-trained knowledge at the start of fine-tuning. It only learns the minimum necessary adaptation.
Only A and B receive gradients. The memory savings are substantial:
python # Memory comparison for Adam optimizer (2 states per param) d, r = 12288, 8 n_layers = 96 n_matrices = 2 # Wq and Wv # Full fine-tuning: Adam stores m and v for each param full_adam = 175e9 * 2 * 4 # 2 states × 4 bytes = 1.4 TB # LoRA: Adam only for A and B lora_adam = n_layers * n_matrices * 2 * d * r * 2 * 4 print(f"Full Adam: {full_adam/1e9:.0f} GB") # 1400 GB print(f"LoRA Adam: {lora_adam/1e6:.0f} MB") # 302 MB
Drag the sliders to change the model width and the LoRA rank. The calculator shows the exact parameter counts and the size of the adapter file.
Exact for one matrix (d² against 2dr). The number of layers is a rough guess, d / 128, so the totals are estimates. The file size counts 2 bytes per parameter (fp16).
Chapter 3
Pick which attention matrices get an adapter, and see why queries and values carry most of the gain
A Transformer has four types of weight matrices per attention layer: Wq, Wk, Wv, Wo (query, key, value, output projections). Plus the FFN's up and down projections. Where should you put LoRA?
Hu et al. ran ablations on GPT-3 175B:
| LoRA Applied To | Trainable Params | WikiSQL Acc | MNLI Acc |
|---|---|---|---|
| Wq only | 4.7M | 70.4% | 91.0% |
| Wv only | 4.7M | 73.0% | 91.2% |
| Wq + Wv | 9.4M | 73.4% | 91.5% |
| Wq + Wk + Wv + Wo | 18.8M | 73.7% | 91.4% |
The original LoRA paper focused on attention layers and didn't apply LoRA to FFN. Later work (QLoRA, LoRA+) found that including FFN gives small additional gains, especially for knowledge-intensive tasks. The FFN stores factual knowledge, so adapting it helps when the target task requires domain-specific facts not in the pre-training data.
Hu et al. used the same rank r for all layers, but subsequent work showed that different layers may benefit from different ranks. Lower layers (closer to input) tend to capture general linguistic features and need less adaptation. Upper layers (closer to output) are more task-specific and benefit from higher ranks.
python # Practical LoRA setup for a Transformer def add_lora(model, r=8, alpha=16, target_modules=['q_proj', 'v_proj']): """Add LoRA to specified attention projections.""" for name, module in model.named_modules(): if any(t in name for t in target_modules): if isinstance(module, nn.Linear): lora_module = LoRALinear(module, r=r, alpha=alpha) # Replace the original module parent = get_parent(model, name) setattr(parent, name.split('.')[-1], lora_module) # Freeze everything except LoRA parameters for n, p in model.named_parameters(): p.requires_grad = 'lora' in n # only LoRA params train
Switch the four attention matrices on and off. The panel shows the trainable parameter count and the WikiSQL accuracy. Wq + Wv gives the best accuracy for the parameters.
The four combinations in the lesson table (Wq, Wv, Wq + Wv, all four) use the paper’s numbers. Every other combination is a rough estimate and is marked as one.
Chapter 4
Slide the rank and find the point where extra parameters stop paying for themselves
The rank r is LoRA's most important hyperparameter. It controls the expressiveness of the adaptation, higher rank means more capacity to learn, but also more parameters and compute.
Hu et al. found that surprisingly low ranks work well:
| Rank | Params (Wq+Wv, 96 layers) | WikiSQL | MNLI |
|---|---|---|---|
| r = 1 | 2.4M | 68.8% | 90.7% |
| r = 4 | 4.7M | 72.6% | 91.3% |
| r = 8 | 9.4M | 73.4% | 91.5% |
| r = 64 | 75.5M | 73.7% | 91.3% |
| Full FT | 175,000M | 73.8% | 91.7% |
The weight update ΔW during fine-tuning is approximately low-rank because:
1. Task similarity: Most downstream tasks are related to the pre-training distribution (both involve language). The adaptation is a small perturbation, not a complete rewrite. Small perturbations tend to be low-rank.
2. Intrinsic dimensionality: Aghajanyan et al. showed that the intrinsic dimensionality of fine-tuning for GPT-3 is only ~200-1000 across all layers combined. Distributed across 192 matrices (2 per layer × 96 layers), that's only ~1-5 effective dimensions per matrix, consistent with r ≈ 4-8.
3. Redundancy in attention: Many attention heads learn similar patterns. The adaptation can often be expressed as changing a few "modes" of attention behavior, not independently modifying every head.
| Task Type | Recommended Rank | Reasoning |
|---|---|---|
| Classification (sentiment, NLI) | r = 4-8 | Simple output space, small adaptation |
| Summarization, translation | r = 8-16 | Moderate complexity |
| Code generation, math | r = 16-32 | Requires learning new "skills" |
| Domain transfer (medical, legal) | r = 32-64 | Significant distribution shift |
Drag the rank slider and see how accuracy changes. Most of the gain comes from the first few ranks. The cost is the trainable parameter count. Find where the curve goes flat.
The hollow dots are the paper’s measured WikiSQL scores at r = 1, 4, 8 and 64 (the table above). The curve between them is a straight-line interpolation on a log scale, not a measurement.
Chapter 5
Compare LoRA with full fine-tuning, adapters and prefix tuning on accuracy, size and latency
How does LoRA compare to other parameter-efficient methods and full fine-tuning? Hu et al. ran comprehensive comparisons on GPT-3 175B.
| Method | Trainable Params | WikiSQL | MNLI-m | SAMSum | Inference Latency |
|---|---|---|---|---|---|
| Full Fine-Tuning | 175,000M | 73.8% | 91.7% | 52.0 | Baseline |
| Adapter (Houlsby) | 7.1M | 71.9% | 90.5% | 53.2 | +20-30% |
| Prefix Tuning | 0.77M | 63.1% | 88.6% | 51.4 | Baseline |
| LoRA (r=8) | 4.7M | 73.4% | 91.5% | 53.8 | Baseline |
Beyond parameter count, LoRA saves substantial compute during training:
| Metric | Full FT | LoRA | Savings |
|---|---|---|---|
| Trainable params | 175B | 4.7M | 37,000x |
| GPU memory (training) | ~1.2 TB | ~350 GB | ~3.4x |
| Checkpoint size | 350 GB | ~35 MB | 10,000x |
| Task switching | Load full model | Swap LoRA file | Instant |
Note: GPU memory savings are "only" 3.4x (not 37,000x) because you still need to load the full model weights for the forward pass. The savings come from not storing optimizer states and gradients for the frozen weights.
LoRA also works well on encoder models. On RoBERTa-Base (125M params) with the GLUE benchmark:
| Method | Params | MRPC | SST-2 | QNLI |
|---|---|---|---|---|
| Full FT | 125M | 90.2 | 94.8 | 92.8 |
| Adapters | 0.3M | 89.5 | 94.0 | 91.5 |
| LoRA (r=8) | 0.3M | 90.0 | 95.1 | 93.3 |
On RoBERTa, LoRA actually exceeds full fine-tuning on some tasks (SST-2: 95.1 vs 94.8). This suggests that the low-rank constraint acts as a beneficial regularizer, preventing overfitting on small datasets.
Switch methods on and off. The chart shows accuracy against trainable parameters. LoRA is the only method with high accuracy, few parameters and no added latency.
WikiSQL accuracy and trainable parameters for GPT-3 175B, from the comparison table above. A dashed ring marks a method that adds inference latency.
Chapter 6
Turn the knobs of a real configuration, and swap adapters on one frozen base model
Time to see LoRA in action. This explorer lets you configure LoRA parameters and watch how they affect the weight update decomposition, parameter efficiency, and task performance.
Choose the model width, the rank and alpha. The panel shows the decomposition of one weight matrix, the parameter counts and the compression. The B and A blocks grow as you raise the rank.
Counts are exact for one d×d matrix. The blocks are drawn at a stand-in scale, not to the real proportions.
See how one base model serves several tasks by swapping LoRA modules. Pick a task to load its adapter. The base model (350 GB) stays in memory. Only the tiny adapter file (about 35 MB) changes. This is how production systems serve dozens of specialised models from one GPU.
Sizes are the lesson’s round numbers (350 GB base, about 35 MB per adapter). The task names are illustrative.
Chapter 7
Trace what LoRA built on, what grew from it, and why it changed who can fine-tune a model
LoRA sits at the intersection of parameter efficiency, matrix theory, and practical ML engineering. Its connections reveal both its intellectual roots and its enormous impact.
| Work | Contribution | Relationship to LoRA |
|---|---|---|
| Adapter Modules (Houlsby 2019) | First major PEFT method | LoRA avoids adapter's inference overhead |
| Intrinsic Dimensionality (Aghajanyan 2021) | Fine-tuning is low-dimensional | Theoretical justification for low-rank ΔW |
| Lottery Ticket Hypothesis (Frankle 2019) | Dense networks contain sparse subnetworks | Both exploit redundancy; LTH finds sparse masks, LoRA finds low-rank subspaces |
| Work | How It Extended LoRA |
|---|---|
| QLoRA (Dettmers 2023) | Quantize base model to 4-bit, apply LoRA on quantized weights → fine-tune 65B on single GPU |
| LoRA+ (Hayou 2024) | Different learning rates for A and B → better convergence |
| DoRA (Liu 2024) | Decompose W into magnitude and direction, apply LoRA to direction only |
| rsLoRA (Kalajdzievski 2024) | Fix scaling: use α/√r instead of α/r for better rank-independence |
| Hugging Face PEFT | Standard library making LoRA a one-line operation |
Before LoRA (2019-2021):
Fine-tuning = update all weights.
One GPU cluster per task.
Serving = separate model per task.
After LoRA (2022+):
Fine-tuning = train tiny adapters.
One consumer GPU per task.
Serving = one base + swap adapters.
As Leonardo da Vinci put it, “Simplicity is the ultimate sophistication.” And LoRA is as simple as W + BA.
LoRA freezes the pre-trained weights and trains a thin side path B·A next to each chosen matrix. The side path has rank r, so it holds 2dr numbers instead of d². Training starts from zero, so the model starts as the pre-trained one. After training, B·A merges into W and the adapter disappears.
| Number | Value | Where it came from |
|---|---|---|
| Compression of one matrix | 768× | d = 12,288, r = 8 (Chapter 2) |
| Trainable parameters, Wq + Wv, r = 8 | 9.4M of 175,000M | Rank table (Chapter 4) |
| WikiSQL accuracy | 73.4% against 73.8% | LoRA against full fine-tuning (Chapter 5) |
| Inference latency added | None | Adapters add 20 to 30% |
| Checkpoint per task | about 35 MB against 350 GB | Chapter 5 |
python# after training: fold the adapter into the frozen weight, once W_merged = W + (alpha / r) * (B @ A) # same shape as W, so zero extra latency # to switch tasks: subtract this adapter, add the next one W = W_merged - (alpha / r) * (B @ A) W = W + (alpha / r) * (B2 @ A2)
Read the earlier approach in Adapter Modules, and the sparse cousin in the Lottery Ticket Hypothesis.
Go back to the instrument at the top of the page and pick LoRA again. Then use Present to explain the idea out loud, or Teach to draw it on a whiteboard.