Skip to content
samit
Interviews/Math Foundations

Math Foundations

20 questions

20 questions
Linear Algebra
What is an eigenvector/eigenvalue? Why do they matter in ML?▶

Av = λv - multiplying matrix A by eigenvector v only scales it (by λ), never changes its direction.

  • PCA: eigenvectors of the covariance matrix are the principal components (directions of max variance). Eigenvalues = variance explained in each direction. Sort descending, take top-k.
  • RNN stability: a recurrent network blows up if the spectral radius (largest eigenvalue magnitude) of the weight matrix > 1. Gradient clipping and orthogonal init address this.
  • Kernel SVMs: the kernel matrix must be PSD (all eigenvalues ≥ 0). Indefinite kernels break the dual formulation.
  • Covariance matrices are always PSD - all eigenvalues ≥ 0 because xTCx = ||X x||2 ≥ 0.

Note: PCA on MNIST - first eigenvector captures global brightness, later ones capture strokes. Draw this connection to what each dimension "means."

Explain SVD and its applications in ML.frontier▶

A = UΣVT where U (m×m) and V (n×n) are orthogonal, Σ (m×n) is diagonal with non-negative singular values σ1 ≥ σ2 ≥... ≥ 0.

  • Dimensionality reduction: keep top-k columns of U, V and top-k singular values. Minimizes reconstruction error (Eckart-Young theorem).
  • Recommender systems: matrix factorization of user-item rating matrix.
  • PCA connection: right singular vectors V = eigenvectors of ATA. Singular values σi = √λi.
  • Pseudo-inverse: A† = VΣ†UT - solves least squares even for non-square/singular matrices.
  • Why not eigendecomposition: SVD works on any m×n matrix; eigendecomposition requires square symmetric. SVD is more numerically stable.
Why divide attention scores by √d_k? Derive it.frontier▶

If Q and K components are drawn from N(0,1), then the dot product Q·K = Σ qiki has variance dk (sum of dk independent unit-variance terms).

With large dk (e.g., 64), the dot products have high magnitude. After softmax, this creates near one-hot distributions where almost all attention goes to one token. The gradient through softmax then vanishes (softmax is nearly flat everywhere except the peak).

Dividing by √dk normalizes variance to 1 regardless of dk, keeping softmax in a region where gradients flow cleanly.

Follow-up: What if you use dk=1? Then the softmax is very flat - model loses ability to attend sharply. The √d_k scaling is the right tradeoff.

What is the Jacobian? The Hessian? When do you use each in ML?frontier▶

Jacobian Jij = ∂fi/∂xj - matrix of first-order partial derivatives for vector-valued functions. Shape: (output_dim, input_dim).

Hessian Hij = ∂²L/∂xi∂xj - matrix of second-order partial derivatives of a scalar loss. Shape: (params, params).

  • Jacobian in backprop: the chain rule is a product of Jacobians. ∂L/∂x = (∂y/∂x)T · ∂L/∂y.
  • Hessian for analysis: positive definite H = local minimum; indefinite = saddle point. Eigenvalues of H = curvature in each direction.
  • Why Hessian is rarely used for training: O(n²) to compute, O(n²) to store for n parameters. Newton's method uses H-1g - infeasible for billions of params. Approximations: L-BFGS, K-FAC (Kronecker factored).
How are matrix multiplications used inside a single Transformer layer?frontier▶

For input X of shape [batch, seq_len, d_model]:

  • Q = X @ W_Q → [batch, seq_len, d_k] - project to query space
  • K = X @ W_K → [batch, seq_len, d_k] - project to key space
  • V = X @ W_V → [batch, seq_len, d_v] - project to value space
  • scores = Q @ K.T / sqrt(d_k) → [batch, seq_len, seq_len] - pairwise compatibility
  • out = softmax(scores) @ V → [batch, seq_len, d_v] - weighted aggregation
  • out = out @ W_O → [batch, seq_len, d_model] - output projection
  • ffn = Linear(ReLU(Linear(out))) → two more matrix multiplications

Total per Transformer block: ~8 matrix multiplications. The attention matrix QKT is the only O(n²) operation - the bottleneck for long sequences.

What is the rank of a matrix? Why does low rank matter in LoRA?▶

Rank = number of linearly independent rows (or columns). Rank-r means the matrix can be expressed as a sum of r outer products.

LoRA insight: when fine-tuning LLMs, the weight update matrix ΔW has low intrinsic rank. Rather than learning a full d×d update (d=4096 → 16M params), LoRA learns ΔW = BA where A is (d×r) and B is (r×d) with r=4 to 64.

  • Parameters reduced: 2dr vs d² (e.g., r=16, d=4096: 131K vs 16M)
  • Merge at inference: W' = W + αBA - zero added latency
  • Hypothesis: task-specific adaptation lives in a low-dimensional subspace of weight space
Explain orthogonality. Why do we want weight matrices to be orthogonal?▶
  • Orthogonal matrix: WTW = I. Columns are unit vectors, pairwise perpendicular.
  • Norm preservation: ||Wx|| = ||x|| - orthogonal matrices are isometries. They rotate/reflect but don't scale.
  • In deep networks: an orthogonal weight matrix has all singular values = 1. This prevents both vanishing (σ < 1) and exploding (σ > 1) gradients through layers.
  • Orthogonal initialization: initialize W as a random orthogonal matrix (QR decomposition of random Gaussian). Proven to help with deep networks.
  • Spectral normalization: divide W by its largest singular value σmax at each step. Used in GANs (discriminator Lipschitz constraint).
Derive why PCA is the eigendecomposition of the covariance matrix.▶

Center the data: X ∈ ℝn×d with zero column means. Covariance C = (1/n) XᵀX, a d×d symmetric PSD matrix.

Goal: find the unit direction w that maximises the variance of the projections Xw:

maximise wᵀCw   subject to   ‖w‖ = 1.

Lagrangian: L = wᵀCw − λ(wᵀw − 1). Set ∂L/∂w = 2Cw − 2λw = 0:

Cw = λw - the optimal w is an eigenvector of C, and the variance it captures is wᵀCw = λ. So the top eigenvalue is the maximum-variance direction; subsequent principal components are the next eigenvectors (orthogonal, by symmetry of C), in descending λ.

Via SVD (what you actually compute): X = UΣVᵀ ⟹ C = (1/n)VΣ²Vᵀ. The right singular vectors V are the principal components and σ²/n are the variances. SVD of X is numerically more stable than forming C explicitly.

Note: on MNIST the first eigenvector ≈ global brightness, later ones capture strokes. That lets you say what each retained dimension "means," not just that you ran PCA.

Probability & Statistics
MLE vs MAP estimation - when do they coincide? What are they equivalent to in regularization?▶

MLE: θ* = argmax P(data|θ) - parameters that maximize likelihood of observed data.

MAP: θ* = argmax P(data|θ)·P(θ) = argmax [log-likelihood + log-prior]

  • They coincide when the prior is uniform (flat) - then log-prior is a constant and doesn't affect the argmax.
  • MAP with Gaussian prior P(θ) ∝ exp(-||θ||²/2σ²) → adds -λ||θ||² to log-likelihood → L2 / Ridge regularization
  • MAP with Laplace prior P(θ) ∝ exp(-|θ|/b) → adds -λ||θ||₁ → L1 / LASSO regularization

So regularization is Bayesian inference with different priors - L2 says you believe weights are Gaussian around 0; L1 says you believe they're sparse.

Explain KL divergence. Is it symmetric? Forward vs reverse KL - when to use each?frontier▶

KL(P||Q) = Σ P(x) log(P(x)/Q(x)) - "how much extra information you need to encode P using Q instead of P itself." Always ≥ 0. Equals 0 iff P=Q.

Not symmetric: KL(P||Q) ≠ KL(Q||P) in general.

  • Forward KL (I-projection, mode-covering): KL(P||Q). Q must cover all modes of P - if P has probability mass somewhere Q doesn't, you get ∞ loss. Used in VAE decoder, SFT (cross-entropy loss).
  • Reverse KL (M-projection, mode-seeking): KL(Q||P). Q concentrates on peaks of P. Produces mode-seeking behavior - Q might ignore some modes of P. Used in PPO (KL penalty from reference policy), variational inference.

Practical: In RLHF, the KL penalty KL(π||π_ref) is reverse KL - the new policy stays near the reference policy at the modes it's already good at.

Explain bias-variance tradeoff.▶

For a model f̂ trained on dataset D:

MSE = Bias² + Variance + Irreducible Noise

  • Bias: error from wrong assumptions in the model. High-bias = underfitting (linear model for nonlinear data).
  • Variance: sensitivity to training data fluctuations. High-variance = overfitting (memorizes training set).

Complex models (deep nets, many parameters): low bias, high variance. Simple models (linear regression): high bias, low variance. Regularization reduces variance at cost of some bias.

Twist: deep nets with SGD can have low bias AND surprisingly low variance (double descent phenomenon). Traditional tradeoff breaks for very overparameterized models.

What is entropy? How does it relate to cross-entropy loss?▶

Entropy H(P) = -Σ P(x) log P(x) - average surprise / uncertainty of distribution P. Maximized by uniform distribution, 0 for deterministic distribution.

Cross-entropy H(P,Q) = -Σ P(x) log Q(x) - average bits needed to encode P-distributed data using code optimized for Q.

Relationship: H(P,Q) = H(P) + KL(P||Q)

The cross-entropy loss in classification: L = -Σ yi log p̂i where y is one-hot true label, p̂ is predicted probability. This equals H(y, p̂). Minimizing cross-entropy = minimizing KL divergence from true distribution (H(y) is fixed - it's 0 for one-hot labels).

State Bayes' theorem. Why does it matter for ML?▶

P(H|E) = P(E|H) · P(H) / P(E)

Posterior = Likelihood × Prior / Evidence

  • Naive Bayes classifier: P(class|features) ∝ P(features|class)·P(class)
  • Bayesian neural networks: maintain a distribution over weights instead of point estimates - better uncertainty quantification
  • MAP estimation: mode of posterior = combining likelihood with prior (see MLE vs MAP)
  • Calibration: a well-calibrated model's confidence should match Bayesian posterior probabilities
Type I vs Type II errors. Map to precision and recall.▶
  • Type I (false positive): rejecting true null hypothesis. e.g., spam filter marks legitimate email as spam. Rate = 1 - Precision.
  • Type II (false negative): failing to reject false null hypothesis. e.g., spam filter misses actual spam. Rate = 1 - Recall = FNR.

In ML: you control the tradeoff via decision threshold. Lower threshold → more positives → fewer false negatives (higher recall) but more false positives (lower precision). The ROC curve and PR curve visualize this.

When to prioritize: Medical diagnosis - minimize Type II (miss no cancer); spam filter - minimize Type I (don't block legitimate email).

What is the Central Limit Theorem and why does it matter for ML?▶

The sum (or mean) of n independent, identically distributed random variables approaches a normal distribution as n → ∞, regardless of the original distribution. Mean → population mean, variance → σ²/n.

  • Mini-batch gradient estimates: each mini-batch estimate of the gradient is approximately normal for large batch sizes
  • Statistical testing: comparing two models' performance - can use t-tests because sample means are approximately normal
  • Confidence intervals: model accuracy ± margin of error relies on CLT
  • Why SGD works: noise in gradient estimates is approximately Gaussian, which has nice theoretical properties
Explain p-values and their limitations for ML evaluation.▶

p-value: probability of observing data at least as extreme as what you got, assuming the null hypothesis is true.

p < 0.05 means: if null were true, you'd see this only 5% of the time. It does NOT mean: 95% chance the hypothesis is correct.

Limitations in ML:

  • Multiple comparisons: test 20 models - expect 1 to hit p<0.05 by chance. Use Bonferroni correction.
  • Effect size ignored: p=0.001 for a 0.01% accuracy improvement is statistically but not practically significant
  • Data leakage: repeated evaluation on same test set inflates apparent significance
  • Better alternatives: bootstrapped confidence intervals, effect size (Cohen's d), held-out test sets
Calculus & Optimization
Derive the gradient of cross-entropy loss w.r.t. logits.frontier▶

Let z be logits, p = softmax(z), y be one-hot target. Loss L = -Σ yi log pi.

Compute ∂pj/∂zi using softmax derivative:

  • If j = i: ∂pi/∂zi = pi(1 - pi)
  • If j ≠ i: ∂pj/∂zi = -pjpi

Applying chain rule: ∂L/∂zi = -Σj yj/pj · ∂pj/∂zi = pi - yi

This beautiful result: gradient is simply predictions minus one-hot labels. For the correct class it's pc-1, for others it's pj. This is why cross-entropy + softmax is the universal classification loss.

Explain gradient descent variants: SGD, Momentum, RMSprop, Adam.▶
  • SGD: θ ← θ - α·∇L. Simple. Noisy with single samples. Full-batch = slow. Mini-batch = good tradeoff.
  • Momentum: v ← βv + ∇L; θ ← θ - αv. Accumulates gradient direction. Dampens oscillations, accelerates in consistent directions. Like a ball rolling downhill with inertia. β=0.9 typical.
  • RMSprop: v ← βv + (1-β)∇L²; θ ← θ - α·∇L/√(v+ε). Adapts learning rate per-parameter based on recent gradient magnitude. Good for RNNs.
  • Adam = Momentum + RMSprop: m ← β₁m + (1-β₁)g; v ← β₂v + (1-β₂)g²; θ ← θ - α·m̂/√(v̂+ε). Bias-corrected (divides by 1-β^t at start). β₁=0.9, β₂=0.999, ε=1e-8.
  • AdamW: Adam with weight decay applied directly to weights, not gradient estimate. Standard for LLMs.
Why do vanishing gradients happen? What fixes them?▶

Backprop multiplies Jacobians through each layer. If each layer's Jacobian has spectral radius < 1, the product → 0 exponentially fast. For sigmoid: derivative max is 0.25; after 10 layers, gradient ~ 0.25^10 ≈ 10^-6.

Fixes:

  • ReLU: gradient = 1 when active (no saturation). Propagates gradient unchanged.
  • Residual connections: gradient can flow directly through identity skip. Even if F(x) has small gradient, the total gradient ≥ 1.
  • Batch/Layer normalization: normalizes activations, preventing saturation in sigmoid/tanh regions.
  • Proper initialization: Xavier/He keeps variance constant across layers.
  • LSTM/GRU: cell state highway with near-identity gradient through forget gate.
What is a saddle point? Are they actually a problem?frontier▶

A saddle point has ∇L = 0 but is neither a minimum nor maximum - some directions curve up, some down (Hessian has positive and negative eigenvalues).

In high dimensions: most critical points are saddle points, not local minima. For a d-dimensional problem, local minima require ALL d eigenvalues of the Hessian to be positive. The probability of this decreases exponentially with d.

Are they a problem in practice? Not really:

  • SGD noise helps escape saddle points
  • Near saddle points, loss is still decreasing in many directions
  • Local minima in deep nets tend to have similar loss to global minima (Goodfellow et al. 2015)

The real concern is flat regions / plateaus, not saddle points.