Sub topic 3
The low-rank idea behind LoRA
This chapter assumes you know matrix multiplication and matrix rank, and that you have run a Hugging Face transformers model for inference. It explains the one assumption that makes LoRA work: the change that fine-tuning makes to a weight matrix can be described with far fewer numbers than the matrix has. The next chapter turns this into the exact update formula.
The problem this idea solves
Full fine-tuning treats every weight as trainable. For a linear layer with weight matrix W of shape d_out x d_in, training produces a new matrix W'. You can write that as the original plus a difference:
W' = W + ΔWΔW has the same shape as W, so it has d_out * d_in entries. A layer with d_out = d_in = 4096 has 16,777,216 of them. Storing one ΔW per layer is as large as storing the model again, and training it needs gradients and optimizer state for every entry.
LoRA (Low-Rank Adaptation, Hu et al., 2021) asks whether ΔW really needs all those degrees of freedom. If it doesn't, you can train a compact description of ΔW and leave W untouched.
Rank in one paragraph
The rank of a matrix is the number of linearly independent rows (equivalently, columns) it has. A rank-1 matrix is an outer product of one column vector and one row vector, so every row is a multiple of the same direction. A matrix with rank r is a sum of r such outer products.
This gives a factorization. If ΔW has rank at most r, it can be written as a product of two thin matrices:
ΔW = B @ A
B: d_out x r
A: r x d_inThe factors hold r * (d_out + d_in) numbers in total. For d_out = d_in = 4096 and r = 8, that is 65,536 numbers instead of 16,777,216, a factor of 256.
The hypothesis
Two observations motivate the bet that adaptation updates are low rank:
- Aghajanyan et al. (2020) showed that large pretrained models can be fine-tuned well inside a random subspace of very small dimension. This suggests fine-tuning has a low "intrinsic dimension".
- Hu et al. (2021) hypothesized that the weight updates during adaptation also have a low intrinsic rank, and showed that ranks as small as 1 to 8 matched full fine-tuning on several benchmarks.
The intuition is that pretraining already learned general features. Adapting to a task, such as a response style or a domain vocabulary, mostly re-weights directions that already exist. It does not need to rebuild the whole matrix.
This is a hypothesis, not a theorem. It holds well for style, format and narrow-task adaptation, and less well when you want to teach large amounts of new knowledge or a very different skill. You will see the consequences of that when you choose a rank in the next chapters.
Seeing low rank numerically
The following script builds a matrix that is exactly rank 8, then shows that a truncated SVD (singular value decomposition) recovers it from only 8 components. It then adds small noise to mimic a real update that is only approximately low rank.
import torch
torch.manual_seed(0)
d_out, d_in, r = 512, 512, 8
# An exactly rank-8 "update": product of two thin matrices.
B = torch.randn(d_out, r)
A = torch.randn(r, d_in)
delta = B @ A
print("rank of delta:", torch.linalg.matrix_rank(delta).item())
print("full entries:", delta.numel())
print("factor entries:", A.numel() + B.numel())
# A realistic update: low-rank structure plus small noise.
noisy = delta + 0.05 * torch.randn(d_out, d_in)
U, S, Vh = torch.linalg.svd(noisy)
for k in [1, 4, 8, 32, 128]:
approx = (U[:, :k] * S[:k]) @ Vh[:k]
rel_err = torch.linalg.norm(noisy - approx) / torch.linalg.norm(noisy)
print(f"k={k:>3} relative error={rel_err.item():.4f}")Expected behavior: the rank prints as 8, and the factors hold 8,192 numbers against 262,144 for the full matrix. The approximation error falls steeply until k = 8. After that it falls slowly, because the remaining singular values only encode noise. A curve with a sharp knee like this is what a low-rank update looks like. In LoRA you never compute an SVD of a real update, but the knee is the reason a small r can capture most of the change.
How LoRA uses the factorization
LoRA does not first learn ΔW and then factor it. It parameterizes ΔW as B @ A from the start and trains A and B directly. The pretrained W stays frozen. The forward pass adds the two paths:
h = W x + B (A x)Order matters for cost. A x first shrinks the input to r dimensions, then B expands it back to d_out. Nothing ever forms the full d_out x d_in matrix B @ A during training.
What you save
Three costs shrink, and they shrink by different amounts.
| Cost | Full fine-tuning | LoRA |
|---|---|---|
| Trainable parameters | all of `W` | `r * (d_out + d_in)` per adapted layer |
| Gradients and optimizer state | for every weight | only for `A` and `B` |
| Saved checkpoint | a full copy of the model | only `A` and `B` |
| Forward pass compute | one matmul per layer | one matmul plus two small ones |
| Base model weights in memory | needed | still needed |
The last two rows are the ones people forget. The frozen base model still has to sit in GPU memory, and the extra small matmuls add a little latency unless you merge the adapter later. Activations for backpropagation also remain. LoRA cuts optimizer and gradient memory, which is usually the largest part, but it does not make a 7B model fit on a small GPU by itself. That is the job of quantization, covered in a later chapter.
You can count the parameters of a single layer directly:
d_out = d_in = 4096
r = 8
full = d_out * d_in
lora = r * (d_out + d_in)
print(f"full: {full:,}")
print(f"lora: {lora:,}")
print(f"ratio: {full // lora}x smaller")This prints 16,777,216 for the full layer, 65,536 for LoRA, and a ratio of 256x.
Rank of the update versus rank of the weights
A frequent misunderstanding is that LoRA makes the model low rank. It does not. The constraint applies only to the update:
rank(B @ A) <= r, because the rank of a product is at most the smaller rank of its factors.W + B @ Acan still be full rank. A full-rankWplus a rank-8 matrix is generally full rank.
So the adapted layer keeps its full representational capacity from pretraining. LoRA only limits how far the layer can move in one adaptation. In effect, the update is confined to an r-dimensional subspace of input directions and an r-dimensional subspace of output directions.
Common errors in thinking about it
- Believing a higher rank is always better. Rank raises capacity, but also the parameter count and the risk of overfitting a small dataset. Returns diminish quickly once
rexceeds the true rank of the update. - Believing the adapter changes the model's size. The adapter is small on disk, but after merging, the model is the same size as the base.
- Adapting only one layer type and expecting full coverage. The factorization is per matrix. Which matrices receive an adapter is a separate choice, and it affects quality as much as rank does.
- Forgetting that
AandBneed compatible shapes.Bisd_out x randAisr x d_in. Swapping them gives a shape error in the forward pass, or silently wrong behavior if the layer is square. - Assuming low rank is guaranteed for your task. If training loss plateaus well above what full fine-tuning reaches, the update may need more rank, more adapted layers, or full fine-tuning.
Key points
- Fine-tuning can be written as
W' = W + ΔW, and LoRA assumesΔWhas low rank. - A rank-
rupdate factors intoB(d_out x r) andA(r x d_in), which needsr * (d_out + d_in)numbers instead ofd_out * d_in. - LoRA trains
AandBdirectly and keepsWfrozen, adding the two paths in the forward pass. - The update is constrained to rank at most
r, but the adapted weightW + B @ Ais not. - The assumption is empirical. It works well for style and task adaptation, and can fall short for large knowledge changes.
Exercise
A layer has din = 2048 and dout = 8192. You adapt it with LoRA at r = 16. How many trainable parameters does the adapter add, and how many times smaller is that than training the full weight matrix? Also, can W + B @ A be full rank?
Show answer
The adapter has r (dout + din) = 16 (8192 + 2048) = 163,840 parameters. The full matrix has 2048 * 8192 = 16,777,216 entries, so the adapter is about 102 times smaller (16,777,216 / 163,840 = 102.4). Yes, W + B @ A can be full rank. Only the update B @ A is limited to rank at most 16, while the sum with a full-rank W is generally full rank.
Exercise
Modify the SVD script so the true update has rank 32 instead of 8. At which value of k in your list do you expect the error curve to stop falling steeply, and what does that imply about choosing r?
Show answer
The error should stop falling steeply at about k = 32, where the list includes k = 32. Below that, components still carry real structure. Beyond it, they carry only noise. This implies that r should be near the true rank of the update. A much smaller r loses structure and a much larger r adds parameters without capturing more of the update.