Singular Value Decomposition (SVD), PCA & Low-Rank Compression (LoRA)
Factorize ANY rectangular matrix M = UΣVᵀ — optimal rank-k compression, PCA without forming XᵀX, Moore–Penrose pseudoinverse, and LoRA
SVD is the Swiss Army Knife of modern AI — powering LoRA LLM fine-tuning, Netflix Recommender Systems, Stable PCA, and Pseudoinverses!
Fine-tuning a 70B LLM on consumer GPUs is only possible because of Low-Rank Adaptation (LoRA): factoring giant ΔW updates into two tiny rank-r matrices B·A cuts VRAM by 98%+!
SVD works on EVERY rectangular matrix (unlike eigendecomposition which requires square matrices!), powering `sklearn.decomposition.PCA`, Latent Semantic Analysis, and collaborative filtering.
Explaining 'What are U, Σ, Vᵀ geometrically?', 'Eckart–Young optimal rank-k approximation', and 'How LoRA saves 98% parameters' wins Senior ML & GenAI rounds!
A Llama layer has a 4,096 × 4,096 weight matrix (~16.8 MILLION parameters!). With LoRA rank r = 8, you replace full ΔW with two skinny matrices B (4096×8) and A (8×4096). Roughly how much trainable memory do you SAVE?
- Decompose any rectangular m × n matrix via SVD (M = UΣVᵀ) and visualize its 3-step rotate → stretch → rotate geometry.
- Derive how centered SVD directly yields PCA principal components and variance ratios without forming XᵀX.
- Apply the Eckart–Young theorem to compute optimal rank-k approximations and explained energy ratios (Σ σ_i²).
- Compute exact LoRA parameter savings and use the Moore–Penrose pseudoinverse M⁺ = VΣ⁺Uᵀ.
Singular Value Decomposition (SVD) is the crown jewel of Linear Algebra. It works on every matrix — rectangular, non-symmetric, even singular — proving that every linear transformation in the universe is just (1) Rotate () (2) Stretch/Zero along axes () (3) Rotate ()!
1. The SVD Factorization & Its 3-Stage Geometry
Eigendecomposition had an annoying catch: it ONLY works on square matrices! What about a rectangular Netflix ratings grid (500,000 users × 10,000 movies) or a 1080 × 1920 photo? SVD (A = UΣVᵀ) works on EVERY matrix in the universe! Geometrically, EVERY matrix action — no matter how tangled — is just 3 baby steps: (1) Rotate (Vᵀ), (2) Stretch along axes (Σ), (3) Rotate again (U)!
Every matrix of rank factors as:
- (left singular vectors): Orthonormal columns (eigenvectors of ).
- (singular values): Non-negative diagonal entries sorted .
- (right singular vectors): Orthonormal rows (eigenvectors of ).
Why Production PCA Uses SVD (Not Covariance Eigendecomposition)
For centered data :
- Rows of ARE the principal components; eigenvalues are .
- Computing SVD on avoids forming , preventing condition-number squaring !
Eckart–Young Theorem: keeping the top k singular layers gives the mathematically BEST possible rank-k approximation!
The first few singular values capture giant macro patterns (faces, movie genres); tiny tail σ's are just random noise!
A centered dataset X_c has singular values [10, 4, 2, 0]. What is the rank of X_c, and what percentage of total variance does PC1 capture?
2. Thin SVD, Eckart–Young Optimal Compression & Pseudoinverse
How does scikit-learn actually compute PCA on a massive 50,000-column genetics dataset without blowing up RAM forming a 50,000×50,000 covariance matrix? Thin SVD directly on X_c! Because X_cᵀX_c = V Σ² Vᵀ, the right singular vectors V ARE the exact PCA axes and σᵢ² / n ARE the exact PCA eigenvalues — faster AND twice as numerically accurate!
Keeping only the top singular values gives . By the Eckart–Young–Mirsky Theorem, is the unique global best rank- approximation:
The Moore–Penrose Pseudoinverse
Invert every non-zero to (leaving zeros as ) to get: Then automatically gives the minimum-norm least-squares solution even for rank-deficient or wide () matrices!
If M has shape (1000, 200) and we store its rank-10 SVD (U₁₀, Σ₁₀, V₁₀ᵀ), how many floats do we store instead of 200,000?
3. LoRA Fine-Tuning: Low-Rank Matrices Powering Modern GenAI
Fine-tuning a modern 70-billion-parameter LLM normally requires a cluster of 16× H100 GPUs! In 2021, Microsoft researchers realized a stunning Linear Algebra fact: the change ΔW needed to adapt an LLM to a new task has tiny intrinsic rank (r = 4 to 16)! Slide the LoRA rank r below to watch GPU parameter requirements collapse by 99%+!
When fine-tuning a 70B LLM on a downstream task, weight updates empirically have very low intrinsic rank. LoRA (Low-Rank Adaptation) freezes pretrained and trains two tiny matrices and ():
- Worked Math (): Full has params; LoRA has params — 99.22% fewer trainable weights!
- Zero Inference Latency: After training, simply merge !
Instead of fine-tuning a massive 4096 × 4096 Llama weight update matrix (16.78M parameters!), LoRA factors it into two skinny matrices (4096 × r) and (r × 4096)! Slide rank r below:
Pause & Check: In LoRA (W = W₀ + B·A), why do engineers initialize matrix A with random Gaussian noise and matrix B with ALL ZEROS?
Why does LoRA initialize matrix A with random Gaussian values and matrix B with all ZEROS?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
- Eigendecomposition (
A = QΛQ⁻¹): ONLY works on square matrices, may fail or produce complex numbers, and uses ONE basis (Q). - SVD (
A = UΣVᵀ): Works on EVERY matrix (tall, wide, square, singular!), ALWAYS has 100% real non-negativeΣ, and uses TWO clean perpendicular bases (Vfor input space,Ufor output space)!
LoRA & QLoRA Fine-Tuning
Injects trainable rank-r factors BA alongside frozen quantized LLM weights, letting a 7B–70B model fine-tune on a single GPU.
Production PCA (scikit-learn)
Uses centered thin SVD (`full_matrices=False`) or randomized SVD for speed and numerical precision.
Matrix Factorization Recommenders
Approximates sparse User × Item ratings as low-rank U_k V_kᵀ latent factors.
DeepSeek Multi-Head Latent Attention (MLA)
Compresses high-dimensional KV caches into a shared low-rank latent vector to slash inference memory.
import numpy as np
X = np.random.default_rng(42).normal(size=(100, 12))
X_c = X - X.mean(axis=0, keepdims=True) # ALWAYS mean-center!
# ALWAYS pass full_matrices=False to avoid allocating 100x100 U!
U, S, Vt = np.linalg.svd(X_c, full_matrices=False) # U:(100,12), S:(12,), Vt:(12,12)
explained_var_ratio = (S ** 2) / np.sum(S ** 2)
# Top-k PCA projection & reconstruction:
k = 3
Z = X_c @ Vt[:k].T # (100, 3)
X_hat = Z @ Vt[:k] + X.mean(axis=0) # (100, 12)