Quiz 2

Math Foundations: SVD, Eigendecomposition, Matrix Calculus, and ELBO Derivation

4735 words
24 min read
Python Week 1: the first filter for runtime behavior
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 ARn×nA \in \mathbb{R}^{n \times n}, a non-zero vector vRnv \in \mathbb{R}^n is an eigenvector with corresponding eigenvalue λ\lambda if:
Av=λvA v = \lambda v
This means: multiplying AA with vv is equivalent to scaling vv by λ\lambda. The eigenvector's direction is preserved; only its magnitude changes.

1.2.2 Intuition

Think of AA 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|\lambda| > 1: Stretching
  • λ<1|\lambda| < 1: Compression
  • λ=1|\lambda| = 1: Unchanged
  • λ=0\lambda = 0: Direction is in the nullspace

1.2.3 Eigendecomposition

If AA has nn linearly independent eigenvectors, we can diagonalize it:
A=VΛV1A = V \Lambda V^{-1}
where:
  • VV: Matrix whose columns are eigenvectors
  • Λ\Lambda: Diagonal matrix of eigenvalues diag(λ1,...,λn)\text{diag}(\lambda_1, ..., \lambda_n) For real symmetric matrices (A=ATA = A^T), eigenvectors are orthogonal, so V1=VTV^{-1} = V^T:
A=VΛVTA = V \Lambda V^T

Worked Example 1: Eigendecomposition of a 2×2 Matrix

Find eigenvalues and eigenvectors of
A=[4113]A = \begin{bmatrix} 4 & 1 \\ 1 & 3 \end{bmatrix}
. Step 1: Solve characteristic equation det(AλI)=0\det(A - \lambda I) = 0:
det([4λ113λ])=(4λ)(3λ)1=0\det\left(\begin{bmatrix} 4-\lambda & 1 \\ 1 & 3-\lambda \end{bmatrix}\right) = (4-\lambda)(3-\lambda) - 1 = 0 127λ+λ21=012 - 7\lambda + \lambda^2 - 1 = 0 λ27λ+11=0\lambda^2 - 7\lambda + 11 = 0 λ=7±49442=7±52\lambda = \frac{7 \pm \sqrt{49 - 44}}{2} = \frac{7 \pm \sqrt{5}}{2} λ1=7+524.618,λ2=7522.382\lambda_1 = \frac{7 + \sqrt{5}}{2} \approx 4.618, \quad \lambda_2 = \frac{7 - \sqrt{5}}{2} \approx 2.382
Step 2: Find eigenvector for λ1\lambda_1: (Aλ1I)v1=0(A - \lambda_1 I)v_1 = 0
[44.6181134.618]v1=[0.618111.618]v1=0\begin{bmatrix} 4-4.618 & 1 \\ 1 & 3-4.618 \end{bmatrix} v_1 = \begin{bmatrix} -0.618 & 1 \\ 1 & -1.618 \end{bmatrix} v_1 = 0
From first row: 0.618v11+v12=0    v12=0.618v11-0.618v_{11} + v_{12} = 0 \implies v_{12} = 0.618v_{11} So
v1=[10.618]v_1 = \begin{bmatrix} 1 \\ 0.618 \end{bmatrix}
, normalized:
v1=11.382[10.618][0.8510.526]v_1 = \frac{1}{\sqrt{1.382}} \begin{bmatrix} 1 \\ 0.618 \end{bmatrix} \approx \begin{bmatrix} 0.851 \\ 0.526 \end{bmatrix}
Step 3: Similarly for λ2\lambda_2:
v2=[0.5260.851]v_2 = \begin{bmatrix} -0.526 \\ 0.851 \end{bmatrix}
Step 4: Verify: VTAV=ΛV^T A V = \Lambda
V=[0.8510.5260.5260.851],VTAV=[4.618002.382]=ΛV = \begin{bmatrix} 0.851 & -0.526 \\ 0.526 & 0.851 \end{bmatrix}, \quad V^T A V = \begin{bmatrix} 4.618 & 0 \\ 0 & 2.382 \end{bmatrix} = \Lambda

1.3 Singular Value Decomposition (SVD)

SVD generalizes eigendecomposition to non-square matrices. Any matrix ARm×nA \in \mathbb{R}^{m \times n} can be decomposed as:
A=UΣVTA = U \Sigma V^T
where:
  • URm×mU \in \mathbb{R}^{m \times m}: Left singular vectors (orthogonal columns, UTU=IU^T U = I)
  • ΣRm×n\Sigma \in \mathbb{R}^{m \times n}: Diagonal matrix of singular values σ1σ2...σr>0\sigma_1 \geq \sigma_2 \geq ... \geq \sigma_r > 0
  • VRn×nV \in \mathbb{R}^{n \times n}: Right singular vectors (orthogonal columns, VTV=IV^T V = I)
  • rr: Rank of AA (number of non-zero singular values)

1.3.1 Intuition

SVD reveals what AA does as a linear transformation:
  1. VTV^T rotates the input to align with a new coordinate system
  2. Σ\Sigma scales each coordinate by σi\sigma_i
  3. UU rotates the result to produce the output (Diagram)

1.3.2 Relationship to Eigendecomposition

For ATAA^T A (a square symmetric matrix):
ATA=(UΣVT)T(UΣVT)=VΣTΣVT=VΛVTA^T A = (U \Sigma V^T)^T (U \Sigma V^T) = V \Sigma^T \Sigma V^T = V \Lambda V^T
So:
  • VV contains eigenvectors of ATAA^T A
  • σi2=λi\sigma_i^2 = \lambda_i (singular values squared = eigenvalues of ATAA^T A) Similarly, UU contains eigenvectors of AATA A^T.

Worked Example 2: SVD of a 2×2 Matrix

Compute SVD of
A=[3113]A = \begin{bmatrix} 3 & 1 \\ 1 & 3 \end{bmatrix}
. Step 1: Compute
ATA=A2=[106610]A^T A = A^2 = \begin{bmatrix} 10 & 6 \\ 6 & 10 \end{bmatrix}
Step 2: Find eigenvalues of ATAA^T A:
det(ATAλI)=(10λ)236=0\det(A^T A - \lambda I) = (10-\lambda)^2 - 36 = 0 λ220λ+64=0\lambda^2 - 20\lambda + 64 = 0 λ=20±4002562=20±122\lambda = \frac{20 \pm \sqrt{400 - 256}}{2} = \frac{20 \pm 12}{2} λ1=16,λ2=4\lambda_1 = 16, \quad \lambda_2 = 4
Singular values: σ1=16=4\sigma_1 = \sqrt{16} = 4, σ2=4=2\sigma_2 = \sqrt{4} = 2 Step 3: Find eigenvectors of ATAA^T A for VV: For λ1=16\lambda_1 = 16:
(ATA16I)v=[6666]v=0    v1=12[11](A^T A - 16I)v = \begin{bmatrix} -6 & 6 \\ 6 & -6 \end{bmatrix}v = 0 \implies v_1 = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ 1 \end{bmatrix}
For λ2=4\lambda_2 = 4:
(ATA4I)v=[6666]v=0    v2=12[11](A^T A - 4I)v = \begin{bmatrix} 6 & 6 \\ 6 & 6 \end{bmatrix}v = 0 \implies v_2 = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ -1 \end{bmatrix}
Step 4: Compute UU: ui=Aviσiu_i = \frac{A v_i}{\sigma_i}
u1=14[3113]12[11]=142[44]=12[11]u_1 = \frac{1}{4} \begin{bmatrix} 3 & 1 \\ 1 & 3 \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ 1 \end{bmatrix} = \frac{1}{4\sqrt{2}}\begin{bmatrix} 4 \\ 4 \end{bmatrix} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ 1 \end{bmatrix} u2=12[3113]12[11]=122[22]=12[11]u_2 = \frac{1}{2} \begin{bmatrix} 3 & 1 \\ 1 & 3 \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ -1 \end{bmatrix} = \frac{1}{2\sqrt{2}}\begin{bmatrix} 2 \\ -2 \end{bmatrix} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ -1 \end{bmatrix}
Step 5: Verify:
A=UΣVT=12[1111][4002]12[1111]A = U \Sigma V^T = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} \begin{bmatrix} 4 & 0 \\ 0 & 2 \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} =[2222]1212[1111]=[2222]12[1111]=[3113]=A= \begin{bmatrix} 2 & 2 \\ 2 & -2 \end{bmatrix} \frac{1}{\sqrt{2}} \cdot \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} = \begin{bmatrix} 2 & 2 \\ 2 & -2 \end{bmatrix} \cdot \frac{1}{2} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} = \begin{bmatrix} 3 & 1 \\ 1 & 3 \end{bmatrix} = A

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

OperationGradient
x(aTx)=a\frac{\partial}{\partial x} (a^T x) = aLinear form
x(xTAx)=(A+AT)x\frac{\partial}{\partial x} (x^T A x) = (A + A^T)xQuadratic form
XTr(AX)=AT\frac{\partial}{\partial X} \text{Tr}(AX) = A^TTrace
Xdet(X)=det(X)(X1)T\frac{\partial}{\partial X} \det(X) = \det(X) (X^{-1})^TDeterminant
$\frac{\partial}{\partial X} \X\

Worked Example 3: Gradient of a Quadratic Form

Compute xf(x)\nabla_x f(x) where f(x)=(xμ)TΣ1(xμ)f(x) = (x - \mu)^T \Sigma^{-1} (x - \mu) (Mahalanobis distance squared). Step 1: Expand: Let y=xμy = x - \mu, then f=yTΣ1yf = y^T \Sigma^{-1} y. Step 2: Using y(yTAy)=(A+AT)y\frac{\partial}{\partial y} (y^T A y) = (A + A^T)y with A=Σ1A = \Sigma^{-1} (which is symmetric):
fy=2Σ1y\frac{\partial f}{\partial y} = 2 \Sigma^{-1} y
Step 3: Chain rule:
xf=fyyx=2Σ1(xμ)1=2Σ1(xμ)\nabla_x f = \frac{\partial f}{\partial y} \cdot \frac{\partial y}{\partial x} = 2 \Sigma^{-1} (x - \mu) \cdot 1 = 2 \Sigma^{-1} (x - \mu)

1.4.2 Gradients of Log-Likelihood for Gaussians

For a multivariate Gaussian p(x)=N(xμ,Σ)p(x) = \mathcal{N}(x|\mu, \Sigma):
logp(x)=12(xμ)TΣ1(xμ)12logΣD2log(2π)\log p(x) = -\frac{1}{2}(x-\mu)^T \Sigma^{-1} (x-\mu) - \frac{1}{2}\log|\Sigma| - \frac{D}{2}\log(2\pi)
Gradient w.r.t. μ\mu:
μlogp(x)=Σ1(xμ)\nabla_\mu \log p(x) = \Sigma^{-1}(x - \mu)
Gradient w.r.t. Σ1\Sigma^{-1} (natural parameterization):
Σ1logp(x)=12((xμ)(xμ)TΣ)\nabla_{\Sigma^{-1}} \log p(x) = \frac{1}{2}\left((x-\mu)(x-\mu)^T - \Sigma\right)
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.
f(λx+(1λ)y)λf(x)+(1λ)f(y)f(\lambda x + (1-\lambda)y) \leq \lambda f(x) + (1-\lambda) f(y)
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)\theta_{t+1} = \theta_t - \eta_t \nabla_\theta \mathcal{L}_B(\theta_t)
where LB\mathcal{L}_B is the loss computed on a mini-batch BB. 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:
mt=β1mt1+(1β1)gt(momentum)m_t = \beta_1 m_{t-1} + (1-\beta_1) g_t \quad \text{(momentum)} vt=β2vt1+(1β2)gt2(RMS)v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2 \quad \text{(RMS)} m^t=mt1β1t,v^t=vt1β2t(bias correction)\hat{m}_t = \frac{m_t}{1-\beta_1^t}, \quad \hat{v}_t = \frac{v_t}{1-\beta_2^t} \quad \text{(bias correction)} θt+1=θtηv^t+ϵm^t\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t
Recommended defaults for generative models:
  • β1=0.9,β2=0.999,η=1e4\beta_1 = 0.9, \beta_2 = 0.999, \eta = 1e-4 (GANs), 3e43e-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:
pθ(x)=pθ(xz)p(z)dzp_\theta(x) = \int p_\theta(x|z) p(z) dz
This integral is intractable for complex models (neural network decoders) because we'd need to integrate over all possible zz.

1.6.2 Introducing the Variational Distribution

We introduce an approximate posterior qϕ(zx)q_\phi(z|x) (the encoder). The goal: make qϕ(zx)q_\phi(z|x) close to the true posterior pθ(zx)p_\theta(z|x).

1.6.3 Derivation Step 1: Start with Log-Likelihood

logpθ(x)=logpθ(xz)p(z)dz\log p_\theta(x) = \log \int p_\theta(x|z) p(z) dz

1.6.4 Derivation Step 2: Multiply by 1 = q/q

logpθ(x)=logqϕ(zx)pθ(xz)p(z)qϕ(zx)dz\log p_\theta(x) = \log \int q_\phi(z|x) \cdot \frac{p_\theta(x|z) p(z)}{q_\phi(z|x)} dz

1.6.5 Derivation Step 3: Apply Jensen's Inequality

For a concave function (log is concave), log(E[y])E[log(y)]\log(\mathbb{E}[y]) \geq \mathbb{E}[\log(y)]:
logpθ(x)=logEzqϕ(zx)[pθ(xz)p(z)qϕ(zx)]Ezqϕ(zx)[logpθ(xz)p(z)qϕ(zx)]\log p_\theta(x) = \log \mathbb{E}_{z \sim q_\phi(z|x)} \left[ \frac{p_\theta(x|z) p(z)}{q_\phi(z|x)} \right] \geq \mathbb{E}_{z \sim q_\phi(z|x)} \left[ \log \frac{p_\theta(x|z) p(z)}{q_\phi(z|x)} \right]
The RHS is the ELBO, denoted L(x;θ,ϕ)\mathcal{L}(x; \theta, \phi).

1.6.6 Derivation Step 4: Rearrange the ELBO

L(x;θ,ϕ)=Eqϕ(zx)[logpθ(xz)]+Eqϕ(zx)[logp(z)qϕ(zx)]\mathcal{L}(x; \theta, \phi) = \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] + \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{p(z)}{q_\phi(z|x)}\right] =Eqϕ(zx)[logpθ(xz)]ReconstructionDKL(qϕ(zx)p(z))KL divergence= \underbrace{\mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)]}_{\text{Reconstruction}} - \underbrace{D_{KL}(q_\phi(z|x) \| p(z))}_{\text{KL divergence}}

1.6.7 Derivation Step 5: The Gap

The gap between the true log-likelihood and the ELBO is the KL divergence between qϕ(zx)q_\phi(z|x) and the true posterior pθ(zx)p_\theta(z|x):
logpθ(x)L(x;θ,ϕ)=DKL(qϕ(zx)pθ(zx))\log p_\theta(x) - \mathcal{L}(x; \theta, \phi) = D_{KL}(q_\phi(z|x) \| p_\theta(z|x))
Proof:
DKL(qϕ(zx)pθ(zx))=Eqϕ(zx)[logqϕ(zx)pθ(zx)]D_{KL}(q_\phi(z|x) \| p_\theta(z|x)) = \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{q_\phi(z|x)}{p_\theta(z|x)}\right] =Eqϕ(zx)[logqϕ(zx)pθ(xz)p(z)/pθ(x)]= \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{q_\phi(z|x)}{p_\theta(x|z) p(z) / p_\theta(x)}\right] =Eqϕ(zx)[logqϕ(zx)pθ(x)pθ(xz)p(z)]= \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{q_\phi(z|x) \cdot p_\theta(x)}{p_\theta(x|z) p(z)}\right] =logpθ(x)+Eqϕ(zx)[logqϕ(zx)pθ(xz)p(z)]= \log p_\theta(x) + \mathbb{E}_{q_\phi(z|x)}\left[\log \frac{q_\phi(z|x)}{p_\theta(x|z) p(z)}\right] =logpθ(x)Eqϕ(zx)[logpθ(xz)]DKL(qϕ(zx)p(z))= \log p_\theta(x) - \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z)) =logpθ(x)L(x;θ,ϕ)= \log p_\theta(x) - \mathcal{L}(x; \theta, \phi)

1.6.8 The Reparameterization Trick

The ELBO requires gradient through Ezqϕ(zx)[logpθ(xz)]\mathbb{E}_{z \sim q_\phi(z|x)}[\log p_\theta(x|z)], but zz is sampled stochastically. Since sampling is non-differentiable, we reparameterize:
z=μϕ(x)+σϕ(x)ϵ,ϵN(0,I)z = \mu_\phi(x) + \sigma_\phi(x) \cdot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)
Now the expectation is over ϵ\epsilon (which doesn't depend on ϕ\phi), and the gradient can flow through μϕ\mu_\phi and σϕ\sigma_\phi:
ϕEzqϕ[logpθ(xz)]=EϵN(0,I)[ϕlogpθ(xμϕ(x)+σϕ(x)ϵ)]\nabla_\phi \mathbb{E}_{z \sim q_\phi}[\log p_\theta(x|z)] = \mathbb{E}_{\epsilon \sim \mathcal{N}(0, I)}[\nabla_\phi \log p_\theta(x | \mu_\phi(x) + \sigma_\phi(x) \cdot \epsilon)]

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

ConceptFormulaApplication in GenAI
EigendecompositionA=VΛVTA = V \Lambda V^T (symmetric)PCA, covariance analysis
SVDA=UΣVTA = U \Sigma V^TLow-rank approximations, latent structure
Quadratic gradientx(xTAx)=2Ax\nabla_x (x^T A x) = 2Ax (A symmetric)Gaussian gradient computation
ELBO$\mathcal{L} = \mathbb{E}q[\log p\theta(xz)] - D_{KL}(q_\phi(z
Reparameterizationz=μ+σϵz = \mu + \sigma \cdot \epsilonDifferentiable sampling
Adam updateθt+1=θtηmtvt+ϵ\theta_{t+1} = \theta_t - \eta \frac{m_t}{\sqrt{v_t}+\epsilon}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), zz takes discrete values and can't be written as μ+σϵ\mu + \sigma \cdot \epsilon with ϵN(0,I)\epsilon \sim \mathcal{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ϕ(zx)q_\phi(z|x) to match the prior p(z)p(z). If the decoder is powerful enough, the model can "ignore" zz and set qϕ(zx)=p(z)q_\phi(z|x) = p(z), resulting in DKL=0D_{KL}=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: fW\frac{\partial f}{\partial W} has the same dimensions as WW, but the chain rule for matrix functions requires attention to transposition. Correct approach: Use dimensional analysis. If f=Wxy2f = \|Wx - y\|^2:
  • ff is scalar
  • WW is dout×dind_{out} \times d_{in}
  • fW=2(Wxy)xT\frac{\partial f}{\partial W} = 2(Wx - y)x^T (check: dout×dind_{out} \times d_{in} ✓)

4. 📝 Practice Questions

**Q1: Compute the eigenvalues of
>A=[2112]>> A = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix} >
and explain what they mean geometrically.**
Step 1: det(AλI)=(2λ)21=λ24λ+3=0\det(A - \lambda I) = (2-\lambda)^2 - 1 = \lambda^2 - 4\lambda + 3 = 0
Step 2: λ=4±16122=4±22\lambda = \frac{4 \pm \sqrt{16 - 12}}{2} = \frac{4 \pm 2}{2}
Step 3: λ1=3\lambda_1 = 3, λ2=1\lambda_2 = 1
Geometric interpretation: AA stretches space by a factor of 3 along eigenvectors corresponding to λ1\lambda_1 and by 1 (no stretch) along eigenvectors corresponding to λ2\lambda_2.
Eigenvectors:
  • λ1=3\lambda_1 = 3: v1=[1,1]T/2v_1 = [1, 1]^T/\sqrt{2} (direction of equal increase)
  • λ2=1\lambda_2 = 1: v2=[1,1]T/2v_2 = [1, -1]^T/\sqrt{2} (direction of difference)
>A=[2112]=VΛVT=12[1111][3001][1111]>> A = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix} = V \Lambda V^T = \frac{1}{2}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} \begin{bmatrix} 3 & 0 \\ 0 & 1 \end{bmatrix} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} >
**Q2: Compute the SVD of
>A=[100020]>> A = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 2 & 0 \end{bmatrix} >
.**
Step 1: AA is 2×32 \times 3, so UU is 2×22 \times 2, Σ\Sigma is 2×32 \times 3, VV is 3×33 \times 3.
Step 2:
>AAT=[1004]>> AA^T = \begin{bmatrix} 1 & 0 \\ 0 & 4 \end{bmatrix} >
, eigenvalues: λ1=4\lambda_1 = 4, λ2=1\lambda_2 = 1.
Singular values: σ1=2\sigma_1 = 2, σ2=1\sigma_2 = 1.
Step 3: UU from eigenvectors of AATAA^T: u1=[0,1]Tu_1 = [0, 1]^T, u2=[1,0]Tu_2 = [1, 0]^T.
Step 4: VV from V=ATUΣ1V = A^T U \Sigma^{-1} (more carefully):
Σ=[diag(2,1),02×1]\Sigma = [\text{diag}(2, 1), 0_{2 \times 1}]
>v1=ATu1σ1=12[100200][01]=12[020]=[010]>> v_1 = \frac{A^T u_1}{\sigma_1} = \frac{1}{2} \begin{bmatrix} 1 & 0 \\ 0 & 2 \\ 0 & 0 \end{bmatrix} \begin{bmatrix} 0 \\ 1 \end{bmatrix} = \frac{1}{2} \begin{bmatrix} 0 \\ 2 \\ 0 \end{bmatrix} = \begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix} >
>v2=ATu2σ2=11[100200][10]=[100]>> v_2 = \frac{A^T u_2}{\sigma_2} = \frac{1}{1} \begin{bmatrix} 1 & 0 \\ 0 & 2 \\ 0 & 0 \end{bmatrix} \begin{bmatrix} 1 \\ 0 \end{bmatrix} = \begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix} >
v3v_3 is in the nullspace of AA (since Av3=0A v_3 = 0): v3=[0,0,1]Tv_3 = [0, 0, 1]^T.
Step 5: Verify:
>UΣVT=[0110][200010][010100001]=[100020]=A>> U \Sigma V^T = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 2 & 0 & 0 \\ 0 & 1 & 0 \end{bmatrix} \begin{bmatrix} 0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix} = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 2 & 0 \end{bmatrix} = A >
Q3: Compute xf\nabla_x f for f(x)=Axb22f(x) = \|Ax - b\|_2^2.
Step 1: Expand: f=(Axb)T(Axb)=xTATAx2bTAx+bTbf = (Ax - b)^T (Ax - b) = x^T A^T A x - 2b^T A x + b^T b
Step 2: Differentiate each term:
  • x(xTATAx)=2ATAx\frac{\partial}{\partial x} (x^T A^T A x) = 2 A^T A x
  • x(2bTAx)=2ATb\frac{\partial}{\partial x} (-2b^T A x) = -2 A^T b
  • x(bTb)=0\frac{\partial}{\partial x} (b^T b) = 0
Step 3: xf=2ATAx2ATb=2AT(Axb)\nabla_x f = 2 A^T A x - 2 A^T b = 2 A^T (Ax - b) Q4: Starting from logp(x)\log p(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:
  1. logp(x)=logp(xz)p(z)dz\log p(x) = \log \int p(x|z) p(z) dz
  2. Introduce q(zx)q(z|x): logp(x)=logq(zx)p(xz)p(z)q(zx)dz\log p(x) = \log \int q(z|x) \frac{p(x|z)p(z)}{q(z|x)} dz
  3. Jensen's inequality: logEq[f]Eq[logf]\log \mathbb{E}_q[f] \geq \mathbb{E}_q[\log f]
  4. Result: logp(x)Eq[logp(xz)]DKL(q(zx)p(z))=ELBO\log p(x) \geq \mathbb{E}_q[\log p(x|z)] - D_{KL}(q(z|x) \| p(z)) = \text{ELBO}
Optimizing θ,ϕ\theta, \phi to maximize the ELBO:
  • Increases the log-likelihood (by at least as much as the ELBO increases)
  • Decreases DKL(qϕ(zx)pθ(zx))D_{KL}(q_\phi(z|x) \| p_\theta(z|x)) (the approximation gap)
The tightness depends on how well qϕ(zx)q_\phi(z|x) approximates the true posterior pθ(zx)p_\theta(z|x). Q5: In the reparameterization trick, why can't we just differentiate through the sampling operation directly?
The sampling operation zqϕ(zx)z \sim q_\phi(z|x) is a stochastic process. The gradient of this operation w.r.t. ϕ\phi would require differentiating through a random number generator, which is non-differentiable.
Concretely, z=sample(μϕ,σϕ)z = \text{sample}(\mu_\phi, \sigma_\phi) involves calling a random number generator to produce ϵN(0,1)\epsilon \sim \mathcal{N}(0, 1), then computing z=μϕ+σϕϵz = \mu_\phi + \sigma_\phi \epsilon. 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 ϵ\epsilon:
z=μϕ(x)+σϕ(x)ϵ,ϵN(0,1)z = \mu_\phi(x) + \sigma_\phi(x) \cdot \epsilon, \quad \epsilon \sim \mathcal{N}(0, 1)
Now:
  • The gradient can flow through μϕ\mu_\phi and σϕ\sigma_\phi (differentiable operations)
  • ϵ\epsilon is independent of ϕ\phi, so no gradient through sampling
  • The expectation is still valid because N(zμ,σ2)dz=N(ϵ0,1)dϵ\mathcal{N}(z|\mu, \sigma^2) dz = \mathcal{N}(\epsilon|0, 1) d\epsilon Q6: For a covariance matrix Σ\Sigma, explain why Σ\Sigma must be positive semidefinite and how eigendecomposition reveals this.
A covariance matrix must be positive semidefinite (PSD) because for any vector vv:
vTΣv=vTE[(Xμ)(Xμ)T]v=E[vT(Xμ)(Xμ)Tv]=E[(vT(Xμ))2]0v^T \Sigma v = v^T \mathbb{E}[(X - \mu)(X - \mu)^T] v = \mathbb{E}[v^T (X - \mu)(X - \mu)^T v] = \mathbb{E}[(v^T (X - \mu))^2] \geq 0
The variance of any linear combination is non-negative.
By eigendecomposition, Σ=VΛVT\Sigma = V \Lambda V^T. PSD means all eigenvalues λi0\lambda_i \geq 0. This is evident because:
  • If any λi<0\lambda_i < 0, then viTΣvi=λi<0v_i^T \Sigma v_i = \lambda_i < 0 (contradiction)
  • The singular values from SVD of the data matrix are λi\sqrt{\lambda_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\eta=0.001, β1=0.9\beta_1=0.9, β2=0.999\beta_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 zz and functioning as an autoencoder with no regularization. The decoder is powerful enough to reconstruct xx without zz, so the KL term forces q(zx)p(z)=N(0,I)q(z|x) \to p(z) = \mathcal{N}(0, I), giving DKL0D_{KL} \approx 0.
Fixes (in order of recommendation):
  1. KL annealing: Start with β=0\beta = 0 in L=ReconβKL\mathcal{L} = \text{Recon} - \beta \cdot KL, gradually increase β\beta from 0 to 1 over training. This lets the model learn meaningful latent representations before the KL penalty kicks in.
  2. Free bits: Set a minimum KL per dimension: KLmin=max(βKL,λ)KL_{\text{min}} = \max(\beta \cdot KL, \lambda). This ensures each dimension carries at least λ\lambda nats of information.
  3. Reduce decoder capacity: A weaker decoder (fewer layers, smaller hidden size) forces the model to use the latent code.
  4. 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 θExpθ[f(x)]=Expθ[f(x)θlogpθ(x)]\nabla_\theta \mathbb{E}_{x \sim p_\theta}[f(x)] = \mathbb{E}_{x \sim p_\theta}[f(x) \nabla_\theta \log p_\theta(x)] (the REINFORCE/score function gradient).
Step 1: Write the expectation as an integral:
θExpθ[f(x)]=θf(x)pθ(x)dx\nabla_\theta \mathbb{E}_{x \sim p_\theta}[f(x)] = \nabla_\theta \int f(x) p_\theta(x) dx
Step 2: Swap gradient and integral (under smoothness conditions):
=f(x)θpθ(x)dx= \int f(x) \nabla_\theta p_\theta(x) dx
Step 3: Use the log-derivative trick: θpθ(x)=pθ(x)θlogpθ(x)\nabla_\theta p_\theta(x) = p_\theta(x) \nabla_\theta \log p_\theta(x)
=f(x)pθ(x)θlogpθ(x)dx= \int f(x) p_\theta(x) \nabla_\theta \log p_\theta(x) dx
Step 4: Recognize as an expectation:
=Expθ[f(x)θlogpθ(x)]= \mathbb{E}_{x \sim p_\theta}[f(x) \nabla_\theta \log p_\theta(x)]
This is the REINFORCE gradient estimator or score function estimator. It allows gradient estimation through non-differentiable sampling by using logpθ(x)\log p_\theta(x) instead of θx\nabla_\theta x.
Comparison with reparameterization:
  • Reparameterization: Lower variance, but requires continuous xx and differentiable ff
  • REINFORCE: Higher variance, but works for discrete xx and non-differentiable ff Q9: For a multivariate Gaussian N(μ,Σ)\mathcal{N}(\mu, \Sigma), derive the gradient of the log-likelihood with respect to μ\mu for a single sample xx.
Step 1: Write the log-likelihood:
logp(xμ,Σ)=12(xμ)TΣ1(xμ)12logΣD2log(2π)\log p(x|\mu, \Sigma) = -\frac{1}{2}(x-\mu)^T \Sigma^{-1} (x-\mu) - \frac{1}{2}\log|\Sigma| - \frac{D}{2}\log(2\pi)
Step 2: Only the first term depends on μ\mu:
μlogp(xμ,Σ)=12μ[(xμ)TΣ1(xμ)]\nabla_\mu \log p(x|\mu, \Sigma) = -\frac{1}{2} \nabla_\mu [(x-\mu)^T \Sigma^{-1} (x-\mu)]
Step 3: Let y=xμy = x - \mu. Then yμ=I\frac{\partial y}{\partial \mu} = -I.
Step 4: y(yTΣ1y)=2Σ1y\frac{\partial}{\partial y} (y^T \Sigma^{-1} y) = 2\Sigma^{-1} y (since Σ1\Sigma^{-1} is symmetric)
Step 5: Chain rule:
μlogp=12(yTΣ1y)yyμ=12(2Σ1y)T(I)=yTΣ1=(xμ)TΣ1\nabla_\mu \log p = -\frac{1}{2} \cdot \frac{\partial (y^T \Sigma^{-1} y)}{\partial y} \cdot \frac{\partial y}{\partial \mu} = -\frac{1}{2} \cdot (2\Sigma^{-1} y)^T \cdot (-I) = y^T \Sigma^{-1} = (x-\mu)^T \Sigma^{-1}
In column-vector convention: μlogp=Σ1(xμ)\nabla_\mu \log p = \Sigma^{-1} (x - \mu).
The MLE for μ\mu sets this gradient to zero: Σ1(μ^xavg)=0    μ^=1Nxi\Sigma^{-1} (\hat{\mu} - x_{\text{avg}}) = 0 \implies \hat{\mu} = \frac{1}{N}\sum x_i, 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=0m_0 = 0, v_0 = 0:
mt=β1mt1+(1β1)gtm_t = \beta_1 m_{t-1} + (1-\beta_1) g_t
In early iterations, mtm_t is "warmed up" from 0. For β1=0.9\beta_1 = 0.9:
  • t=1t=1: m1=0.90+0.1g1=0.1g1m_1 = 0.9 \cdot 0 + 0.1 \cdot g_1 = 0.1 g_1 (10% of true gradient)
  • t=5t=5: m50.41gavgm_5 \approx 0.41 g_{\text{avg}} (still biased)
  • t=20t=20: m200.88gavgm_{20} \approx 0.88 g_{\text{avg}} (approaching true)
Bias correction divides by 1β1t1 - \beta_1^t:
m^t=mt1β1t\hat{m}_t = \frac{m_t}{1 - \beta_1^t}
  • t=1t=1: m^1=0.1g1/(10.9)=g1\hat{m}_1 = 0.1 g_1 / (1 - 0.9) = g_1
  • t=5t=5: m^50.41gavg/(10.95)=0.41/0.41gavg\hat{m}_5 \approx 0.41 g_{\text{avg}} / (1 - 0.9^5) = 0.41 / 0.41 \approx g_{\text{avg}}
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ϕ(zx)p(z))D_{KL}(q_\phi(z|x) \| p(z)) with respect to ϕ\phi where qϕ(zx)=N(μϕ,σϕ2)q_\phi(z|x) = \mathcal{N}(\mu_\phi, \sigma_\phi^2) and p(z)=N(0,1)p(z) = \mathcal{N}(0, 1).
Step 1: Write the KL in closed form for Gaussians:
DKL(N(μ,σ2)N(0,1))=log1σ+σ2+μ2212D_{KL}(\mathcal{N}(\mu, \sigma^2) \| \mathcal{N}(0, 1)) = \log\frac{1}{\sigma} + \frac{\sigma^2 + \mu^2}{2} - \frac{1}{2}
=logσ+σ2+μ2212= -\log\sigma + \frac{\sigma^2 + \mu^2}{2} - \frac{1}{2}
Step 2: Differentiate w.r.t. μ\mu:
KLμ=μ\frac{\partial KL}{\partial \mu} = \mu
Step 3: Differentiate w.r.t. σ\sigma (using σ\sigma as the standard deviation):
KLσ=1σ+σ=σ1σ=σ21σ\frac{\partial KL}{\partial \sigma} = -\frac{1}{\sigma} + \sigma = \sigma - \frac{1}{\sigma} = \frac{\sigma^2 - 1}{\sigma}
Step 4: In practice, we parameterize logσ2\log\sigma^2 (log-variance) for numerical stability. Let s=logσ2s = \log\sigma^2, so σ=es/2\sigma = e^{s/2}:
KLs=KLσσs=(σ1σ)es/22=(es/2es/2)es/22\frac{\partial KL}{\partial s} = \frac{\partial KL}{\partial \sigma} \cdot \frac{\partial \sigma}{\partial s} = \left(\sigma - \frac{1}{\sigma}\right) \cdot \frac{e^{s/2}}{2} = \left(e^{s/2} - e^{-s/2}\right) \cdot \frac{e^{s/2}}{2}
=es12=σ212= \frac{e^s - 1}{2} = \frac{\sigma^2 - 1}{2}
The gradient tells us:
  • If μ>0\mu > 0, push μ\mu toward zero (reduce mean)
  • If σ>1\sigma > 1, push σ\sigma toward 1 (reduce variance)
  • If σ<1\sigma < 1, push σ\sigma 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]\mathcal{L} = \mathbb{E}_{t, x_0, \epsilon}[\|\epsilon - \epsilon_\theta(x_t, 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(xt1xt,x0)pθ(xt1xt))]\mathcal{L}_{vb} = \sum_{t=1}^T \mathbb{E}_{x_0, \epsilon_t}[D_{KL}(q(x_{t-1}|x_t, x_0) \| p_\theta(x_{t-1}|x_t))]
Each KL term is between two Gaussians:
  • q(xt1xt,x0)=N(μ~t(xt,x0),β~tI)q(x_{t-1}|x_t, x_0) = \mathcal{N}(\tilde{\mu}_t(x_t, x_0), \tilde{\beta}_t I) (the forward posterior, known)
  • pθ(xt1xt)=N(μθ(xt,t),σt2I)p_\theta(x_{t-1}|x_t) = \mathcal{N}(\mu_\theta(x_t, t), \sigma_t^2 I) (the model, learned)
Using the closed-form KL for Gaussians:
DKL(qpθ)=12σt2μ~t(xt,x0)μθ(xt,t)2+constD_{KL}(q \| p_\theta) = \frac{1}{2\sigma_t^2} \|\tilde{\mu}_t(x_t, x_0) - \mu_\theta(x_t, t)\|^2 + \text{const}
We parameterize μθ\mu_\theta as:
μθ(xt,t)=1αt(xtβt1αˉtϵθ(xt,t))\mu_\theta(x_t, t) = \frac{1}{\sqrt{\alpha_t}} \left(x_t - \frac{\beta_t}{\sqrt{1-\bar{\alpha}_t}} \epsilon_\theta(x_t, t)\right)
And the forward posterior mean is:
μ~t(xt,x0)=1αt(xtβt1αˉtϵt)\tilde{\mu}_t(x_t, x_0) = \frac{1}{\sqrt{\alpha_t}} \left(x_t - \frac{\beta_t}{\sqrt{1-\bar{\alpha}_t}} \epsilon_t\right)
Substituting, the KL simplifies to:
DKL(qpθ)ϵtϵθ(xt,t)2D_{KL}(q \| p_\theta) \propto \|\epsilon_t - \epsilon_\theta(x_t, t)\|^2
Thus, the diffusion training loss ϵϵθ(xt,t)2\|\epsilon - \epsilon_\theta(x_t, 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
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.