TExcelTAD
Home › Linear Algebra & Matrix Theory › Low-Rank Approximation: Compression and LoRA

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-kk matrices are cheap

A matrix of rank kk can be written as a product of an m×km \times k and a k×nk \times n matrix (or as a sum of kk outer products uvT\mathbf{u}\mathbf{v}^T). Storing and multiplying it then costs k(m+n)k(m + n) instead of mnmn:

m×nm \times n full rank 8 ratio
1000×10001000 \times 1000 1,000,000 16,000 1.6%
4096×40964096 \times 4096 16,777,216 65,536 0.39%

Multiplying a vector by B(Ax)B(A\mathbf{x}) instead of (BA)x(BA)\mathbf{x} also drops the cost from mnmn to k(m+n)k(m + n).

The Eckart–Young theorem

Write the SVD as A=∑σiuiviTA = \sum \sigma_i \mathbf{u}_i \mathbf{v}_i^T and let Ak=σ1u1v1T+⋯+σkukvkTA_k = \sigma_1 \mathbf{u}_1 \mathbf{v}_1^T + \cdots + \sigma_k \mathbf{u}_k \mathbf{v}_k^T (keep the kk largest singular values).

Theorem (Eckart–Young–Mirsky). Among all matrices BB of rank at most kk,

∥A−B∥2≥∥A−Ak∥2=σk+1∥A−B∥F≥∥A−Ak∥F=σk+12+⋯+σr2\begin{aligned} \lVert A - B \rVert_2 &\ge \lVert A - A_k \rVert_2 = \sigma_{k+1} \\ \lVert A - B \rVert_F &\ge \lVert A - A_k \rVert_F = \sqrt{\sigma_{k+1}^2 + \cdots + \sigma_r^2} \end{aligned}

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 (σ12+⋯+σk2)/(σ12+⋯+σr2)(\sigma_1^2 + \cdots + \sigma_k^2)/(\sigma_1^2 + \cdots + \sigma_r^2).

Proof idea (operator norm). If rank⁡B≤k\operatorname{rank} B \le k, its null space has dimension ≥n−k\ge n - k, so it meets the (k+1)(k + 1)-dimensional span of v1,…,vk+1\mathbf{v}_1, \ldots, \mathbf{v}_{k+1} in some unit vector x\mathbf{x}. Then (A−B)x=Ax(A - B)\mathbf{x} = A\mathbf{x}, and ∥Ax∥≥σk+1\lVert A\mathbf{x} \rVert \ge \sigma_{k+1} for any unit x\mathbf{x} in that span.

python · try it yourself
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 σ3\sigma_3 reveals the true rank; everything after it is noise. Choosing kk 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 WW (d×kd \times k), 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 WW and learns only a low-rank change:

W′=W+ΔW,ΔW=(α/r)⋅BA,B:d×r,A:r×k,r≪min⁡(d,k)forward: h=Wx+(α/r)⋅B(Ax)\begin{aligned} &W' = W + \Delta W, \quad \Delta W = (\alpha/r) \cdot BA, \quad B: d \times r, \quad A: r \times k, \quad r \ll \min(d, k) \\ &\text{forward: } \mathbf{h} = W\mathbf{x} + (\alpha/r) \cdot B(A\mathbf{x}) \end{aligned}
  • BB starts at 0 (and AA random), so ΔW=0\Delta W = 0 and training starts exactly at the pretrained model.
  • Trainable parameters per matrix: r(d+k)r(d + k) instead of dkdk.
  • After training, ΔW\Delta W can be merged into WW (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 ΔW\Delta W.
python · try it yourself
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 W0W_0 has to learn a task whose ideal weights are W0+ΔWtrueW_0 + \Delta W_{\text{true}} with rank 2. We train only BB and AA (rank 2) by gradient descent, using the backward-pass formulas from Neural Network Layers:

python · try it yourself
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 B=0B = 0 initialization: the gradient of AA is BT⋅(…)=0B^T \cdot (\ldots) = 0 at first, so only BB moves until it has grown. Real fine-tuning updates are only approximately low rank, which is why rr is a tunable trade-off.

Note: BB and AA are not unique: BA=(BM)(M−1A)BA = (BM)(M^{-1}A) for any invertible r×rr \times r matrix MM. Only their product is determined, so compare ΔW\Delta W, never BB or AA 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 WW) 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

AA has singular values 10, 4, 3, 0.5. What are the operator-norm and Frobenius-norm errors of the best rank-2 approximation?

Answer

∥A−A2∥2=3\lVert A - A_2 \rVert_2 = 3 and ∥A−A2∥F=9.25≈3.0414\lVert A - A_2 \rVert_F = \sqrt{9.25} \approx 3.0414.

Solution

The operator error is σ3=3\sigma_3 = 3. The Frobenius error is 32+0.52=9.25\sqrt{3^2 + 0.5^2} = \sqrt{9.25}.

Exercise 2: Energy kept

With the singular values of Exercise 1, what fraction of ∥A∥F2\lVert A \rVert_F^2 does A2A_2 keep?

Answer

116/125.25≈92.6%116/125.25 \approx 92.6\%.

Solution

σ12+σ22=100+16=116\sigma_1^2 + \sigma_2^2 = 100 + 16 = 116; the total is 116+9+0.25=125.25116 + 9 + 0.25 = 125.25.

Exercise 3: LoRA budget

A layer has WW of size 1024×40961024 \times 4096. How many trainable parameters does LoRA with r=16r = 16 add, and what percentage of WW is that?

Answer

81,920 parameters, about 1.95% of 4,194,304.

Solution

r(d+k)=16⋅(1024+4096)=16⋅5120=81 920r(d + k) = 16 \cdot (1024 + 4096) = 16 \cdot 5120 = 81\,920, and 81 920/4 194 304≈0.019581\,920/4\,194\,304 \approx 0.0195.

Exercise 4: Rank of a product (code)

Show numerically that BABA has rank at most rr for random BB (50×350 \times 3) and AA (3×403 \times 40), and that adding it to a full-rank WW changes WW by a rank-3 matrix.

Answer

rank⁡(BA)=3\operatorname{rank}(BA) = 3, rank⁡(W)=40\operatorname{rank}(W) = 40, rank⁡((W+BA)−W)=3\operatorname{rank}((W + BA) - W) = 3.

Solution

Every column of BABA is a combination of the 3 columns of BB, so its column space has dimension ≤3\le 3.

python · try it yourself
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-kk approximation of AA in the 2-norm has error…

  1. σk\sigma_k
  2. σk+1\sigma_{k+1}
  3. σ1−σk\sigma_1 - \sigma_k
  4. 0

In LoRA, why is BB initialized to zero?

  1. To save memory
  2. So that ΔW=BA=0\Delta W = BA = 0 and training starts from the pretrained model
  3. Because BB must stay zero
  4. To make AA orthogonal

How many trainable parameters does LoRA with rank rr add to a d×kd \times k weight matrix?

  1. d⋅kd \cdot k
  2. r2r^2
  3. r(d+k)r(d + k)
  4. d+kd + k