Math Foundations: SVD, Eigendecomposition, Matrix Calculus, and ELBO Derivation
4735 words
24 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Math Foundations: SVD, Eigendecomposition, Matrix Calculus, and ELBO Derivation ## 🎯 Learning Objectives - Compute and interpret singular value decomposition (SVD) and eigendecomposition - Understand matrix calculus for gradient-based optimization - Derive the ELBO from first principles with full mathematical det...

Math Foundations: SVD, Eigendecomposition, Matrix Calculus, and ELBO Derivation
🎯 Learning Objectives
- Compute and interpret singular value decomposition (SVD) and eigendecomposition
- Understand matrix calculus for gradient-based optimization
- Derive the ELBO from first principles with full mathematical detail
- Apply optimization concepts to generative model training
- Connect linear algebra to key generative model operations
📋 Prerequisites
- Linear algebra basics: Vectors, matrices, matrix multiplication
- Calculus: Partial derivatives, chain rule
- Probability: Expectation, Bayes rule, KL divergence
- Generative Models Overview (Week 1): Basic ML concepts
1. 📖 Core Content
1.1 Intuition: Why Math Matters for Generative AI
Every generative model is built on mathematical foundations:
- Linear algebra powers the transformations in neural networks — matrix multiplications, convolutions, attention mechanisms. SVD and eigendecomposition are used for PCA (preprocessing), understanding latent spaces, and analyzing optimization landscapes.
- Matrix calculus enables gradient-based learning — backpropagation is repeated application of the chain rule on matrix expressions.
- Optimization theory explains why certain training strategies work — SGD, Adam, learning rate schedules all exploit properties of the loss landscape.
- The ELBO is the central objective for VAEs, diffusion models, and many other generative models. Understanding its derivation is essential for debugging and extending these models.
1.2 Eigenvalues and Eigenvectors
1.2.1 Definition
For a square matrix A∈Rn×n, a non-zero vector v∈Rn is an eigenvector with corresponding eigenvalue λ if:
This means: multiplying A with v is equivalent to scaling v by λ. The eigenvector's direction is preserved; only its magnitude changes.
1.2.2 Intuition
Think of A as a transformation that stretches/compresses space. Eigenvectors are the "special directions" that are only scaled, not rotated. The eigenvalue tells you how much stretching occurs along that direction.
- ∣λ∣>1: Stretching
- ∣λ∣<1: Compression
- ∣λ∣=1: Unchanged
- λ=0: Direction is in the nullspace
1.2.3 Eigendecomposition
If A has n linearly independent eigenvectors, we can diagonalize it:
where:
- V: Matrix whose columns are eigenvectors
- Λ: Diagonal matrix of eigenvalues diag(λ1,...,λn) For real symmetric matrices (A=AT), eigenvectors are orthogonal, so V−1=VT:
Worked Example 1: Eigendecomposition of a 2×2 Matrix
Find eigenvalues and eigenvectors of
.
Step 1: Solve characteristic equation det(A−λI)=0:
Step 2: Find eigenvector for λ1: (A−λ1I)v1=0
From first row: −0.618v11+v12=0⟹v12=0.618v11
So
, normalized:
Step 3: Similarly for λ2:
Step 4: Verify: VTAV=Λ
1.3 Singular Value Decomposition (SVD)
SVD generalizes eigendecomposition to non-square matrices. Any matrix A∈Rm×n can be decomposed as:
where:
- U∈Rm×m: Left singular vectors (orthogonal columns, UTU=I)
- Σ∈Rm×n: Diagonal matrix of singular values σ1≥σ2≥...≥σr>0
- V∈Rn×n: Right singular vectors (orthogonal columns, VTV=I)
- r: Rank of A (number of non-zero singular values)
1.3.1 Intuition
SVD reveals what A does as a linear transformation:
- VT rotates the input to align with a new coordinate system
- Σ scales each coordinate by σi
- U rotates the result to produce the output (Diagram)
1.3.2 Relationship to Eigendecomposition
For ATA (a square symmetric matrix):
So:
- V contains eigenvectors of ATA
- σi2=λi (singular values squared = eigenvalues of ATA) Similarly, U contains eigenvectors of AAT.
Worked Example 2: SVD of a 2×2 Matrix
Compute SVD of
.
Step 1: Compute
Step 2: Find eigenvalues of ATA:
Singular values: σ1=16=4, σ2=4=2
Step 3: Find eigenvectors of ATA for V:
For λ1=16:
For λ2=4:
Step 4: Compute U: ui=σiAvi
Step 5: Verify:
1.4 Matrix Calculus
For training neural networks, we need gradients of scalar loss functions with respect to matrix parameters.
1.4.1 Key Rules
| Operation | Gradient |
|---|---|
| ∂x∂(aTx)=a | Linear form |
| ∂x∂(xTAx)=(A+AT)x | Quadratic form |
| ∂X∂Tr(AX)=AT | Trace |
| ∂X∂det(X)=det(X)(X−1)T | Determinant |
| $\frac{\partial}{\partial X} \ | X\ |
Worked Example 3: Gradient of a Quadratic Form
Compute ∇xf(x) where f(x)=(x−μ)TΣ−1(x−μ) (Mahalanobis distance squared).
Step 1: Expand: Let y=x−μ, then f=yTΣ−1y.
Step 2: Using ∂y∂(yTAy)=(A+AT)y with A=Σ−1 (which is symmetric):
Step 3: Chain rule:
1.4.2 Gradients of Log-Likelihood for Gaussians
For a multivariate Gaussian p(x)=N(x∣μ,Σ):
Gradient w.r.t. μ:
Gradient w.r.t. Σ−1 (natural parameterization):
These gradients are used in:
- MLE for Gaussian models
- VAE training (Gaussian encoder/decoder)
- KL divergence computation in diffusion models
1.5 Optimization for Generative Models
1.5.1 Convex vs Non-Convex Optimization
Convex functions: Bowl-shaped, any local minimum is global. Guaranteed convergence for gradient descent.
Non-convex functions: Multi-modal, multiple local minima. Neural network training landscapes are non-convex.
Generative model training is highly non-convex due to:
- Neural network parameterizations
- Min-max objectives (GANs)
- Latent variable marginalization (VAEs)
1.5.2 Stochastic Gradient Descent (SGD)
θt+1=θt−ηt∇θLB(θt)where LB is the loss computed on a mini-batch B.
Why SGD works for generative models:
- Efficient for large datasets (compute gradient on subset)
- Noise helps escape shallow local minima
- Generalizes better than full-batch gradient descent
1.5.3 Adam Optimizer
Adam combines momentum + adaptive learning rates:
Recommended defaults for generative models:
- β1=0.9,β2=0.999,η=1e−4 (GANs), 3e−4 (diffusion models)
- Lower learning rates for discriminator/critic (two-timescale update rule)
1.6 The ELBO: Full Derivation
The Evidence Lower Bound (ELBO) is the central objective for VAEs and many other generative models.
1.6.1 The Problem
We have a latent variable model:
This integral is intractable for complex models (neural network decoders) because we'd need to integrate over all possible z.
1.6.2 Introducing the Variational Distribution
We introduce an approximate posterior qϕ(z∣x) (the encoder). The goal: make qϕ(z∣x) close to the true posterior pθ(z∣x).
1.6.3 Derivation Step 1: Start with Log-Likelihood
logpθ(x)=log∫pθ(x∣z)p(z)dz1.6.4 Derivation Step 2: Multiply by 1 = q/q
logpθ(x)=log∫qϕ(z∣x)⋅qϕ(z∣x)pθ(x∣z)p(z)dz1.6.5 Derivation Step 3: Apply Jensen's Inequality
For a concave function (log is concave), log(E[y])≥E[log(y)]:
The RHS is the ELBO, denoted L(x;θ,ϕ).
1.6.6 Derivation Step 4: Rearrange the ELBO
L(x;θ,ϕ)=Eqϕ(z∣x)[logpθ(x∣z)]+Eqϕ(z∣x)[logqϕ(z∣x)p(z)] =ReconstructionEqϕ(z∣x)[logpθ(x∣z)]−KL divergenceDKL(qϕ(z∣x)∥p(z))1.6.7 Derivation Step 5: The Gap
The gap between the true log-likelihood and the ELBO is the KL divergence between qϕ(z∣x) and the true posterior pθ(z∣x):
Proof:
1.6.8 The Reparameterization Trick
The ELBO requires gradient through Ez∼qϕ(z∣x)[logpθ(x∣z)], but z is sampled stochastically. Since sampling is non-differentiable, we reparameterize:
Now the expectation is over ϵ (which doesn't depend on ϕ), and the gradient can flow through μϕ and σϕ:
1.7 Why This Matters
The mathematical tools covered here are used throughout generative AI:
- SVD: PCA for data preprocessing, analyzing latent space structure, low-rank approximations (LoRA) for fine-tuning
- Eigendecomposition: Understanding covariance structure of features, FID computation
- Matrix calculus: Every gradient-based training loop
- Optimization: Choosing optimizers (Adam vs SGD), learning rate schedules, warmup
- ELBO: Foundations of VAEs, diffusion models (which can be seen as hierarchical VAEs)
2. 📐 Key Formulas / Concepts
| Concept | Formula | Application in GenAI |
|---|---|---|
| Eigendecomposition | A=VΛVT (symmetric) | PCA, covariance analysis |
| SVD | A=UΣVT | Low-rank approximations, latent structure |
| Quadratic gradient | ∇x(xTAx)=2Ax (A symmetric) | Gaussian gradient computation |
| ELBO | $\mathcal{L} = \mathbb{E}q[\log p\theta(x | z)] - D_{KL}(q_\phi(z |
| Reparameterization | z=μ+σ⋅ϵ | Differentiable sampling |
| Adam update | θt+1=θt−ηvt+ϵmt | Default optimizer for gen models |
3. ⚠️ Common Pitfalls
Pitfall 1: Confusing SVD and Eigendecomposition
Mistake: Using eigendecomposition when SVD is needed (for non-square matrices).
Why: Eigendecomposition only works for square matrices. SVD works for any matrix.
Correct approach: Use eigendecomposition for analyzing square symmetric matrices (covariance matrices, Gram matrices). Use SVD for data matrices, weight matrices, and any non-square case.
Pitfall 2: Forgetting the Reparameterization Trick Isn't Always Applicable
Mistake: Trying to apply the reparameterization trick to discrete latent variables.
Why: The reparameterization trick requires the sampling distribution to be reparameterizable as a deterministic function of a noise source. For discrete distributions (e.g., categorical), z takes discrete values and can't be written as μ+σ⋅ϵ with ϵ∼N(0,I).
Correct approach: Use the Gumbel-Softmax trick (continuous relaxation of discrete sampling) or REINFORCE gradient estimator for discrete latents.
Pitfall 3: Ignoring the KL Vanishing Problem
Mistake: Training a VAE and wondering why the latent variables aren't used.
Why: The KL term in the ELBO encourages qϕ(z∣x) to match the prior p(z). If the decoder is powerful enough, the model can "ignore" z and set qϕ(z∣x)=p(z), resulting in DKL=0 but no meaningful latent representation.
Correct approach: Monitor KL divergence during training. If it drops to near zero, use KL annealing, free bits (a minimum KL per dimension), or reduce decoder capacity.
Pitfall 4: Using SGD when Adam is Needed
Mistake: Using vanilla SGD for GAN or VAE training with poor results.
Why: Generative model losses are highly non-convex and have varying gradient scales across parameters. SGD's fixed learning rate per parameter struggles. Adam's adaptive learning rates handle the varying scales better.
Correct approach: Use Adam for most generative models. For GANs, use two-timescale Adam (different learning rates for generator and discriminator).
Pitfall 5: Mishandling Matrix Calculus Gradients
Mistake: Computing matrix gradients as scalars without respecting transpose relationships.
Why: ∂W∂f has the same dimensions as W, but the chain rule for matrix functions requires attention to transposition.
Correct approach: Use dimensional analysis. If f=∥Wx−y∥2:
- f is scalar
- W is dout×din
- ∂W∂f=2(Wx−y)xT (check: dout×din ✓)
4. 📝 Practice Questions
>A=[2112]>**Q1: Compute the eigenvalues of
>A=[2112]=VΛVT=21[111−1][3001][111−1]>and explain what they mean geometrically.**Step 1: det(A−λI)=(2−λ)2−1=λ2−4λ+3=0Step 2: λ=24±16−12=24±2Step 3: λ1=3, λ2=1Geometric interpretation: A stretches space by a factor of 3 along eigenvectors corresponding to λ1 and by 1 (no stretch) along eigenvectors corresponding to λ2.Eigenvectors:
λ1=3: v1=[1,1]T/2 (direction of equal increase) λ2=1: v2=[1,−1]T/2 (direction of difference)
>A=[100200]>**Q2: Compute the SVD of
>AAT=[1004]>.**Step 1: A is 2×3, so U is 2×2, Σ is 2×3, V is 3×3.Step 2:
>v1=σ1ATu1=21100020[01]=21020=010>, eigenvalues: λ1=4, λ2=1.Singular values: σ1=2, σ2=1.Step 3: U from eigenvectors of AAT: u1=[0,1]T, u2=[1,0]T.Step 4: V from V=ATUΣ−1 (more carefully):Σ=[diag(2,1),02×1]
>v2=σ2ATu2=11100020[10]=100>
>UΣVT=[0110][200100]010100001=[100200]=A>v3 is in the nullspace of A (since Av3=0): v3=[0,0,1]T.Step 5: Verify:
Q3: Compute ∇xf for f(x)=∥Ax−b∥22.Step 1: Expand: f=(Ax−b)T(Ax−b)=xTATAx−2bTAx+bTbStep 2: Differentiate each term:
- ∂x∂(xTATAx)=2ATAx
- ∂x∂(−2bTAx)=−2ATb
- ∂x∂(bTb)=0
Step 3: ∇xf=2ATAx−2ATb=2AT(Ax−b) Q4: Starting from logp(x), derive the ELBO and show that optimizing it maximizes a lower bound on the log-likelihood.The derivation is in Section 1.6 above. The key steps:
- logp(x)=log∫p(x∣z)p(z)dz
- Introduce q(z∣x): logp(x)=log∫q(z∣x)q(z∣x)p(x∣z)p(z)dz
- Jensen's inequality: logEq[f]≥Eq[logf]
- Result: logp(x)≥Eq[logp(x∣z)]−DKL(q(z∣x)∥p(z))=ELBO
Optimizing θ,ϕ to maximize the ELBO:
- Increases the log-likelihood (by at least as much as the ELBO increases)
- Decreases DKL(qϕ(z∣x)∥pθ(z∣x)) (the approximation gap)
The tightness depends on how well qϕ(z∣x) approximates the true posterior pθ(z∣x). Q5: In the reparameterization trick, why can't we just differentiate through the sampling operation directly?The sampling operation z∼qϕ(z∣x) is a stochastic process. The gradient of this operation w.r.t. ϕ would require differentiating through a random number generator, which is non-differentiable.Concretely, z=sample(μϕ,σϕ) involves calling a random number generator to produce ϵ∼N(0,1), then computing z=μϕ+σϕϵ. The RNG call has no gradient (the operation is discrete — a number is drawn; there's no continuous path for gradient flow).The reparameterization trick moves the stochasticity to an independent noise source ϵ:z=μϕ(x)+σϕ(x)⋅ϵ,ϵ∼N(0,1)Now:
- The gradient can flow through μϕ and σϕ (differentiable operations)
- ϵ is independent of ϕ, so no gradient through sampling
- The expectation is still valid because N(z∣μ,σ2)dz=N(ϵ∣0,1)dϵ Q6: For a covariance matrix Σ, explain why Σ must be positive semidefinite and how eigendecomposition reveals this.
A covariance matrix must be positive semidefinite (PSD) because for any vector v:vTΣv=vTE[(X−μ)(X−μ)T]v=E[vT(X−μ)(X−μ)Tv]=E[(vT(X−μ))2]≥0The variance of any linear combination is non-negative.By eigendecomposition, Σ=VΛVT. PSD means all eigenvalues λi≥0. This is evident because:
- If any λi<0, then viTΣvi=λi<0 (contradiction)
- The singular values from SVD of the data matrix are λi, confirming non-negativity
This PSD property ensures:
- FID computation (matrix square root) is valid
- KL divergence between Gaussians is well-defined
- Cholesky decomposition for efficient sampling exists Q7: A VAE uses Adam with default parameters (η=0.001, β1=0.9, β2=0.999). After 100 epochs, the KL term is 0.01 (near zero). Diagnose the problem and propose a fix.
Diagnosis: KL vanishing. The model is ignoring the latent variable z and functioning as an autoencoder with no regularization. The decoder is powerful enough to reconstruct x without z, so the KL term forces q(z∣x)→p(z)=N(0,I), giving DKL≈0.Fixes (in order of recommendation):
KL annealing: Start with β=0 in L=Recon−β⋅KL, gradually increase β from 0 to 1 over training. This lets the model learn meaningful latent representations before the KL penalty kicks in. Free bits: Set a minimum KL per dimension: KLmin=max(β⋅KL,λ). This ensures each dimension carries at least λ nats of information. Reduce decoder capacity: A weaker decoder (fewer layers, smaller hidden size) forces the model to use the latent code. Increase latent dimension: More dimensions give the model more capacity to encode information before the KL penalty forces them to the prior.Q8: Show that ∇θEx∼pθ[f(x)]=Ex∼pθ[f(x)∇θlogpθ(x)] (the REINFORCE/score function gradient).Step 1: Write the expectation as an integral:∇θEx∼pθ[f(x)]=∇θ∫f(x)pθ(x)dxStep 2: Swap gradient and integral (under smoothness conditions):=∫f(x)∇θpθ(x)dxStep 3: Use the log-derivative trick: ∇θpθ(x)=pθ(x)∇θlogpθ(x)=∫f(x)pθ(x)∇θlogpθ(x)dxStep 4: Recognize as an expectation:=Ex∼pθ[f(x)∇θlogpθ(x)]This is the REINFORCE gradient estimator or score function estimator. It allows gradient estimation through non-differentiable sampling by using logpθ(x) instead of ∇θx.Comparison with reparameterization:
- Reparameterization: Lower variance, but requires continuous x and differentiable f
- REINFORCE: Higher variance, but works for discrete x and non-differentiable f Q9: For a multivariate Gaussian N(μ,Σ), derive the gradient of the log-likelihood with respect to μ for a single sample x.
Step 1: Write the log-likelihood:logp(x∣μ,Σ)=−21(x−μ)TΣ−1(x−μ)−21log∣Σ∣−2Dlog(2π)Step 2: Only the first term depends on μ:∇μlogp(x∣μ,Σ)=−21∇μ[(x−μ)TΣ−1(x−μ)]Step 3: Let y=x−μ. Then ∂μ∂y=−I.Step 4: ∂y∂(yTΣ−1y)=2Σ−1y (since Σ−1 is symmetric)Step 5: Chain rule:∇μlogp=−21⋅∂y∂(yTΣ−1y)⋅∂μ∂y=−21⋅(2Σ−1y)T⋅(−I)=yTΣ−1=(x−μ)TΣ−1In column-vector convention: ∇μlogp=Σ−1(x−μ).The MLE for μ sets this gradient to zero: Σ−1(μ^−xavg)=0⟹μ^=N1∑xi, confirming that the MLE for the mean is the sample mean. Q10: Explain why Adam's bias correction is important in the first few iterations of VAE training.Without bias correction, Adam's moment estimates are biased toward zero because they're initialized as m0=0,v0=0:mt=β1mt−1+(1−β1)gtIn early iterations, mt is "warmed up" from 0. For β1=0.9:
- t=1: m1=0.9⋅0+0.1⋅g1=0.1g1 (10% of true gradient)
- t=5: m5≈0.41gavg (still biased)
- t=20: m20≈0.88gavg (approaching true)
Bias correction divides by 1−β1t:m^t=1−β1tmt
- t=1: m^1=0.1g1/(1−0.9)=g1 ✓
- t=5: m^5≈0.41gavg/(1−0.95)=0.41/0.41≈gavg ✓
Without bias correction, the first steps would be too small, slowing convergence — particularly noticeable in VAE training where initial gradients guide the model toward meaningful latent representations. Q11: Derive the gradient of DKL(qϕ(z∣x)∥p(z)) with respect to ϕ where qϕ(z∣x)=N(μϕ,σϕ2) and p(z)=N(0,1).Step 1: Write the KL in closed form for Gaussians:DKL(N(μ,σ2)∥N(0,1))=logσ1+2σ2+μ2−21=−logσ+2σ2+μ2−21Step 2: Differentiate w.r.t. μ:∂μ∂KL=μStep 3: Differentiate w.r.t. σ (using σ as the standard deviation):∂σ∂KL=−σ1+σ=σ−σ1=σσ2−1Step 4: In practice, we parameterize logσ2 (log-variance) for numerical stability. Let s=logσ2, so σ=es/2:∂s∂KL=∂σ∂KL⋅∂s∂σ=(σ−σ1)⋅2es/2=(es/2−e−s/2)⋅2es/2=2es−1=2σ2−1The gradient tells us:
- If μ>0, push μ toward zero (reduce mean)
- If σ>1, push σ toward 1 (reduce variance)
- If σ<1, push σ toward 1 (increase variance)
The KL pushes the posterior toward a unit Gaussian — neither too wide nor too narrow. Q12: In diffusion models, the training loss L=Et,x0,ϵ[∥ϵ−ϵθ(xt,t)∥2] resembles a denoising objective. Show how this relates to the ELBO.The diffusion model's variational bound can be written as:Lvb=∑t=1TEx0,ϵt[DKL(q(xt−1∣xt,x0)∥pθ(xt−1∣xt))]Each KL term is between two Gaussians:
- q(xt−1∣xt,x0)=N(μ~t(xt,x0),β~tI) (the forward posterior, known)
- pθ(xt−1∣xt)=N(μθ(xt,t),σt2I) (the model, learned)
Using the closed-form KL for Gaussians:DKL(q∥pθ)=2σt21∥μ~t(xt,x0)−μθ(xt,t)∥2+constWe parameterize μθ as:μθ(xt,t)=αt1(xt−1−αˉtβtϵθ(xt,t))And the forward posterior mean is:μ~t(xt,x0)=αt1(xt−1−αˉtβtϵt)Substituting, the KL simplifies to:DKL(q∥pθ)∝∥ϵt−ϵθ(xt,t)∥2Thus, the diffusion training loss ∥ϵ−ϵθ(xt,t)∥2 is equivalent to minimizing the KL divergence between the true denoising step and the model's prediction at each timestep — which is exactly the ELBO for diffusion models. This demonstrates the deep connection between denoising score matching and variational inference.
5. 🔗 Cross-References
- All BSDA5002 topics: This math is used throughout
- Information Theory (Week 9) (../week09/09-information-theory.md) — KL divergence, entropy
- VAEs (Week 3) (../week03/03-vaes.md) — ELBO in practice
- External: Matrix Cookbook by Petersen & Pedersen — Comprehensive matrix calculus reference
- External: "Deep Learning" by Goodfellow, Bengio, Courville — Chapters on optimization and linear algebra Join Discord PreviousInformation TheoryNextBSDA5002 — Generative AI Foundations