The SVD: rotate, stretch, rotate
Every matrix, of any shape, is a rotation, a stretch along the axes and another rotation. Keep the biggest stretches and you get the best low-rank copy, the idea behind LoRA.
1. The idea
Eigenvectors only work for square matrices, and not even for all of those. The singular value decomposition works for every matrix: A = UΣVᵀ. Read it right to left: Vᵀ rotates, Σ stretches along the axes, and U rotates again. Any matrix, whatever its shape, is a rotate, a stretch and a rotate.
The stretch factors σ₁ ≥ σ₂ ≥ … ≥ 0 on Σ's diagonal are the singular values. They say how much A stretches in its most-stretched direction, in the next, and so on. The number of non-zero ones is the rank of A.
Keep only the biggest k singular values and you get the best rank-k approximation of A: no other rank-k matrix is closer. That is low-rank compression, and it is the intuition behind LoRA, which stores a fine-tuning update ΔW as the product of two thin matrices, a rank-r matrix, betting that what the update needs to do lives in a few directions.
2. Try it: three moves, one ellipse
Set a matrix with the four sliders, then step through Vᵀ, Σ and U and watch the unit circle become an ellipse. Then keep only σ₁ and see what a rank-1 copy of A does.
3. The math
4. The code (python)
import numpy as np
rng = np.random.default_rng(0)
# a 6 x 5 matrix that is almost rank 2: two strong directions plus a little noise
M = rng.normal(size=(6, 2)) @ rng.normal(size=(2, 5)) + 0.01 * rng.normal(size=(6, 5))
U, s, Vt = np.linalg.svd(M)
print(U.shape, s.shape, Vt.shape) # (6, 6) (5,) (5, 5)
print(s.round(3)) # [4.979 2.174 0.023 0.016 0.005]
M2 = (U[:, :2] * s[:2]) @ Vt[:2] # keep the two largest singular values
print(round(np.linalg.norm(M - M2) / np.linalg.norm(M), 4)) # 0.0053
d, r = 4096, 8 # LoRA: a full update against a rank-8 one
print(d * d, 2 * d * r) # 16777216 655365. You’ll see this in
- Reference notes: matrix decompositions, SVD and LoRA the same ideas, with proofs
- Module 1: linear combinations and span rank, from the other side
6. Check yourself
Finished this chapter?
The Epoch Zero newsletter
What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.