Low-Rank Approximation: Compression and LoRA
Many large matrices are "almost" low rank: a few directions carry most of the information. The SVD finds the best low-rank approximation with a provable error, and the same idea, applied to the changes of a neural network's weights, is LoRA, the standard way to fine-tune large language models cheaply.
Rank- matrices are cheap
A matrix of rank can be written as a product of an and a matrix (or as a sum of outer products ). Storing and multiplying it then costs instead of :
| full | rank 8 | ratio | |
|---|---|---|---|
| 1,000,000 | 16,000 | 1.6% | |
| 16,777,216 | 65,536 | 0.39% |
Multiplying a vector by instead of also drops the cost from to .
The Eckart–Young theorem
Write the SVD as and let (keep the largest singular values).
Theorem (Eckart–Young–Mirsky). Among all matrices of rank at most ,
So truncating the SVD is optimal in both the operator norm and the Frobenius norm (inner products on matrices), and the error is read straight off the discarded singular values. The relative "energy" kept is .
Proof idea (operator norm). If , its null space has dimension , so it meets the -dimensional span of in some unit vector . Then , and for any unit in that span.
import numpy as np
rng = np.random.default_rng(0)
# a 60x40 matrix that is "almost" rank 3: three strong directions plus small noise
A = rng.normal(size=(60, 3)) @ rng.normal(size=(3, 40)) + 0.1 * rng.normal(size=(60, 40))
U, s, Vt = np.linalg.svd(A, full_matrices=False)
print("singular values:", np.round(s[:6], 3), "...")
for k in (1, 2, 3, 4):
Ak = U[:, :k] * s[:k] @ Vt[:k]
e2, eF = np.linalg.norm(A - Ak, 2), np.linalg.norm(A - Ak)
print(f"k={k}: ||A-Ak||_2 = {e2:7.3f} (sigma_{k+1} = {s[k]:7.3f}) "
f"||A-Ak||_F = {eF:7.3f} (formula {np.sqrt(np.sum(s[k:]**2)):7.3f})")
B = rng.normal(size=(60, 3)) @ rng.normal(size=(3, 40)) # some other rank-3 matrix
print("random rank-3 error:", round(float(np.linalg.norm(A - B)), 3))singular values: [58.852 47.749 44.916 1.373 1.339 1.239] ...
k=1: ||A-Ak||_2 = 47.749 (sigma_2 = 47.749) ||A-Ak||_F = 65.715 (formula 65.715)
k=2: ||A-Ak||_2 = 44.916 (sigma_3 = 44.916) ||A-Ak||_F = 45.151 (formula 45.151)
k=3: ||A-Ak||_2 = 1.373 (sigma_4 = 1.373) ||A-Ak||_F = 4.598 (formula 4.598)
k=4: ||A-Ak||_2 = 1.339 (sigma_5 = 1.339) ||A-Ak||_F = 4.388 (formula 4.388)
random rank-3 error: 118.043
The sharp drop after reveals the true rank; everything after it is noise. Choosing at such an "elbow" is the standard way to pick a rank.
LoRA: low-rank adaptation
Fine-tuning a large model normally updates every weight matrix (), which means storing a full copy of the model per task and optimizer state for billions of parameters. LoRA (Low-Rank Adaptation, Hu et al., 2021) freezes and learns only a low-rank change:
- starts at 0 (and random), so and training starts exactly at the pretrained model.
- Trainable parameters per matrix: instead of .
- After training, can be merged into (no extra inference cost), or kept separate so one base model serves many small adapters.
- It works because the useful update directions for a new task turn out to be close to low rank, which is the Eckart–Young intuition applied to .
d = k = 4096 # one attention projection in a 7B-class model
for r in (4, 8, 16, 64):
lora = r * (d + k)
print(f"r={r:3d}: LoRA params {lora:>9,} vs full {d * k:,} -> {lora / (d * k):.2%}")
layers, mats = 32, 4 # e.g. adapt Q, K, V and O projections in 32 layers
print(f"whole model, r=8: {layers * mats * 8 * (d + k):,} trainable parameters")r= 4: LoRA params 32,768 vs full 16,777,216 -> 0.20%
r= 8: LoRA params 65,536 vs full 16,777,216 -> 0.39%
r= 16: LoRA params 131,072 vs full 16,777,216 -> 0.78%
r= 64: LoRA params 524,288 vs full 16,777,216 -> 3.12%
whole model, r=8: 8,388,608 trainable parameters
A tiny demo: a frozen linear layer has to learn a task whose ideal weights are with rank 2. We train only and (rank 2) by gradient descent, using the backward-pass formulas from Neural Network Layers:
import numpy as np
rng = np.random.default_rng(1)
d, k, r, n = 20, 30, 2, 400
W0 = rng.normal(size=(d, k)) / np.sqrt(k) # "pretrained", frozen
dW_true = rng.normal(size=(d, r)) @ rng.normal(size=(r, k)) / k # the task needs this change
X = rng.normal(size=(n, k)); Y = X @ (W0 + dW_true).T
B = np.zeros((d, r)); A = rng.normal(size=(r, k)) * 0.1 # LoRA init: B = 0
lr = 0.05
for step in range(301):
P = X @ (W0 + B @ A).T
G = (P - Y) / n # dL/dP for L = mean over samples of 0.5*|p - y|^2
gW = G.T @ X # gradient w.r.t. the full update ΔW
gB, gA = gW @ A.T, B.T @ gW # chain rule through ΔW = B A
B -= lr * gB; A -= lr * gA
if step % 60 == 0:
print(f"step {step:3d} loss {0.5 * np.mean(np.sum((P - Y)**2, axis=1)):.2e}")
dW = B @ A
print("trainable:", B.size + A.size, "of", W0.size, " rank(BA) =", np.linalg.matrix_rank(dW))
print(f"relative error of learned update: {np.linalg.norm(dW - dW_true) / np.linalg.norm(dW_true):.1e}")step 0 loss 9.29e-01
step 60 loss 8.37e-01
step 120 loss 4.03e-02
step 180 loss 6.37e-04
step 240 loss 1.88e-05
step 300 loss 7.13e-07
trainable: 100 of 600 rank(BA) = 2
relative error of learned update: 1.1e-03
Training 100 numbers recovered a 600-number update to about 0.1%, because the update really was rank 2. The slow start is typical of the initialization: the gradient of is at first, so only moves until it has grown. Real fine-tuning updates are only approximately low rank, which is why is a tunable trade-off.
Note: and are not unique: for any invertible matrix . Only their product is determined, so compare , never or separately.
In software
- LLM fine-tuning. Hugging Face PEFT,
LoraConfig(r=8, lora_alpha=16, target_modules=[...]); QLoRA adds a 4-bit quantized base model. - Model compression. Replacing a dense layer by two thin ones (truncated SVD of ) shrinks models and speeds up inference.
- Recommenders. Matrix factorization of a ratings matrix, see the mini project.
- Images and scientific data. Truncated SVD compression and denoising (SVD); randomized SVD scales it to huge matrices.
Go further: LoRA: Low-Rank Adaptation from Scratch puts low-rank updates inside a network and measures how much rank a fine-tuning change needs.
Exercises
Exercise 1: Error from singular values
has singular values 10, 4, 3, 0.5. What are the operator-norm and Frobenius-norm errors of the best rank-2 approximation?
Answer
and .
Solution
The operator error is . The Frobenius error is .
Exercise 2: Energy kept
With the singular values of Exercise 1, what fraction of does keep?
Answer
.
Solution
; the total is .
Exercise 3: LoRA budget
A layer has of size . How many trainable parameters does LoRA with add, and what percentage of is that?
Answer
81,920 parameters, about 1.95% of 4,194,304.
Solution
, and .
Exercise 4: Rank of a product (code)
Show numerically that has rank at most for random () and (), and that adding it to a full-rank changes by a rank-3 matrix.
Answer
, , .
Solution
Every column of is a combination of the 3 columns of , so its column space has dimension .
import numpy as np
rng = np.random.default_rng(4)
B, A, W = rng.normal(size=(50, 3)), rng.normal(size=(3, 40)), rng.normal(size=(50, 40))
r = np.linalg.matrix_rank
print(r(B @ A), r(W), r((W + B @ A) - W))3 40 3
Test yourself
By the Eckart–Young theorem, the best rank- approximation of in the 2-norm has error…
- 0
In LoRA, why is initialized to zero?
- To save memory
- So that and training starts from the pretrained model
- Because must stay zero
- To make orthogonal
How many trainable parameters does LoRA with rank add to a weight matrix?