Whiteboard Derivations — Deep Dive
Frontier-lab interview prep. Pair with
INTERVIEW_GRILL.md.
This deep dive is the catalog of derivations you should be able to do on a whiteboard cold. Frontier-lab interviews routinely ask “derive X” — backprop, attention, OLS gradient, KL, EM, DPO. Knowing the shape of these derivations beats memorizing the answer.
This is a meta-document that points to the relevant deep dive for each derivation while listing the key steps you need to recite.
1. Backpropagation for a 2-layer MLP
Setup: , , , , .
Steps:
-
Cross-entropy + softmax simplification (the magic step — derive it, don’t just assert):
Softmax Jacobian: .
.
(using ).
So .
-
.
-
.
-
.
-
.
-
.
Key insights:
- Cross-entropy + softmax simplifies dramatically: gradient is just . The mess from softmax’s Jacobian and CE’s cancel.
- Chain rule: each layer multiplies by (transpose) and .
See 31_neural_networks/.
Saying it out loud (narrate while you write). “I’ll write the forward pass across the top first, so I always have something to point at. Now backwards. The magic step is the last layer, so let me actually derive it rather than assert it: the softmax Jacobian is
y-hat_itimesdelta_ij minus y-hat_j, and cross-entropy contributesminus y_i over y-hat_i. Multiply them and they-hat_icancels — I’m left withminus y_j plus y-hat_jtimes the sum ofy, which is one becauseyis a distribution. So delta-2 is justy-hat minus y.” Then the mechanical part, and say the pattern out loud: every layer does the same three things — the weight gradient is the incoming delta times the layer’s input transposed, the bias gradient is just the delta, and to push further back you multiply byWtranspose and gate by the activation derivative. Land it on shapes: ifdWdoesn’t come out the same shape asW, you’ve transposed something, and that’s the single most common whiteboard slip here.
2. Scaled dot-product attention
Setup: .
Steps:
- .
- .
- .
Why : variance of entries scales with if have unit-variance entries. Divide by to keep variance at 1 → softmax doesn’t saturate.
Multi-head: project to heads of dim ; do attention per head; concatenate; project back.
See 04_transformers/, 05_attention_mechanisms/.
Saying it out loud (narrate while you write). “Three lines and then I’ll justify the scaling. Scores are
Q Ktranspose over rootd— I’ll draw the box,LbyL, and say what it is: tokeni’s row tells me how much it attends to every other token. Softmax along that row, over keys, so each row sums to one. Then timesV, which contracts the sequence dimension and hands me backLbyd_v.” Now the question they always ask: “Why rootd? Because a dot product of twod-dimensional unit-variance vectors has varianced, so the raw scores grow like rootd. Feed those into a softmax and it saturates into a near one-hot, where the gradient is essentially zero. Dividing by rootdputs the variance back at 1.” Close with the cost: thatLbyLbox is quadratic in time and memory, which is the reason every long-context trick exists.
3. OLS closed form
Setup: .
Steps:
- .
- Set to zero: .
- Solve: (assuming invertible).
Hessian: — PSD always; PD if has full column rank.
Geometric: where is the projection onto .
See 24_linear_algebra_qa/, 48_optimization_and_matrix_calculus/.
Saying it out loud (narrate while you write). “Half the squared residual norm, and I want the gradient, so I’ll expand it:
ytransposeyminus2 wtransposeXtransposeypluswtransposeXtransposeX w, all over two. Differentiating, the linear term givesminus Xtransposeyand the quadratic givesXtransposeX w— so the gradient isXtranspose times the residual, negated. Set it to zero and you get the normal equations.” Then say the thing that scores: “the Hessian isXtransposeX, which is positive semi-definite for anyX, so this problem is convex and the stationary point is the global minimum — and it’s strictly positive definite, hence uniquely solvable, exactly whenXhas full column rank.” Finish geometrically: the fitted values are an orthogonal projection ofyonto the column space ofX, which is why the residual is perpendicular to every feature. And name the failure mode: collinear features makeXtransposeXsingular, which is why you solve with QR or add ridge rather than literally inverting.
4. Logistic regression gradient
Setup: , .
Steps:
- (combine fractions).
- (sigmoid derivative).
- Chain rule — the magic cancellation: . The from sigmoid derivative kills the in the denominator from CE — that’s the GLM canonical-link beauty.
- (since , ).
Key insight: same gradient form as linear regression (residual times input) — that’s why these models feel the same. Hessian is , always PSD → loss convex.
See 01_classical_ml/, 37_mle_map_estimation/.
Saying it out loud (narrate while you write). “Chain rule through the sigmoid, and I’ll show the cancellation because that’s the whole point. Differentiating binary cross-entropy with respect to
pgivesminus y over p plus one minus y over one minus p; over a common denominator that’sp minus yon top andp times one minus punderneath. Now the sigmoid derivative isp times one minus p” — write it directly below — “so multiplying, those cancel” — strike them out — “anddL/dzisp minus y. Timesdz/dw, which isx, gives residual times input.” Then land the two payoffs: it’s the same form as linear regression, which is the canonical-link property of generalized linear models, and the Hessian is a sum ofp(1-p) x xtranspose, which is PSD, so the loss is convex and there are no local minima to worry about. Named failure mode to mention: on separable data that convex loss has no finite minimizer, so the weights diverge unless you regularize.
5. KL divergence
In plain language: KL divergence is a number that says how badly one probability distribution stands in for another. If you built a code assuming distribution q but reality is p, KL is the extra bits you waste per symbol. It’s zero only when the two match, and it is not symmetric, so the order of the arguments genuinely matters.
Definition: .
Properties:
-
, with equality iff (Gibbs’ inequality). Proof via Jensen (memorize this — most-asked):
. Since is concave, Jensen’s inequality gives . So , i.e. . Equality iff is constant, i.e. (since both are distributions).
-
Asymmetric: .
-
Forward KL (): mean-seeking. MLE.
-
Reverse KL (): mode-seeking. Variational inference.
MLE = forward KL minimization: — the entropy term is constant.
See 33_information_theory/, 37_mle_map_estimation/.
Saying it out loud (narrate while you write). “KL is the expected log-likelihood ratio under
p— the average number of extra bits I pay for using the wrong distribution. Two facts to prove, both quick. It’s non-negative: I’ll write minus KL, which is the expectation oflog q over p, and sincelogis concave, Jensen lets me pull the expectation inside the log” — write it — “givinglogof the sum ofq, which islog 1, which is zero. So minus KL is at most zero, hence KL is at least zero, with equality only when the ratio is constant, meaning the distributions are identical.” Then the asymmetry, said with the consequence: “forward KL is the MLE direction and it’s mass-covering —pis out there whereqis near zero, the log ratio explodes, soqis forced to smear over everything. Reverse KL is what variational inference minimizes and it’s mode-seeking —qis penalized for putting mass wherephas none, so it collapses onto one mode.” That’s the named tradeoff: blurry-but-inclusive versus sharp-but-incomplete, and it’s exactly why VAEs blur and reverse-KL variational fits drop modes.
6. EM for GMM
In plain language: EM is what you do when your model has a hidden label you never observe — like which cluster each point came from. You alternate between guessing the hidden labels using your current parameters, and refitting your parameters as if those guesses were true. This section is mostly about why that loop can’t make things worse.
Setup: .
E-step: posterior responsibilities
M-step: weighted MLE updates
Why EM converges (the key identity to memorize):
For any distribution :
So always, with equality iff .
- E-step: set (the posterior responsibilities ). KL = 0 → bound is tight: .
- M-step: maximize over (since is fixed, this is just weighted MLE). raises the bound.
- Net: . Likelihood non-decreasing → bounded above → converges.
See 19_advanced_clustering/.
Saying it out loud (narrate while you write). “The problem is circular: if I knew which Gaussian each point came from I could fit the Gaussians, and if I knew the Gaussians I could assign the points. EM just alternates. The E-step computes soft assignments — the responsibility is the prior times the density, normalized over components, which is Bayes’ rule. The M-step is ordinary maximum likelihood with those responsibilities as weights: each mean is a weighted average of the points, each covariance a weighted scatter, each mixing weight the share of total responsibility.” Then the part interviewers are actually testing — why it converges: “write the log-likelihood as the ELBO plus a KL term. The E-step sets
qto the exact posterior, which drives that KL to zero and makes the bound tight. The M-step then raises the bound. Since the bound was touching the likelihood before the step and can only have gone up, the likelihood is non-decreasing, and it’s bounded above, so it converges.” Land on the failure modes: convergence is to a local optimum, so initialization matters, and a component can collapse onto a single point, sending its variance to zero and the likelihood to infinity — which is why you floor the covariance.
7. PCA via SVD
Setup: centered .
Steps:
- Center the data, compute covariance: .
- SVD of centered : with , .
- Substitute and simplify: (using — that’s the load-bearing step). So — this is the eigendecomposition of .
- Top- principal directions: columns of . Variances along them: .
- Reduced data: (project data onto top- directions).
Eckart-Young: truncated SVD minimizes .
See 21_dimensionality_reduction/.
Saying it out loud (narrate while you write). “PCA asks for the directions of maximum variance, which are the top eigenvectors of the covariance matrix — but I’d never actually form the covariance matrix, and here’s why. Take the SVD of the centered data,
XequalsU S Vtranspose. Now computeXtransposeX” — write it out — “theV S Utranspose timesU S Vtranspose, and becauseUhas orthonormal columns,UtransposeUis the identity and vanishes. What’s left isV S squared Vtranspose, which is the eigendecomposition, read straight off.” So the principal directions are the columns ofV, the variances are the singular values squared overn, and the projected data isU_k S_k. Then the reason to prefer this route: formingXtransposeXsquares the condition number and loses precision, while the SVD works onXdirectly. Close on Eckart-Young — truncating the SVD gives the provably best rank-kapproximation in Frobenius norm, which is why this one decomposition underlies PCA, LSA, and low-rank compression alike.
8. SVM dual
In plain language: the SVM dual is a rewrite. Instead of solving for a weight vector directly, you solve for one weight per training point, and the answer turns out to depend on the data only through pairwise dot products. That rewrite is what makes kernels possible, and it’s the whole reason anyone bothers.
Primal: s.t. .
Lagrangian: .
Steps:
- .
- (constraint on ).
- Substitute back into — this is the load-bearing step:
- .
- (the full quadratic).
- (using ).
- stays.
- Combining: .
Dual: s.t. .
Kernel trick: replace with . The dual is the only place data enters as inner products — perfect for kernels.
KKT — support vectors: complementary slackness gives only for points where (on margin); for soft-margin with , for margin violators.
See 35_kernel_functions/, 48_optimization_and_matrix_calculus/.
Saying it out loud (narrate while you write). “The primal is minimize half the squared norm of
wsubject to every point being on the right side of the margin. I’ll form the Lagrangian with one multiplier alpha per constraint. Take the derivative with respect towand set it to zero:wequals the sum ofalpha_i y_i x_i— so the solution is a weighted combination of the training points, which is already the interesting part. Derivative with respect tobgives the constraint that thealpha yterms sum to zero.” Then the load-bearing move: “substitutew-star back in. The quadratic term gives me half the double sum, the constraint term gives me the full double sum with the opposite sign, so they combine to minus a half, thebterm dies becausealpha ysums to zero, and the plus-ones survive as sum of alpha.” Land the two payoffs: the data appears only as inner productsx_itransposex_j, so you swap in a kernel and get nonlinear boundaries for free, and complementary slackness means alpha is nonzero only for points sitting exactly on the margin — those are the support vectors, and everything else could be deleted without changing the answer.
9. RoPE rotation
In plain language: RoPE encodes a token’s position by rotating its query and key vectors by an angle proportional to that position. The trick is that when you later take a dot product between two rotated vectors, the absolute angles cancel and only the difference survives — so the model sees relative position for free.
Goal: encode relative position via rotation in 2D subspaces.
Setup: pair up dimensions; for pair , apply rotation by to position :
with .
Property: . Inner product depends only on the relative position .
Why this works (the algebra to memorize):
- .
- Rotations are orthogonal, so .
- Rotations also compose by adding angles: .
- Therefore — a function of only.
This is what makes attention self-positionally-aware in a relative way without any added position embeddings to the input.
See 14_advanced_positional_embeddings/.
Saying it out loud (narrate while you write). “Instead of adding a position vector, RoPE rotates. I pair up the dimensions, treat each pair as a point in a plane, and rotate the pair at position
mby anglem theta, with a different frequency theta for each pair — fast rotations for early dimensions, slow ones for later, so together they encode position across many scales. Now here’s why it gives relative position.” Write the inner product: “R_m qdotted withR_n kisqtransposeR_mtransposeR_n k. Rotation matrices are orthogonal, so the transpose is the inverse, which is rotation by minusm. And rotations compose by adding angles, soR_minus-mtimesR_nisR_(n minus m).” Land it: the attention score depends only onnminusm, never on absolute position, which is why RoPE extrapolates far better than learned absolute embeddings — and the named failure mode is that it still degrades past the training context length, which is exactly what NTK scaling and YaRN interpolate around.
10. DPO (direct preference optimization)
In plain language: DPO is RLHF with the reinforcement learning taken out. The usual pipeline trains a reward model and then optimizes against it; DPO shows that if you write down the optimal policy in closed form, the reward can be expressed in terms of the policy itself, so you can train straight from preference pairs with an ordinary classification loss.
Starting point: RLHF objective with KL regularization to a reference policy:
Step 1 — derive the closed-form optimal policy. Set up Lagrangian on the constrained max (with ). Setting gives , where is from the normalization Lagrange multiplier. Cleaning up:
with — depends only on prompt , not on .
Step 2 — invert for :
Step 3 — substitute into Bradley-Terry: . Critically, depends on only — it appears identically in both reward terms and cancels in the subtraction.
Step 4 — final DPO loss (NLL of preferences):
Key insight: closed-form optimal policy + depending only on prompt = reward model eliminates itself. No RL loop, no rollouts, just a supervised classification loss on preferences.
See 08_training_techniques/.
Saying it out loud (narrate while you write). “The starting objective is standard RLHF: maximize reward, minus beta times the KL to a reference policy so you don’t drift into gibberish. Step one — this constrained problem has a closed-form solution. Set up the Lagrangian with the normalization constraint, take the functional derivative, and you get that the optimal policy is the reference policy tilted by
expof reward over beta, divided by a partition functionZ of x. Step two — and this is the trick — invert that: the reward equals beta times the log ratio of policy to reference, plus beta logZ. Step three, plug it into Bradley-Terry, which models the probability that one response is preferred as a sigmoid of the reward difference. And hereZ of xdepends only on the prompt, so it appears in both rewards identically and cancels in the subtraction” — strike it out. “What’s left has no reward model in it at all: just a log-sigmoid of the difference of log-ratios on the chosen and rejected responses.” Land the tradeoff: you gain enormous simplicity and stability by dropping the RL loop and the rollouts, and you lose online exploration — DPO only ever sees the fixed preference dataset, which is why on-policy methods still tend to win at the frontier.
11. Variational lower bound (ELBO)
In plain language: the ELBO is a workaround for an integral you can’t compute. The quantity you actually want, the probability of the data with the hidden variable summed out, is intractable, so you build a lower bound on it that you can compute and maximize that instead. Pushing the bound up pushes the real thing up with it.
Setup: latent-variable model . Want to maximize .
Trick: introduce variational distribution and use Jensen’s:
Jensen’s inequality for concave : . Apply it:
This is the ELBO.
Equivalent form (split ):
The gap to true log-likelihood: — exactly the KL between approximate and true posterior. ELBO is tight when matches the true posterior.
Reconstruction term + KL-to-prior term. The VAE objective.
See 21_dimensionality_reduction/ (autoencoders), 33_information_theory/.
Saying it out loud (narrate while you write). “I want the log-likelihood, but it has an integral over the latent inside a log, which is hopeless. So I multiply and divide by a distribution
qof my choosing — that turns the integral into an expectation underq. Nowlogis concave, so Jensen’s inequality lets me swap the log and the expectation and only lose something:logof an expectation is at least the expectation of the log.” Write the bound. “That’s the ELBO, and rearranged it’s a reconstruction term minus the KL fromqto the prior — the VAE objective, exactly.” Then the identity that scores: “the gap between the true log-likelihood and the ELBO is precisely the KL between my approximate posterior and the true one. So maximizing the bound does two jobs at once — it fits the model and it dragsqtoward the true posterior — and the bound is tight exactly when they coincide.” Named failure mode: posterior collapse, whereqjust becomes the prior, the KL term goes to zero, and the latent carries no information at all.
12. Bias-variance decomposition
Setup: estimate from random training set . Evaluate at fixed .
Steps:
- Let .
- Add and subtract: .
- Cross-term vanishes: take . and are constants w.r.t. , so (by definition of ).
- .
- Now take over the noise in : first term becomes . Second term is .
See 27_advanced_theory/, 52_statistical_learning_theory/.
Saying it out loud (narrate while you write). “The whole derivation is one add-and-subtract. Imagine retraining on many different datasets and let
f-barbe the average prediction at this point. Write the squared error and insertminus f-bar plus f-barin the middle” — write it — “expand the square into three terms. Now take the expectation over datasets: the cross term hasf-bar minus f-hatin it, and by definition the average off-hatisf-bar, so that expectation is zero and the cross term vanishes.” That’s the trick, and it’s the same trick as in the variance identity. “What’s left is a squared gap between the average model and the truth — that’s bias, the error you’d still have with infinite datasets — plus the spread of the models around their own average, which is variance. Then letycarry noise, and that contributes an irreducible sigma-squared.” Land it with the intuition and the caveat: a straight line through a curve has high bias and low variance, a wiggly polynomial the reverse, and the classical U-curve says balance them — while modern over-parameterized networks descend a second time past the interpolation point, so treat the U as intuition, not law.
13. Information gain (decision tree split)
Setup: dataset with class labels.
Entropy: .
After split on feature into :
Information gain: .
Key identity: — IG is exactly the mutual information between class label and feature . That makes it intuitive: pick the feature that’s most informative about the label.
Why : conditioning never increases entropy (Jensen on concave , applied to ). Equality iff .
Tree picks the split that maximizes IG (or Gini decrease in CART).
Gini: . Computationally cheaper (no log); similar selection.
See 26_tree_based_methods/.
Saying it out loud (narrate while you write). “A decision tree wants the split that most reduces uncertainty about the label. Entropy measures that uncertainty, so I write
H of S, then the entropy after splitting on a feature — which is just the weighted average of the children’s entropies, weighted by how many points fall into each. Information gain is the difference.” Then the identity that makes it click: “that difference is exactly the mutual information between the label and the feature, so I’m literally picking the feature that tells me the most about the class.” And why it’s never negative: conditioning can’t increase entropy on average, so gain is at least zero, with equality only when the feature is independent of the label. Close with the practical tradeoff: Gini does essentially the same job without computing logarithms, which is why CART uses it, and raw information gain is biased toward high-cardinality features — a unique ID column gets perfect gain and zero generalization, which is what gain ratio corrects.
14. Common interview gotchas
| Question | Common wrong answer | Right answer |
|---|---|---|
| What’s in attention? | Tradition | Variance scaling — keeps QK product unit-variance |
| Cross-entropy + softmax gradient? | Complicated | . Beautifully simple. |
| Why does EM converge? | Gradient descent | Each E-step gives lower bound; M-step maximizes; likelihood monotone |
| What does ELBO bound? | Posterior | Log-marginal-likelihood from below |
| KL forward vs reverse? | Same | Forward mode-covering (MLE); reverse mode-seeking (VI) |
| SVM dual support vectors? | Random points | Points where ; on/violating margin |
| RoPE relative property? | Magic | depends only on |
Saying it out loud. The pattern across this table is that every one of these has a one-line reason, and interviewers are checking whether you know the reason or just the result. Root
dis variance control, not tradition. Thepminusygradient is a cancellation you can derive in two lines. EM converges because each step tightens then raises a lower bound, not because it’s doing gradient descent. ELBO bounds the log-marginal-likelihood from below, not the posterior. And forward versus reverse KL is the difference between blurring across all the modes and collapsing onto one. If you can say the why in a sentence for each row, you’re ready for the follow-up rather than just the question.
15. Eight derivations to drill cold
- 2-layer MLP backprop with cross-entropy + softmax.
- Scaled dot-product attention with multi-head + masking.
- OLS gradient + closed form with PSD Hessian.
- Logistic regression gradient showing convexity.
- EM for GMM: E-step posterior, M-step updates.
- DPO loss from RLHF + Bradley-Terry.
- ELBO derivation via Jensen’s inequality.
- Bias-variance decomposition.
For each: 5 minutes on a whiteboard. Until automatic.
Saying it out loud. When I’m at a whiteboard I say the plan before I write anything: what I’m deriving, what I’m allowed to assume, and roughly how many steps it’ll take. Then I narrate every line while my hand moves, because silence reads as being stuck and an interviewer can’t give you a nudge if they don’t know where you are. Each of these eight has one load-bearing step — the softmax-cross-entropy cancellation, substituting
w-star back into the Lagrangian, the vanishing cross term in bias-variance, the partition function cancelling in DPO — so I make sure I can name that step before I start, and if I blank on the algebra I say what the step is supposed to accomplish and keep going. Budget five minutes each. The failure mode this avoids is the real one: not getting it wrong, but freezing.
16. Drill plan
- 1 derivation per day for 8 days. Then cycle.
- Time yourself: 5 min per derivation cold; 3 min after a week of practice.
- Practice teaching each: explain to an imaginary interviewer.
- Pair the derivation with the relevant deep dive’s “8 most-asked interview questions” to make sure you can recite both proof and intuition.
17. Further reading
This deep dive is a meta-collection. The full derivations live in:
31_neural_networksfor backprop.04_transformersand05_attention_mechanismsfor attention.01_classical_mlfor OLS and logistic.19_advanced_clusteringfor EM.08_training_techniquesfor DPO.21_dimensionality_reductionfor ELBO/VAE.27_advanced_theoryfor bias-variance.
Drill the derivations in those locations and you’ll be ready for the whiteboard rounds.