Chapter 9 of 10 · ~22 min read & lab+60 XP
Chapter 9 · Linear Algebra

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

Why ML Engineers & Data Scientists Actually Need This

SVD is the Swiss Army Knife of modern AI — powering LoRA LLM fine-tuning, Netflix Recommender Systems, Stable PCA, and Pseudoinverses!

ML / AI Engineer

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%+!

Data Scientist

SVD works on EVERY rectangular matrix (unlike eigendecomposition which requires square matrices!), powering `sklearn.decomposition.PCA`, Latent Semantic Analysis, and collaborative filtering.

Interview & Debug Edge

Explaining 'What are U, Σ, Vᵀ geometrically?', 'Eckart–Young optimal rank-k approximation', and 'How LoRA saves 98% parameters' wins Senior ML & GenAI rounds!

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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ᵀ.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“Singular Value Decomposition (SVD)”
Plain-English Meaning
EVERY matrix on Earth — even skinny rectangular tables! — breaks into 3 simple moves: Rotate (Vᵀ) → Stretch (Σ) → Rotate (U)!
Everyday Example
Works on a 1,000,000 × 50 dataset where eigendecomposition fails!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Singular Value Decomposition (SVD) is the crown jewel of Linear Algebra. It works on every matrix M∈Rm×nM \in \mathbb{R}^{m \times n} — rectangular, non-symmetric, even singular — proving that every linear transformation in the universe is just (1) Rotate (VTV^T) →\to (2) Stretch/Zero along axes (Σ\Sigma) →\to (3) Rotate (UU)!

1. The SVD Factorization & Its 3-Stage Geometry

Everyday Story First (Zero Math Yet!)

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)!

Unit CircleVᵀ (Rotate) →Σ (Stretch) →σ₁, σ₂ AxesU (Rotate) →
Figure 9.1 — Geometric Action of SVD (M = UΣVᵀ): EVERY matrix in existence simply rotates (Vᵀ), stretches/flattens along axes (Σ), and rotates again (U).

Every matrix M∈Rm×nM \in \mathbb{R}^{m \times n} of rank r≤min⁡(m,n)r \le \min(m, n) factors as: M=UΣVT=∑i=1rσiuiviTM = U \Sigma V^T = \sum_{i=1}^r \sigma_i \mathbf{u}_i \mathbf{v}_i^T

  • UU (left singular vectors): Orthonormal columns (eigenvectors of MMTMM^T).
  • Σ\Sigma (singular values): Non-negative diagonal entries sorted σ1≥σ2≥⋯≥σr>0\sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_r > 0.
  • VTV^T (right singular vectors): Orthonormal rows (eigenvectors of MTMM^T M).

Why Production PCA Uses SVD (Not Covariance Eigendecomposition)

For centered data Xc=UΣVTX_c = U\Sigma V^T: Σcov=1N−1XcTXc=1N−1VΣ2VT\Sigma_{\text{cov}} = \frac{1}{N-1} X_c^T X_c = \frac{1}{N-1} V \Sigma^2 V^T

  • Rows of VTV^T ARE the principal components; eigenvalues are λi=σi2/(N−1)\lambda_i = \sigma_i^2 / (N - 1).
  • Computing SVD on XcX_c avoids forming XcTXcX_c^T X_c, preventing condition-number squaring κ(Xc)2\kappa(X_c)^2!
Formula Anatomy · Click Any Colored Piece to Decode It
SVD Rank-k Compression: A ≈ σ₁u₁v₁ᵀ + σ₂u₂v₂ᵀ + ... + σₖuₖvₖᵀ

Eckart–Young Theorem: keeping the top k singular layers gives the mathematically BEST possible rank-k approximation!

Importance Weights (Sorted Loudest First!)

The first few singular values capture giant macro patterns (faces, movie genres); tiny tail σ's are just random noise!

In our example: Top 10 singular values often hold 95%+ of image energy!
Put it together with real numbers: On a 1000×1000 grayscale image (1M pixels), keeping just k = 25 SVD layers stores 25×2001 = 50K numbers (20× compression!) while looking crisp!
Try It Yourself

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

Everyday Story First (Zero Math Yet!)

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!

M(m × n)=U_k(m × k)Σ_k(k × k)V_kᵀ(k × n)Why Thin SVD (full_matrices=False)?For m=100,000 rows, n=50 features:• Full U: 100k × 100k = 80 GB RAM 💥• Thin U: 100k × 50 = 40 MB RAM ✓
Figure 9.2 — Thin SVD vs. Full SVD: passing full_matrices=False avoids allocating a giant m×m matrix U when m ≫ n.

Keeping only the top kk singular values gives Mk=∑i=1kσiuiviTM_k = \sum_{i=1}^k \sigma_i \mathbf{u}_i \mathbf{v}_i^T. By the Eckart–Young–Mirsky Theorem, MkM_k is the unique global best rank-kk approximation: ∥M−Mk∥F2=∑i=k+1rσi2,Energy(k)=∑i=1kσi2∑i=1rσi2\|M - M_k\|_F^2 = \sum_{i=k+1}^r \sigma_i^2, \qquad \text{Energy}(k) = \frac{\sum_{i=1}^k \sigma_i^2}{\sum_{i=1}^r \sigma_i^2}

The Moore–Penrose Pseudoinverse M+M^+

Invert every non-zero σi\sigma_i to 1/σi1/\sigma_i (leaving zeros as 00) to get: M+=VΣ+UTM^+ = V \Sigma^+ U^T Then w∗=X+y\mathbf{w}^* = X^+ \mathbf{y} automatically gives the minimum-norm least-squares solution even for rank-deficient or wide (D>ND > N) matrices!

Try It Yourself

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

Everyday Story First (Zero Math Yet!)

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%+!

Input xFrozen W (4096 × 4096)A (4096 → 16)B (16 → 4096)h = Wx + (α/r) BAx99.2% fewer trainable params!
Figure 9.3 — LoRA Low-Rank Adaptation: freeze pretrained W ∈ ℝ^(d×d) and train only tiny bottleneck matrices A (r×d) and B (d×r), cutting trainable weights by >99%.

When fine-tuning a 70B LLM on a downstream task, weight updates ΔW\Delta W empirically have very low intrinsic rank. LoRA (Low-Rank Adaptation) freezes pretrained W∈Rd×dW \in \mathbb{R}^{d \times d} and trains two tiny matrices A∈Rr×dA \in \mathbb{R}^{r \times d} and B∈Rd×rB \in \mathbb{R}^{d \times r} (r≪dr \ll d): h=Wx+αrB(Ax)\mathbf{h} = W\mathbf{x} + \frac{\alpha}{r} B(A\mathbf{x})

  • Worked Math (d=4096,r=16d = 4096, r = 16): Full WW has 16,777,21616{,}777{,}216 params; LoRA (A+B)(A + B) has 16×(4096+4096)=131,07216 \times (4096 + 4096) = \mathbf{131{,}072} params — 99.22% fewer trainable weights!
  • Zero Inference Latency: After training, simply merge Wmerged=W+αrBAW_{\text{merged}} = W + \frac{\alpha}{r} BA!
Hands-On Mini-Lab · Live LLM LoRA Low-Rank Compression Calculator (4096 × 4096 Layer)

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:

Full Matrix ΔW
16.78M
params/layer
LoRA (B·A)
65.5K
params/layer
Memory Saved!
99.61%
Fits on 1 GPU!
Pause & Check · Quick Intuition Pulse

Pause & Check: In LoRA (W = W₀ + B·A), why do engineers initialize matrix A with random Gaussian noise and matrix B with ALL ZEROS?

Try It Yourself

Why does LoRA initialize matrix A with random Gaussian values and matrix B with all ZEROS?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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 (V for input space, U for output space)!
Interactive Visual Lab
Lab Challenge: Drag rank slider k to find the smallest rank capturing at least 90% of matrix energy!
Rank-1 Approx
Original (Rank 8)
Retained Rank kk = 1 / 8
Singular Value Spectrum (σ₁ … σ₈)
σ1
σ2
σ3
σ4
σ5
σ6
σ7
σ8
Energy Captured
72.4%
Compression
-73%
Geometric Takeaway: SVD decomposes any rectangular matrix into UΣVᵀ; truncating to top k singular values gives the optimal rank-k approximation, powering PCA, pseudoinverses, and LoRA.
Where This Powers Real ML, Deep Learning & GenAI

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.

Production NumPy & PyTorch Code Patterns
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)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting `full_matrices=False` in `np.linalg.svd`
Best Practice: For N = 100k rows, full U allocates 80 GB RAM and crashes OOM; thin SVD uses only ~40 MB.
Trap #2: Forgetting to mean-center X before SVD-based PCA
Best Practice: Uncentered SVD aligns the first component toward the mean offset instead of the direction of maximum variance.
Trap #3: Using σ_i instead of σ_i² for explained variance ratio
Best Practice: Variance scales with squared singular values σ_i²!
Chapter Mastery Check (+60 XP)
Score: 0 / 5
1How many scalars does rank-k SVD (U_k, Σ_k, V_kᵀ) of an m × n matrix store?
2A centered matrix has singular values [10, 4, 2, 0]. What fraction of variance is explained by PC1?
3Why does LoRA initialize B = 0 and A ~ Normal(0, σ²)?
4What happens if you call `np.linalg.svd(X)` (default `full_matrices=True`) on a (100000, 20) dataset?
5What does the Moore–Penrose pseudoinverse w* = X⁺y compute when X is rank-deficient?

Apply What You Learned — Solve Matching Coding Problems