Self-assessment: interview-grade questions¶
A bank of 158 questions across every track of this site, of the kind asked in research-engineer, ML-engineer and applied-AI interviews, each with a model answer and a link to the page that teaches it. The idea to walk away with: you understand something when you can explain it out loud, with the numbers, to someone who keeps asking "why?".
10,000 ft
Reading a page gives you the feeling of understanding; answering a question you have not seen, from memory, is the test of it. Cognitive science calls this retrieval practice: recalling an answer strengthens memory more than re-reading it (how to study AI so it sticks). These questions cover the whole field at the depth interviewers probe: the maths behind each idea, why it is designed the way it is, what breaks when you change it, and the numbers a practitioner carries in their head. They pair with the project ladder: the projects make you build, the questions make you explain.
2,000 ft
Pick a track. Read a question, close your eyes, and answer out loud or on paper in two to four sentences, including any formula or number the question asks for. Only then open the model answer and grade yourself: 2 if you were complete and precise, 1 if you had the idea but missed a step or number, 0 if you could not answer. Follow the link on every 0 or 1, re-read that section, and schedule the question again (the Build it section has a short scheduler). Aim for a 2 on every question in the tracks you care about; a 1 on the rest is a strong position.
Ground level¶
How to use this bank¶
- Answer before you look. Opening the answer first trains recognition, which is exactly the illusion this page exists to break.
- Say the number. Many answers include a figure (the variance of a dot product, bytes per parameter for Adam, Chinchilla's tokens per parameter). Interviewers use numbers to distinguish people who have done the work from people who have read about it.
- Go one "why" deeper. After each answer, ask "why is that true?" once more. If you cannot answer the follow-up, grade yourself 1.
- Mix tracks. Interleaving topics is harder and more effective than doing one track at a time.
Questions are ordered within each track from foundational to hard. Hard questions are marked; they are the ones that separate strong candidates.
Mathematical foundations¶
Why is the dot product a similarity measure, and when should you use cosine similarity instead?
\(\mathbf{a}\cdot\mathbf{b} = \lVert\mathbf{a}\rVert\lVert\mathbf{b}\rVert\cos\theta\): it grows with alignment but also with length. Cosine divides out both lengths and measures direction only. Use cosine when vector length carries no meaning for the comparison (most text embeddings); for unit-normalised vectors the two are identical, which is why vector stores often normalise once and use the cheaper dot product. Taught in: vectors and geometry
What does the determinant of a square matrix tell you geometrically, and what does a zero determinant mean for a linear layer?
It is the signed factor by which the map scales volume (area in 2-D); the sign says whether orientation flips. Zero means some direction is squashed to nothing: the map loses information, is not invertible, and its outputs live in a lower-dimensional subspace. Taught in: matrices as linear maps
How are SVD and PCA related? Say exactly where the principal directions and their variances come from.
Centre the data matrix \(X\) (\(n\) rows) and take \(X = U\Sigma V^\top\). The principal directions are the columns of \(V\) (equivalently the eigenvectors of the covariance \(X^\top X/(n-1)\)), and the variance along direction \(i\) is \(\sigma_i^2/(n-1)\). Projecting onto the first \(k\) columns of \(V\) gives the best rank-\(k\) reconstruction in squared error. Taught in: eigenvectors, SVD and PCA
What is the shape of A + B when A is (32, 1, 64) and B is (8, 64)? State the rule.
(32, 8, 64). Broadcasting aligns shapes from the right; B is treated as (1, 8, 64); each dimension pair must be equal or contain a 1, which is stretched. Silent broadcasting is a classic source of bugs, for example a (B,) vector minus a (B, 1) vector producing a (B, B) matrix. Taught in: tensors, shapes and broadcasting
Why does the gradient point in the direction of steepest ascent?
The rate of change of \(f\) in a unit direction \(\mathbf{u}\) is \(\nabla f\cdot\mathbf{u}\). By Cauchy–Schwarz it is at most \(\lVert\nabla f\rVert\), reached exactly when \(\mathbf{u}\) is parallel to \(\nabla f\). So the negative gradient is the steepest local descent, which says nothing about where the minimum is, and is why curvature (step size, conditioning) matters. Taught in: derivatives and gradients
Derive the Jacobian of softmax.
With \(s_i = e^{z_i}/\sum_k e^{z_k}\): \(\partial s_i/\partial z_j = s_i(\delta_{ij} - s_j)\), so \(J = \operatorname{diag}(\mathbf{s}) - \mathbf{s}\mathbf{s}^\top\). It is symmetric and singular (adding a constant to all logits changes nothing, so \(J\mathbf{1} = 0\)). Combined with cross-entropy, the gradient collapses to \(\mathbf{s} - \mathbf{y}\). Taught in: chain rule and Jacobians
A test is 99% sensitive and 95% specific; the condition has 1% prevalence. If you test positive, what is the probability you have it?
\(P(D\mid +) = \frac{0.99\times0.01}{0.99\times0.01 + 0.05\times0.99} = \frac{0.0099}{0.0594} \approx 0.167\). About one in six: false positives from the 99% healthy population outnumber true positives. The same base-rate logic governs any rare-event classifier, from fraud detection to content moderation. Taught in: probability from first principles
Show that maximum likelihood for a classifier is the same as minimising cross-entropy.
The average negative log-likelihood of the data under model \(q\) is \(-\frac{1}{n}\sum_i \log q(y_i\mid x_i)\), which is the cross-entropy between the empirical distribution of labels and \(q\). Maximising likelihood therefore minimises cross-entropy, and since \(H(p, q) = H(p) + \mathrm{KL}(p\Vert q)\) with \(H(p)\) fixed, also minimises KL from the data to the model. Taught in: estimation, information theory
Why is MAP estimation with a Gaussian prior equivalent to L2 regularisation?
MAP maximises \(\log p(\text{data}\mid w) + \log p(w)\). With \(w \sim \mathcal{N}(0, \sigma^2 I)\), \(\log p(w) = -\lVert w\rVert^2/(2\sigma^2) + \text{const}\), so MAP minimises the negative log-likelihood plus \(\lambda\lVert w\rVert^2\) with \(\lambda = 1/(2\sigma^2)\) (in the likelihood's units). A narrower prior means stronger regularisation; a Laplace prior gives L1. Taught in: MLE, MAP and Bayes
KL divergence is asymmetric. Which direction does maximum likelihood minimise, and what behaviour does that produce? (Hard)
MLE minimises forward KL, \(\mathrm{KL}(p_{\text{data}}\Vert q)\), which is infinite wherever the data has mass and \(q\) has none, so \(q\) spreads to cover every mode (mass-covering, sometimes blurry). Reverse KL, \(\mathrm{KL}(q\Vert p)\), penalises \(q\) for putting mass where \(p\) has none, so it locks onto one mode (mode-seeking). The KL penalty in RLHF is a reverse-direction term, \(\mathrm{KL}(\pi\Vert\pi_{\text{ref}})\). Taught in: entropy, cross-entropy and KL
What is the log-sum-exp trick and why is it exact?
\(\log\sum_i e^{x_i} = m + \log\sum_i e^{x_i - m}\) with \(m = \max_i x_i\). It is an algebraic identity (factor out \(e^m\)), so nothing is approximated; it just keeps every exponent at most 0, preventing overflow, and keeps the largest term exactly 1, preventing total underflow. Every softmax and cross-entropy implementation uses it. Taught in: floating point and log-sum-exp
Why is bfloat16 preferred to float16 for training?
Both use 16 bits, but bf16 keeps float32's 8 exponent bits (same range, about \(10^{\pm38}\)) with 7 mantissa bits, while fp16 has 5 exponent bits (max 65,504, underflow below about \(6\times10^{-8}\)) and 10 mantissa bits. Gradients span many orders of magnitude, so fp16 needs loss scaling to avoid underflow; bf16 rarely does, trading away precision that SGD noise swamps anyway. Taught in: numerical computing, mixed precision
If a loss is convex, why is any local minimum global? Are neural-network losses convex?
If \(w\) were a local but not global minimum, the segment from \(w\) to a better point \(w^*\) would, by convexity, lie on or below the chord, giving points arbitrarily close to \(w\) with lower loss, a contradiction. Neural-network losses are not convex (permuting hidden units alone creates many equivalent minima), yet in high dimensions most critical points are saddles, and wide networks find good minima reliably. Taught in: optimisation: convex and not
Model A scores 82% and model B 80% on the same 500 test items. Is A better? (Hard)
Not established. The standard error of each accuracy is about \(\sqrt{0.8\times0.2/500} \approx 1.8\) points, and the unpaired difference has SE about 2.5 points, so a 2-point gap is within noise. Because both models answered the same items, use a paired test (McNemar on the items where they disagree), which is more powerful; and report a confidence interval, not just the two numbers. Taught in: statistics for experiments and evals
Classical machine learning¶
State the bias–variance decomposition of squared error.
For \(y = f(x) + \varepsilon\) with noise variance \(\sigma^2\), the expected error of a learned \(\hat f\) at \(x\), over training sets, is \(\mathbb{E}[(y - \hat f(x))^2] = (\mathbb{E}\hat f(x) - f(x))^2 + \operatorname{Var}(\hat f(x)) + \sigma^2\): bias squared, variance, irreducible noise. Flexible models lower bias and raise variance; regularisation, more data and averaging lower variance. Taught in: bias, variance and regularisation
Why does L1 regularisation produce exact zeros and L2 does not?
The L1 penalty's (sub)gradient has constant magnitude \(\lambda\) however small the weight, so it can push a weight all the way to zero and hold it there when the data gradient is smaller than \(\lambda\). L2's gradient \(2\lambda w\) shrinks with the weight, so weights approach zero but do not reach it. Geometrically, the L1 ball has corners on the axes where the loss contours tend to touch it first. Taught in: bias, variance and regularisation
Why train logistic regression with cross-entropy rather than mean squared error?
Cross-entropy with a sigmoid is convex in the weights and its gradient is simply \((p - y)\mathbf{x}\): large when confidently wrong. MSE through a sigmoid is non-convex and its gradient carries a factor \(p(1-p)\) that vanishes exactly when the model is confidently wrong, so learning stalls where it is needed most. Taught in: logistic regression
Give two realistic examples of data leakage and how you would detect them.
Fitting a scaler or imputer on the full dataset before splitting (test statistics leak into training); features that are only known after the label (a "refund issued" flag when predicting fraud); duplicate or near-duplicate records across splits; random splits of time series. Detect by suspiciously high validation scores, feature-importance spikes on one odd feature, and by re-running with a strict time-based or group-based split. Taught in: metrics, validation and leakage
On a fraud dataset with 0.5% positives, why is accuracy useless and what do you report instead?
Predicting "not fraud" for everything scores 99.5%. Report precision, recall and the precision–recall curve (PR-AUC), choose an operating threshold from the business cost of false positives versus false negatives, and report results at that threshold. ROC-AUC can look flattering under heavy imbalance because the false-positive rate's denominator is huge. Taught in: metrics, validation and leakage
In what sense is gradient boosting gradient descent?
It performs gradient descent in function space: each new tree is fitted to the negative gradient of the loss with respect to the current predictions (for squared error, the residuals), and added with a small learning rate. Shrinkage and many shallow trees play the role of small steps; early stopping on validation loss plays the role of regularisation. Taught in: trees and ensembles
Why does a random forest decorrelate its trees, and what does correlation do to the variance of an average? (Hard)
For \(B\) identically distributed predictors with variance \(\sigma^2\) and pairwise correlation \(\rho\), the variance of their average is \(\rho\sigma^2 + \frac{1-\rho}{B}\sigma^2\). More trees kill only the second term; the first stays. Bootstrap samples and random feature subsets at each split lower \(\rho\), which is what makes averaging effective. Taught in: trees and ensembles
What is the kernel trick?
Algorithms that use data only through inner products (SVMs, ridge regression, PCA) can replace \(\mathbf{x}\cdot\mathbf{x}'\) with \(k(\mathbf{x}, \mathbf{x}') = \phi(\mathbf{x})\cdot\phi(\mathbf{x}')\), working implicitly in a feature space that may be infinite-dimensional (the RBF kernel) without ever computing \(\phi\). The cost moves to the \(n\times n\) kernel matrix, which is why kernel methods struggle beyond tens of thousands of points. Taught in: kernels and SVMs
Describe EM for a Gaussian mixture and what it guarantees.
E-step: compute each point's responsibility for each component given current parameters. M-step: re-estimate weights, means and covariances as responsibility-weighted averages. Each iteration never decreases the data log-likelihood (it maximises a lower bound that touches the likelihood at the current parameters), so EM converges, but only to a local optimum; k-means is its hard-assignment, equal-variance limit. Taught in: clustering, mixtures and EM
Why should you not read distances between clusters in a t-SNE plot?
t-SNE preserves local neighbourhoods by matching neighbour probabilities, with a heavy-tailed distribution in the embedding that deliberately exaggerates separation. Cluster sizes and inter-cluster distances are largely artefacts of perplexity and optimisation; only "these points are near each other" is reliable. UMAP is similar in this respect. Taught in: PCA, t-SNE and UMAP
What is double descent, and why did it surprise classical learning theory? (Hard)
As model size grows, test error first follows the U-shape, peaks near the interpolation threshold (just enough parameters to fit the training data exactly), then falls again as models grow further. Classical bounds tie generalisation to capacity and predict monotonic overfitting; the second descent shows that among the many interpolating solutions, training finds smooth ones (implicit regularisation). Taught in: learning theory
How should you cross-validate a model on time-series data?
Never shuffle. Use forward-chaining splits: train on the past, validate on the next window, roll forward; optionally leave a gap so features computed over windows do not straddle the boundary. Random K-fold leaks the future into training and overstates accuracy. Taught in: metrics, validation and leakage
Which models need feature scaling, and which do not?
Anything based on distances (k-NN, k-means, RBF kernels) or trained by gradient descent with a shared step size (linear models, neural networks) is sensitive to feature scale; standardise using training-set statistics only. Tree-based models split on thresholds of one feature at a time and are invariant to monotonic transformations. Taught in: features and tabular data
Deep learning¶
Why can a network with no non-linear activations not learn XOR, however deep it is?
A composition of linear (affine) maps is a single affine map, so the whole network is a linear classifier, and XOR's classes are not linearly separable. One hidden layer with any non-linearity suffices. Taught in: neurons, perceptrons and MLPs
If one hidden layer is a universal approximator, why use deep networks?
Universality says nothing about how many units are needed or whether training finds them. Some functions need exponentially many units with one layer but polynomially many with depth, because depth composes features (edges, then parts, then objects). Deep networks are also empirically easier to train to good solutions with residual connections and normalisation. Taught in: neurons and MLPs
Roughly how expensive is backpropagation relative to the forward pass, and why?
About twice the forward pass, so a training step costs about three forward passes (the source of the \(6N\) FLOPs-per-token rule: 2 forward, 4 backward). For each matrix multiply the backward pass needs two products of the same size: one for the gradient with respect to the input, one for the weights. Taught in: backpropagation, compute maths
Why do sigmoid networks suffer from vanishing gradients?
\(\sigma'(x) = \sigma(x)(1-\sigma(x)) \le 0.25\), and it is near zero when the unit saturates. Backpropagating through \(L\) sigmoid layers multiplies the gradient by at most \(0.25^L\) (times weight factors), so early layers barely learn. ReLU's derivative is 1 for positive inputs, and residual connections add an identity path. Taught in: activation functions
What is a dead ReLU and how do you prevent it?
A unit whose pre-activation is negative for every input outputs 0 with gradient 0, so it never updates again, often after a large step pushes its bias very negative. Prevent with sensible initialisation, moderate learning rates and warm-up, normalisation, or activations with non-zero negative slope (Leaky ReLU, GELU, SiLU). Taught in: activation functions
What variance should you initialise ReLU-layer weights with, and where does the number come from?
He initialisation, \(\operatorname{Var}(w) = 2/\text{fan-in}\). Keeping activation variance constant across layers requires \(\text{fan-in}\cdot\operatorname{Var}(w)\cdot\mathbb{E}[\text{act}^2]/\operatorname{Var}(\text{pre-act}) = 1\); ReLU zeroes half its inputs, halving the second moment, so the factor 2 compensates. Xavier/Glorot (\(1/\text{fan-in}\), or \(2/(\text{fan-in}+\text{fan-out})\)) suits tanh. Taught in: initialisation and normalisation
Why do transformers use LayerNorm rather than BatchNorm?
BatchNorm normalises each feature across the batch, so its statistics depend on batch composition, behave differently at training and inference, and are awkward with variable-length sequences and small or sharded batches. LayerNorm (and RMSNorm) normalise each token's feature vector on its own, so behaviour is identical for any batch and at generation time. Taught in: initialisation and normalisation
Write the Adam update and explain the bias correction.
\(m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t\), \(v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2\), \(\hat m_t = m_t/(1-\beta_1^t)\), \(\hat v_t = v_t/(1-\beta_2^t)\), \(\theta_t = \theta_{t-1} - \eta\,\hat m_t/(\sqrt{\hat v_t} + \epsilon)\). Both moments start at zero, so early estimates are biased towards zero; dividing by \(1-\beta^t\) removes that bias. The per-parameter division makes the step size roughly invariant to the gradient's scale. Taught in: optimisers
What does AdamW change relative to Adam with L2 regularisation, and why does it matter?
With L2 in the loss, the decay term \(\lambda w\) is part of the gradient and gets divided by \(\sqrt{\hat v}\), so parameters with large gradient history are barely regularised. AdamW applies decay directly to the weights, \(\theta \leftarrow \theta - \eta\lambda\theta\), separately from the adaptive step, so every weight decays at the same rate. It generalises better and is the default for transformers. Taught in: optimisers
How does inverted dropout work, and what happens at inference?
During training each activation is zeroed with probability \(p\) and the survivors are scaled by \(1/(1-p)\), so the expected activation is unchanged. At inference nothing is dropped and nothing is scaled. Forgetting model.eval() leaves dropout on at inference, a common source of noisy evaluations. Taught in: regularisation
How many parameters does a 3×3 convolution from 64 to 128 channels have, and why so few compared with a dense layer?
\(3\times3\times64\times128 + 128 = 73{,}856\). The same small kernel is applied at every spatial position (weight sharing) and connects only to a local neighbourhood, encoding the priors that local patterns matter and can appear anywhere. A dense layer between two \(32\times32\) feature maps of those widths would need about \(8.6\times10^9\) weights. Taught in: convolutional networks
Why does an LSTM handle long-range dependencies better than a vanilla RNN?
A vanilla RNN's gradient through time is a product of Jacobians that repeatedly multiplies by the recurrent weight matrix and activation derivatives, so it vanishes or explodes exponentially. The LSTM's cell state is updated additively, \(c_t = f_t\odot c_{t-1} + i_t\odot\tilde c_t\); with forget gates near 1 the gradient flows back nearly unchanged. Taught in: RNNs and LSTMs
Why do residual connections make very deep networks trainable?
With \(x_{l+1} = x_l + F(x_l)\), \(\partial x_{l+1}/\partial x_l = I + \partial F/\partial x_l\): the identity term gives the gradient a direct path to every earlier layer, so it neither vanishes nor needs every block to be well conditioned. Each block also only has to learn a correction, and an untrained block starts close to the identity. Taught in: residual networks
Your loss does not go down at all. What are the first five things you check?
(1) Overfit a single small batch: if impossible, the bug is in the model, loss or optimiser wiring. (2) Initial loss against \(\ln(\text{classes})\). (3) Inputs and labels as the model sees them (decode a batch; check alignment and normalisation). (4) Learning rate and that parameters are actually in the optimiser and receiving non-zero gradients. (5) Shapes and broadcasting in the loss (for example, a wrong axis in cross-entropy). Taught in: a recipe for training
What is an embedding layer, mathematically, and how is it trained?
A lookup into a matrix \(E \in \mathbb{R}^{V\times d}\): row \(i\) is token \(i\)'s vector, identical to multiplying a one-hot vector by \(E\). It is trained by backpropagation like any weight; only the rows of tokens present in the batch receive gradient. Vectors end up close when tokens appear in similar contexts, the distributional idea behind word2vec. Taught in: embeddings
Transformers and LLMs¶
Why are attention scores divided by √d_k?
If query and key entries have unit variance, \(q\cdot k\) is a sum of \(d_k\) products with variance \(d_k\). Without scaling, large heads produce scores with standard deviation \(\sqrt{d_k}\), the softmax saturates towards one-hot, and its gradients vanish. Dividing by \(\sqrt{d_k}\) restores unit variance at initialisation. Taught in: attention
What is the time and memory complexity of self-attention in sequence length T, and what does FlashAttention change?
\(O(T^2 d)\) compute and \(O(T^2)\) memory for the score matrix per head. FlashAttention computes exactly the same result in tiles, using an online softmax, so the \(T\times T\) matrix is never written to slow GPU memory: memory becomes \(O(T)\) and speed improves because attention was memory-bandwidth-bound. The compute stays quadratic. Taught in: attention, efficient attention
Why use many attention heads of size d/h rather than one head of size d?
The cost is the same (the projections total \(d\times d\) either way), but each head computes its own softmax, so \(h\) heads can attend to \(h\) different positions for different reasons (syntax, previous token, a matching name) at once. One head produces one weighted average per position and must blend those relations. Taught in: multi-head attention
What is the difference between pre-LN and post-LN transformers, and why did pre-LN win?
Post-LN (the 2017 original) normalises after adding the residual: \(x = \operatorname{LN}(x + F(x))\). Pre-LN normalises inside the branch: \(x = x + F(\operatorname{LN}(x))\), leaving a clean identity path through the residual stream. Pre-LN has well-behaved gradients at initialisation and trains deep stacks without delicate warm-up; post-LN can reach slightly better results but is harder to train. Taught in: the transformer block
How many parameters are in one transformer block of width d (ignoring biases and norms)?
About \(12d^2\): \(4d^2\) for the Q, K, V and output projections and \(8d^2\) for an MLP that expands to \(4d\) and back. With \(L\) layers, \(12Ld^2\) plus the embeddings; for GPT-2 small (\(d = 768\), \(L = 12\)) that is 85M in the blocks plus 38.6M in the token embedding. Gated MLPs (SwiGLU) use three matrices at a smaller expansion to keep the total similar. Taught in: the transformer block
What property makes RoPE encode relative position?
RoPE rotates each pair of query and key dimensions by an angle proportional to the token's position. The dot product of a query rotated by \(m\theta\) and a key rotated by \(n\theta\) depends only on \((m - n)\theta\), so attention scores depend on relative offset while positions are injected without adding anything to the residual stream. Taught in: positional encoding
Why do LLMs struggle to count the letters in a word like 'strawberry'?
The model never sees letters: a BPE tokeniser turns the word into one to three subword tokens, so letter counts must be inferred from memorised spelling knowledge about those tokens rather than read off the input. Character-level tasks, arithmetic on long numbers and some multilingual text suffer for the same reason. Taught in: tokenisation and BPE
Define perplexity and convert a loss of 2.0 nats per token into it.
Perplexity is the exponential of the average negative log-likelihood per token: \(\exp(2.0) \approx 7.4\). It is the effective number of equally likely choices the model is torn between at each step. It is only comparable between models with the same tokeniser; across tokenisers, compare bits per character or byte. Taught in: the language-modelling objective
How does a decoder-only model train on every position of a sequence in one forward pass?
The causal mask stops position \(t\) from attending to positions after \(t\), so the outputs at all \(T\) positions are valid next-token predictions computed in parallel (teacher forcing: the true previous tokens are the input). One sequence of length \(T\) gives \(T\) training examples for the price of one pass, which is a large part of why transformers train so efficiently. Taught in: the language-modelling objective
What did Chinchilla find about compute-optimal training, and what is the rule of thumb?
For a fixed compute budget \(C \approx 6ND\), loss is minimised by growing parameters \(N\) and tokens \(D\) in roughly equal proportion, about 20 tokens per parameter. Hoffmann et al. showed that earlier models such as Gopher were undertrained; their 70B Chinchilla, trained on 1.4T tokens, beat the 280B Gopher with the same compute. Taught in: scaling laws
Why do labs now train small models on far more than 20 tokens per parameter? (Hard)
Chinchilla optimises training compute only. A model is trained once but served billions of times, and inference cost scales with parameter count, so it pays to "overtrain" a smaller model: extra training compute buys a model that is cheaper for its whole life. Loss keeps improving with more tokens, just less efficiently than with a bigger model. Taught in: scaling laws
Estimate the KV-cache size per token for a 32-layer model with 32 heads of size 128 in fp16, and for 4,096 tokens.
Per token: \(2\,(\text{K and V})\times32\times32\times128\times2\text{ bytes} = 524{,}288\) bytes, 0.5 MiB. For 4,096 tokens, 2 GiB per sequence, comparable to a large share of the weights at long context. This is why grouped-query attention, cache quantisation and PagedAttention exist. Taught in: KV cache and efficient attention
What do multi-query and grouped-query attention change, and what do they trade?
MQA shares one key/value head across all query heads; GQA shares each K/V head among a group of query heads. The KV cache shrinks by the ratio of query to K/V heads (for example 8×), cutting memory and bandwidth at decode time, with a small quality cost that GQA mostly avoids. Taught in: KV cache and efficient attention
How do top-k and top-p sampling differ, and when does each fail?
Top-k keeps a fixed number of most likely tokens; top-p (nucleus) keeps the smallest set whose probability mass reaches \(p\). Top-k is too permissive when the distribution is sharp (keeps junk) and too strict when it is flat; top-p adapts the set size to the model's confidence. Both are applied after temperature; min-p scales the cut-off by the top token's probability. Taught in: decoding and sampling
In a mixture-of-experts layer, what is the difference between total and active parameters, and why is load balancing needed?
Each token is routed to the top-\(k\) of \(E\) expert MLPs, so compute per token scales with the active experts while capacity scales with all of them. Without a balancing pressure the router collapses onto a few experts (they get more gradient, so they get better, so they get chosen more), wasting capacity and overloading devices; an auxiliary balance loss or bias-adjusted routing counteracts this. Taught in: mixture of experts
What do state-space models such as Mamba offer over attention, and where do they still lag? (Hard)
They process a sequence with a fixed-size recurrent state: linear time in sequence length, constant memory per generated token, no KV cache, while remaining parallel in training. The fixed state compresses the past, so tasks needing exact retrieval of arbitrary earlier tokens (copying, associative recall over long contexts) are harder; hybrids interleave a few attention layers to recover it. Taught in: beyond transformers
What does 'test-time compute' mean for reasoning models?
Spending more computation at inference, typically by generating long chains of reasoning (and sometimes sampling several and selecting or voting), to improve accuracy. Models trained with RL on verifiable tasks learn to use the extra tokens productively, giving accuracy that rises with the length of thinking on maths and code. Taught in: reasoning models
What is the 'lost in the middle' effect?
Liu et al. (2023) found that models used information placed at the beginning or end of a long context much better than information in the middle. Practical consequences: put the most important material at the edges, retrieve fewer and better passages, and test long-context claims with retrieval at varied depths rather than trusting the advertised window. Taught in: long context
Post-training and alignment¶
In supervised fine-tuning on chat data, which tokens should carry the loss, and why?
Usually only the assistant's response tokens. The prompt is given at inference, so learning to generate it wastes capacity and can teach the model to imitate users; masking prompt tokens focuses learning on the behaviour you want. The end-of-turn token must be included, or the model never learns to stop. Taught in: instruction tuning
Write the reward-model loss used for pairwise preferences.
Bradley–Terry: \(\mathcal{L} = -\log\sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\), where \(y_w\) is the preferred response. Only reward differences matter, so the reward's scale and offset are arbitrary, which is why rewards are often normalised before RL. Taught in: reward models
What objective does RLHF optimise, and what does the KL term do?
\(\max_\pi \mathbb{E}_{x, y\sim\pi}[r(x,y)] - \beta\,\mathrm{KL}(\pi(\cdot\mid x)\Vert\pi_{\text{ref}}(\cdot\mid x))\). The KL penalty keeps the policy near the SFT model, where the reward model's judgements are trustworthy, preserving fluency and limiting reward hacking; \(\beta\) trades reward against drift. Taught in: RLHF with PPO
Give two concrete examples of reward hacking in RLHF.
Length: reward models often prefer longer answers, so the policy learns verbosity rather than quality. Sycophancy: raters and reward models favour agreement, so the policy learns to tell users what they want to hear. Others include confident-sounding hedges and formatting tricks. Defences: the KL term, length-controlled rewards, reward-model ensembles, refreshed preference data. Taught in: RLHF with PPO, reward models
Sketch how DPO removes the reward model. (Hard)
The KL-regularised objective has the closed-form optimum \(\pi^*(y\mid x) \propto \pi_{\text{ref}}(y\mid x)\exp(r(x,y)/\beta)\). Inverting gives \(r(x,y) = \beta\log\frac{\pi^*(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta\log Z(x)\). Substituting into the Bradley–Terry likelihood, the intractable \(Z(x)\) cancels in the difference between two responses to the same prompt, giving a classification loss directly on the policy: \(-\log\sigma\big(\beta\log\frac{\pi(y_w)}{\pi_{\text{ref}}(y_w)} - \beta\log\frac{\pi(y_l)}{\pi_{\text{ref}}(y_l)}\big)\). Taught in: DPO
When would you choose PPO-style online RL over DPO?
DPO is simpler, stable and cheap, but learns only from a fixed set of preference pairs (offline). Online RL samples from the current policy and scores those samples, so it can keep improving beyond the data and exploit verifiable rewards. Choose DPO for straightforward preference alignment on good data; choose online RL when you have a reliable reward signal and need the policy to discover better behaviour. Taught in: DPO and friends
How does GRPO estimate advantages without a value network?
For each prompt it samples a group of \(G\) responses, scores them, and uses each response's reward standardised within the group, \(A_i = (r_i - \operatorname{mean}(r))/\operatorname{std}(r)\), as the advantage for all its tokens. The group mean is the baseline, removing the critic model and its memory; it was introduced in DeepSeekMath and used for DeepSeek-R1. Taught in: RL with verifiable rewards
What makes a reward 'verifiable', and why does that help?
The reward is computed by a program that checks correctness: a maths answer matched to the known result, code run against unit tests, an output validated against a schema. Such rewards are cheap, consistent and much harder to hack than a learned preference model, though not impossible (tests can be gamed, answer extraction can be fooled), so verifiers need auditing too. Taught in: RL with verifiable rewards
What are the two phases of Constitutional AI?
Supervised: the model critiques and revises its own responses against written principles (a constitution), and is fine-tuned on the revisions. RL: a model compares pairs of responses against the principles to produce AI preference labels, which train a preference model for RL (RLAIF). Human labour moves from labelling many harmful examples to writing and auditing principles. Taught in: constitutional AI
Explain LoRA's parameterisation, initialisation and why it adds no inference latency.
A frozen weight \(W_0\) gets a trainable low-rank update: \(h = W_0x + \frac{\alpha}{r}BAx\) with \(A\in\mathbb{R}^{r\times d_{in}}\) random and \(B\in\mathbb{R}^{d_{out}\times r}\) zero, so training starts exactly at the base model. After training, \(BA\) is merged into \(W_0\), leaving an ordinary matrix of the same shape. Taught in: LoRA and QLoRA, Project: LoRA
What three ideas let QLoRA fine-tune large models on one GPU?
The frozen base model is stored in 4-bit NormalFloat (NF4), a data type whose levels match normally distributed weights; the quantisation constants are themselves quantised (double quantisation); and paged optimisers move optimiser state to CPU memory during spikes. LoRA adapters train in higher precision on top, with gradients flowing through the dequantised weights. Taught in: LoRA and QLoRA
Why do soft targets from a teacher carry more information than hard labels in distillation?
A teacher's full distribution says which wrong answers are nearly right (a "7" that looks like a "1"), information a one-hot label discards. Raising the softmax temperature exposes these small probabilities; the student matches them with a KL or cross-entropy loss. For LLMs, sequence-level distillation trains on teacher-generated text, often filtered for correctness. Taught in: distillation and synthetic data
What is task arithmetic in model merging?
A task vector is the difference between fine-tuned and base weights, \(\tau = \theta_{ft} - \theta_{base}\). Adding scaled task vectors combines skills; subtracting one can remove a behaviour. It works because fine-tuning from a shared base moves weights a small distance in nearly independent directions; methods such as TIES resolve sign conflicts between vectors. Taught in: model merging and continual learning
Reinforcement learning¶
Write the UCB1 action rule and explain each term.
Choose \(a = \arg\max_a \big(\hat\mu_a + c\sqrt{\ln t / n_a}\big)\): the estimated mean reward plus an exploration bonus that grows slowly with total time \(t\) and shrinks as arm \(a\) is tried more (\(n_a\)). Optimism in the face of uncertainty: rarely tried arms get the benefit of the doubt, giving regret logarithmic in \(t\). Taught in: bandits and exploration
State the Bellman expectation equation for V^π.
\(V^\pi(s) = \sum_a \pi(a\mid s)\sum_{s', r} p(s', r\mid s, a)\,[\,r + \gamma V^\pi(s')\,]\): the value of a state is the expected immediate reward plus the discounted value of the next state, under the policy and the environment's dynamics. The optimality version replaces the average over actions with a max. Taught in: MDPs and the Bellman equations
What role does the discount factor γ play?
It weights future rewards by \(\gamma^k\), keeping infinite-horizon returns finite for \(\gamma < 1\), expressing a preference for sooner reward, and setting an effective horizon of about \(1/(1-\gamma)\) steps. It also makes the Bellman operator a \(\gamma\)-contraction, which is what guarantees value iteration converges. Taught in: MDPs and the Bellman equations
Why does value iteration converge?
The Bellman optimality operator is a contraction in the max norm with factor \(\gamma\): applying it shrinks the distance between any two value functions by at least \(\gamma\). By the Banach fixed-point theorem, repeated application converges to the unique fixed point \(V^*\), with error shrinking geometrically as \(\gamma^k\). Taught in: dynamic programming
Compare Monte Carlo and temporal-difference learning in bias and variance.
Monte Carlo uses the full sampled return: unbiased but high variance, and it must wait until the episode ends. TD(0) bootstraps from the current estimate, \(r + \gamma V(s')\): lower variance and online, but biased while \(V\) is wrong. TD(\(\lambda\)) and n-step returns interpolate between them. Taught in: Monte Carlo and TD learning
Why is Q-learning off-policy while SARSA is on-policy?
Q-learning's target uses \(\max_{a'}Q(s', a')\), the greedy action, regardless of the action the behaviour policy actually takes next, so it learns the optimal policy while exploring. SARSA's target uses the next action actually taken, so it learns the value of the exploring policy itself, which makes it more cautious near hazards. Taught in: Q-learning and DQN
What problems do DQN's replay buffer and target network solve?
Consecutive transitions are highly correlated and non-stationary; sampling minibatches from a large replay buffer breaks the correlation and reuses data. The bootstrapped target \(r + \gamma\max Q(s', a')\) moves every time \(Q\) updates, causing oscillation or divergence; a target network, updated only periodically, holds the target still. Taught in: Q-learning and DQN
Derive the REINFORCE gradient and explain why a baseline does not add bias. (Hard)
\(\nabla_\theta\mathbb{E}_{\tau\sim\pi_\theta}[R(\tau)] = \mathbb{E}[R(\tau)\nabla_\theta\log\pi_\theta(\tau)]\), using \(\nabla p = p\nabla\log p\); the environment's dynamics drop out of \(\nabla\log\pi_\theta(\tau)\), leaving \(\sum_t\nabla\log\pi_\theta(a_t\mid s_t)\). Subtracting a baseline \(b(s)\) is unbiased because \(\mathbb{E}_{a\sim\pi}[\nabla\log\pi(a\mid s)] = \nabla\sum_a\pi(a\mid s) = \nabla1 = 0\), while it can greatly reduce variance. Taught in: policy gradients
What does PPO's clipped objective do?
With ratio \(\rho_t = \pi_\theta(a_t\mid s_t)/\pi_{\text{old}}(a_t\mid s_t)\), it maximises \(\mathbb{E}[\min(\rho_t A_t, \operatorname{clip}(\rho_t, 1-\epsilon, 1+\epsilon)A_t)]\). Once a step has moved an action's probability more than \(\epsilon\) (typically 0.2) in the advantageous direction, the gradient stops, so several epochs of minibatch updates on the same data cannot move the policy too far. Taught in: actor-critic and PPO
What is generalised advantage estimation, and what does λ control?
\(\hat A_t = \sum_{l\ge0}(\gamma\lambda)^l\delta_{t+l}\), with TD errors \(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\). \(\lambda = 0\) gives the one-step TD advantage (low variance, biased); \(\lambda = 1\) gives the Monte Carlo advantage (unbiased, high variance). Values around 0.95 are common. Taught in: actor-critic and PPO
How do AlphaZero's neural network and tree search improve each other?
The network outputs move probabilities (a prior that focuses the search) and a value (which replaces random rollouts). Monte Carlo tree search, guided by both, produces visit counts that are a stronger policy than the raw network; the network is then trained to predict those visit counts and the game outcome. Self-play repeats this loop, a form of policy iteration with search as the improvement step. Taught in: model-based RL and planning
Why is offline RL hard? (Hard)
Learning only from a fixed dataset, the agent cannot try actions the data lacks, yet Q-learning's max picks exactly the actions whose values are least constrained by data, where function approximation errs optimistically. The policy exploits these errors (distribution shift). Remedies constrain the policy near the data or penalise values of unseen actions (conservative Q-learning). RLHF's KL term addresses the same problem. Taught in: offline RL and RL for language models
Generative models and multimodal¶
Write the VAE objective and explain the reparameterisation trick.
Maximise the evidence lower bound \(\mathbb{E}_{q(z\mid x)}[\log p(x\mid z)] - \mathrm{KL}(q(z\mid x)\Vert p(z))\): reconstruct well, while keeping the posterior close to the prior. Sampling \(z\) blocks gradients, so write \(z = \mu(x) + \sigma(x)\odot\varepsilon\) with \(\varepsilon\sim\mathcal{N}(0, I)\): the randomness becomes an input and gradients flow through \(\mu\) and \(\sigma\). Taught in: autoencoders and VAEs
What is a GAN's objective, and what is mode collapse?
\(\min_G\max_D\ \mathbb{E}_x[\log D(x)] + \mathbb{E}_z[\log(1 - D(G(z)))]\): the discriminator separates real from fake, the generator tries to fool it; at the optimum the generator matches the data distribution. Mode collapse is the generator producing only a few kinds of output that currently fool the discriminator, because nothing in the objective directly rewards covering every mode. Taught in: GANs
In DDPM, what is the closed form for noising x₀ to step t, and why does it matter?
\(q(x_t\mid x_0) = \mathcal{N}\big(\sqrt{\bar\alpha_t}\,x_0,\ (1-\bar\alpha_t)I\big)\) with \(\bar\alpha_t = \prod_{s\le t}(1-\beta_s)\), so \(x_t = \sqrt{\bar\alpha_t}x_0 + \sqrt{1-\bar\alpha_t}\,\varepsilon\). Any noise level can be sampled in one step, so training picks random \(t\) per example instead of simulating the chain. Taught in: diffusion models
What does a diffusion model actually learn to predict, and with what loss?
In the standard parameterisation, the noise: \(\mathcal{L} = \mathbb{E}_{t, x_0, \varepsilon}\lVert\varepsilon - \varepsilon_\theta(x_t, t)\rVert^2\), a simplified, reweighted form of the variational bound. Predicting the noise is equivalent, up to scaling, to estimating the score \(\nabla_x\log p_t(x)\), which links diffusion to score matching. Taught in: diffusion models, score and flow matching
Write the classifier-free guidance update and say what the guidance weight trades.
\(\tilde\varepsilon = \varepsilon_\theta(x_t, \varnothing) + w\,(\varepsilon_\theta(x_t, c) - \varepsilon_\theta(x_t, \varnothing))\), one network trained with the condition randomly dropped. \(w > 1\) pushes samples towards what distinguishes the condition, improving prompt adherence and fidelity at the cost of diversity and, at high \(w\), over-saturated images. Taught in: latent diffusion and guidance
Why run diffusion in a latent space?
A pretrained autoencoder compresses images (for example 8× per side) into latents that keep perceptually important structure and discard imperceptible detail. Diffusion over the much smaller latent tensor costs a fraction of pixel-space compute, and the decoder restores fine detail; this is what made Stable Diffusion practical on consumer GPUs. Taught in: latent diffusion and guidance
What does flow matching regress, in the simplest (rectified-flow) form?
Draw noise \(x_0\) and data \(x_1\), form \(x_t = (1-t)x_0 + t x_1\), and regress a velocity field onto the straight-line velocity: \(\lVert v_\theta(x_t, t) - (x_1 - x_0)\rVert^2\). Sampling integrates \(dx/dt = v_\theta\) from noise to data; straighter paths need fewer integration steps than diffusion's curved ones. Taught in: score and flow matching
How is CLIP trained, and why does that enable zero-shot classification?
An image encoder and a text encoder are trained contrastively on image–caption pairs: within a batch, the matching pairs' cosine similarities are pushed up and all mismatched pairs down (a symmetric cross-entropy over the similarity matrix). Zero-shot classification embeds prompts such as "a photo of a {class}" and picks the class whose text embedding is closest to the image's. Taught in: ViT and CLIP
Describe the standard architecture of an open vision-language model.
A pretrained vision encoder (often a ViT from CLIP or SigLIP) turns an image into patch embeddings; a projector (an MLP or a resampler) maps them into the language model's embedding space as "visual tokens"; the LLM reads them with the text. Training usually first aligns the projector on captions, then fine-tunes on visual instruction data. Taught in: vision-language models
How does Whisper turn audio into text?
Audio is converted to a log-Mel spectrogram; a transformer encoder processes it and a transformer decoder generates text tokens autoregressively, with special tokens selecting language, task (transcribe or translate) and timestamps. Its robustness came from weakly supervised training on about 680,000 hours of web audio. Taught in: speech and audio
What is a 'world model' in the video-generation sense, and what is the open question? (Hard)
A model that predicts future observations (frames) given past ones and possibly actions, so it can be used to simulate an environment for planning or training agents. The open question is whether models trained to produce plausible video learn consistent physics, object permanence and controllable dynamics, or only visually convincing statistics; long-horizon consistency remains a weak point. Taught in: video and world models
AI systems and infrastructure¶
Explain the roofline model in two sentences and classify matmul and element-wise ops.
Attainable FLOP/s is the minimum of peak compute and memory bandwidth × arithmetic intensity (FLOPs per byte moved). A large matrix multiply has high intensity (it reuses each loaded value many times) and is compute-bound; element-wise ops such as activations and normalisation do one or two FLOPs per element loaded and are memory-bound, which is why fusing them into neighbouring kernels pays. Taught in: how a GPU works
Why is LLM decoding at batch size 1 memory-bound?
Each new token requires a matrix-vector product with every weight: about 2 FLOPs per parameter while reading 2 bytes per parameter in bf16, an intensity of about 1 FLOP/byte, far below the hundreds a modern GPU needs to be compute-bound. Tokens per second is therefore roughly bandwidth divided by model size in bytes; batching many sequences raises intensity. Taught in: serving LLMs, compute maths
How much memory does mixed-precision Adam training need per parameter, before activations?
About 16 bytes: 2 for bf16 weights, 2 for bf16 gradients, 4 for an fp32 master copy and 8 for Adam's two fp32 moments. A 7B model therefore needs about 112 GB of state, more than one 80 GB GPU, which is what ZeRO/FSDP sharding addresses. Taught in: compute maths, distributed training
What do ZeRO stages 1, 2 and 3 shard?
Stage 1 shards optimiser states across data-parallel workers; stage 2 also shards gradients; stage 3 (equivalent to FSDP) also shards the parameters, gathering each layer's weights just in time for its forward and backward computation. Memory per GPU falls roughly with the number of workers, paid for with extra communication. Taught in: distributed training
Compare tensor parallelism and pipeline parallelism.
Tensor parallelism splits individual matrix multiplies across GPUs (for example attention heads or MLP columns), needing all-reduces inside every layer, so it is kept within a node on fast links. Pipeline parallelism places consecutive layers on different GPUs and streams micro-batches through; its cost is the pipeline bubble when stages wait, reduced by more micro-batches and clever schedules. Large runs combine both with data parallelism. Taught in: distributed training
What makes FP8 training harder than BF16?
FP8 formats have very little range and precision (E4M3 has 3 mantissa bits; E5M2 has more range but only 2), so tensors must be scaled per tensor or per block to fit, with scales tracked from recent maximums, and some operations (accumulation, normalisation, the optimiser) kept in higher precision. Outlier activations are the main hazard. Taught in: mixed precision
How do GPTQ and AWQ differ as post-training quantisation methods?
GPTQ quantises weights one column at a time and updates the remaining columns to compensate for the error, using second-order information from calibration data. AWQ observes that a small fraction of weight channels matter most (those that see large activations) and scales them up before quantisation to protect them, without per-weight error correction. Both target 4-bit weights with 16-bit activations. Taught in: quantisation
What problems do continuous batching and PagedAttention solve?
Static batching waits for the longest sequence in a batch; continuous batching inserts and removes requests at every decoding step, keeping the GPU full. PagedAttention stores the KV cache in fixed-size blocks mapped through a table, like virtual memory, eliminating fragmentation and over-reservation so many more sequences fit, and enabling prefix sharing. Taught in: serving LLMs
Why is speculative decoding lossless? (Hard)
A small draft model proposes \(k\) tokens; the large model scores them all in one forward pass. Each draft token is accepted with probability \(\min(1, p(x)/q(x))\), and on rejection a token is sampled from the normalised residual \(\max(0, p - q)\). This rejection-sampling scheme makes the output distribution exactly the large model's, while the speed-up depends on how often the draft agrees. Taught in: serving LLMs
Why do Apple-silicon Macs run large models well for their price?
CPU and GPU share one pool of unified memory with high bandwidth, so a model can use most of the machine's RAM without copying to a separate GPU memory, and decoding speed (bandwidth-bound) scales with that bandwidth. Frameworks such as MLX and llama.cpp's Metal backend exploit it, usually with 4-bit weights. Taught in: on-device AI
What is kernel fusion and why does it speed things up?
Combining several operations (for example bias add, activation and dropout, or a whole attention computation) into one GPU kernel, so intermediates stay in registers or shared memory instead of being written to and read back from slow global memory. For memory-bound chains of small ops, the saving in memory traffic is nearly the whole runtime. Taught in: kernels: CUDA and Triton
What must you version to reproduce a model result months later?
The code (commit), the exact data (a snapshot or content hash, plus preprocessing), the configuration and random seeds, the environment (library versions, hardware), the trained artefact, and the evaluation set and scores. Missing any one of these makes a regression impossible to diagnose. Taught in: MLOps
Estimate the memory to serve a 70B model at 4-bit with an 8k context for 8 concurrent users. (Hard)
Weights: \(70\times10^9\times0.5\) bytes ≈ 35 GB (plus a few percent for scales). KV cache depends on the architecture: for a Llama-2-70B-like model (80 layers, 8 KV heads of size 128, fp16) it is \(2\times80\times8\times128\times2 = 327{,}680\) bytes ≈ 0.31 MiB per token, so \(8\times8{,}192\) tokens ≈ 20 GiB. Total about 57 GB plus activations and overhead: one 80 GB GPU, but not one 48 GB GPU. Taught in: compute maths, KV cache
LLM application engineering¶
When can few-shot examples in a prompt hurt?
The model imitates surface features of examples: their length, format, label balance and even specific wording, so unrepresentative examples bias outputs (all examples positive, so the model over-predicts positive). Examples also cost tokens on every call. Use diverse, representative examples, explain the principle rather than relying on examples alone, and measure with and without them. Taught in: prompt engineering
How does constrained decoding guarantee valid JSON?
At each step, a grammar or JSON-schema state machine determines which tokens can legally come next, and all other logits are masked to \(-\infty\) before sampling. The output is valid by construction. Masking can distort the distribution (forcing unlikely tokens), so schema design and field order still affect quality. Taught in: structured outputs and function calling
What does an approximate nearest-neighbour index such as HNSW trade?
HNSW builds a layered proximity graph and searches greedily from coarse to fine layers, finding near neighbours in roughly logarithmic time instead of scanning all vectors. It trades a little recall (it may miss the true nearest neighbour) and memory for the graph for large speed-ups; parameters such as ef_search tune the trade. Taught in: embeddings and vector search
What goes wrong with chunks that are too small or too large?
Too small: chunks lose the context that gives them meaning ("it is set to zero") and the answer gets split across chunks. Too large: each chunk mixes several topics, so its embedding and BM25 score are diluted, and fewer chunks fit in the prompt. Prepending document and section titles, and evaluating several sizes on a golden set, is the reliable approach. Taught in: RAG, Project: RAG and agent
Why combine BM25 and dense retrieval, and why fuse by rank?
Their errors are uncorrelated: BM25 fails on vocabulary mismatch, dense retrieval on rare exact terms (codes, names). Their scores are on incomparable scales, so reciprocal rank fusion, \(\sum_r 1/(k + \operatorname{rank}_r)\) with \(k = 60\), combines positions rather than scores and rewards agreement. Taught in: advanced RAG
Why is a cross-encoder reranker more accurate than a bi-encoder, and why not use it for retrieval?
A bi-encoder embeds query and document separately, so the documents can be pre-computed and searched with an index, but the two never interact. A cross-encoder reads query and document together, letting every query token attend to every document token, which is far more accurate but needs one forward pass per pair. So: retrieve 50 to 100 candidates cheaply, rerank the shortlist. Taught in: advanced RAG
Why do errors compound in agents, and what is the arithmetic?
A task succeeds only if every step does. With independent per-step success \(q\), an \(n\)-step task succeeds with \(q^n\): 0.95 per step gives 0.60 over 10 steps. Raising \(q\) (good tools, validation, recoverable errors) or shortening tasks matters more than almost anything else. Taught in: agents and tool use
When should you not build an agent?
When the steps are known in advance: a fixed workflow (retrieve, then answer; classify, then route) is cheaper, faster, more predictable and easier to test. Use an agent when the path genuinely depends on intermediate results and the value justifies the extra cost, latency and risk, and when errors can be caught and recovered from. Taught in: agents and tool use
What are the costs of multi-agent systems compared with a single agent?
Many more tokens (each agent rebuilds context), coordination failures (duplicated or conflicting work, lost information at hand-offs), and harder debugging and evaluation. They pay off when work parallelises into independent sub-tasks with separable contexts, such as broad research, and rarely for tightly coupled tasks like a single code change. Taught in: multi-agent systems
What is context engineering?
Deciding what goes into the model's limited context at each step: instructions, retrieved knowledge, tool results, memory, history. Techniques include retrieving just in time instead of loading everything, summarising or clearing old tool outputs, writing notes to external memory and keeping stable content first for caching. More context is not better: irrelevant tokens dilute attention and cost money. Taught in: context engineering and memory
What does the Model Context Protocol standardise?
A client–server protocol through which applications (clients) connect to servers that expose tools (actions the model can call), resources (data it can read) and prompts (templates), over defined transports. Any MCP client can use any MCP server, turning an M×N integration problem into M+N. It does not make tools safe: permissions and confirmation remain the host's job. Taught in: MCP and tool protocols
What biases do LLM judges have, and how do you make one trustworthy?
Position bias (preferring the first or second answer), verbosity bias, self-preference for their own style, and leniency. Mitigate by swapping positions and averaging, using specific rubrics with yes/no criteria rather than 1–10 scales, and, above all, measuring agreement with human labels on a sample before trusting the judge, and re-measuring when prompts or models change. Taught in: evals in practice
What is indirect prompt injection, and why is there no complete fix? (Hard)
Instructions hidden in content the model reads (a web page, an email, a retrieved document) that the model follows as if they came from the user or developer. Models process instructions and data in the same token stream, so no filter reliably separates them. Defences reduce risk: least-privilege tools, human confirmation for consequential actions, isolating untrusted content from tool-calling contexts, and output checks. Taught in: guardrails and security
What are time-to-first-token and time-per-output-token, and what drives each?
TTFT is the delay before the first token appears: dominated by prefill, which processes the whole prompt (compute-bound) and grows with prompt length; prompt caching cuts it for repeated prefixes. TPOT is the time per subsequent token: dominated by decode (memory-bandwidth-bound) and batch contention. Users perceive TTFT as responsiveness and TPOT as reading speed. Taught in: shipping AI products
What is a model cascade, and what makes one work?
Send each request to a cheap model first and escalate to a stronger one when a check fails or confidence is low. It works only with a reliable escalation signal (a verifier, a schema check, a calibrated confidence), and it must be judged by cost per successful task: a cheap first try that fails often adds latency and cost. Taught in: shipping AI products
Data for AI¶
How are near-duplicate documents found at web scale?
MinHash with locality-sensitive hashing: represent each document by its set of word n-grams (shingles), compute many hash-based minimums whose agreement rate estimates Jaccard similarity, and band the signatures so similar documents collide in some bucket. It finds candidate pairs in roughly linear time instead of comparing all pairs. Taught in: quality filtering and deduplication
Why does deduplication improve models, not just save compute?
Repeated text is memorised rather than generalised from, wastes training tokens, inflates the weight of whatever happens to be copied widely (boilerplate, spam) and leaks test data into training. Deduplicated corpora have been shown to reduce memorisation and to train models of equal or better quality with fewer tokens. Taught in: quality filtering and deduplication
What does Cohen's kappa measure, and why not just percent agreement?
Agreement between two annotators corrected for chance: \(\kappa = (p_o - p_e)/(1 - p_e)\), where \(p_e\) is the agreement expected if both labelled at random with their own label frequencies. On imbalanced labels, high percent agreement can be almost entirely chance; kappa exposes it. Taught in: labelling and human feedback
Distinguish covariate shift, label shift and concept drift.
Covariate shift: the input distribution \(p(x)\) changes but \(p(y\mid x)\) does not (new customer demographics). Label shift: \(p(y)\) changes with \(p(x\mid y)\) fixed (fraud becomes more common). Concept drift: \(p(y\mid x)\) itself changes (what counts as spam evolves). They need different detection and different fixes. Taught in: data in production
What is a feedback loop in a deployed model, with an example?
The model's outputs change the data it will later be trained on. A recommender that shows only what it already predicts users like never observes their reaction to anything else, narrowing what it learns; a credit model that rejects applicants never sees whether they would have repaid. Exploration, holdout groups and logging propensities help. Taught in: data in production
What questions decide whether you may train on a dataset?
Its licence and terms of use, whether it contains personal data (and the legal basis to process it), copyright status and any opt-outs, the provenance of each source, and whether the intended use (commercial training, redistribution) is permitted. Recording these per source, in a datasheet, is what makes a dataset auditable later. Taught in: collection, licensing and curation
Evaluation, safety and interpretability¶
What is Goodhart's law, and how does it show up in AI benchmarks?
"When a measure becomes a target, it ceases to be a good measure." Benchmarks that drive research get optimised directly: through test-set contamination, prompt tuning on the test, and methods that exploit benchmark quirks, so scores rise faster than the capability they were meant to measure. Hence held-out and refreshed benchmarks, and private evaluations. Taught in: benchmarks and their limits
How can you detect benchmark contamination?
Search the training corpus for n-gram overlap with test items; check whether the model completes test items verbatim from a prefix or ranks the original ordering of answer options suspiciously high; compare accuracy on items published before and after the training cut-off, or on freshly written paraphrases of the same problems. Taught in: contamination and evaluation hygiene
What is superposition, and how do sparse autoencoders address it? (Hard)
Networks represent more features than they have dimensions by assigning them nearly orthogonal directions, so individual neurons respond to several unrelated concepts (polysemanticity). A sparse autoencoder learns an overcomplete dictionary that reconstructs activations from a sparse combination of directions; the learned directions are often individually interpretable features, which can then be tested by intervening on them. Taught in: mechanistic interpretability
Distinguish outer and inner misalignment.
Outer misalignment: the objective we specify (a reward, a loss) differs from what we actually want, so optimising it well produces unwanted behaviour (specification gaming). Inner misalignment: even with a good objective, training produces a model whose learned goals differ from it, which may only show up outside the training distribution. Taught in: the alignment problem
Why do RLHF-trained models tend to be sycophantic?
Human raters, and reward models trained on their judgements, tend to prefer responses that agree with the user's stated views and flatter them, so optimising for preference rewards agreement over accuracy. Sharma et al. (2023) documented this across assistants. Mitigations include targeted preference data, principles that reward honest disagreement, and evaluations designed to measure it. Taught in: the alignment problem, reward models
What is a dangerous-capability evaluation, and why is elicitation the hard part?
A test of whether a model can meaningfully assist with severe harms (for example cyber-offence or biological weapons) or act autonomously in risky ways, used to decide on safeguards before release. The hard part is that a negative result is only meaningful if the evaluators tried hard to elicit the capability (fine-tuning, tools, good prompting); weak elicitation underestimates risk. Taught in: red-teaming and dangerous-capability evals
Why can't a classifier generally satisfy calibration and equalised odds at the same time? (Hard)
When base rates differ between groups, a classifier that is calibrated within each group (a score of 0.7 means 70% positive in every group) must have different false-positive or false-negative rates across groups, except in degenerate cases such as perfect prediction. Fairness definitions encode different values, and choosing among them is a policy decision, not a technical one. Taught in: robustness, fairness and privacy
What does differential privacy guarantee, intuitively?
That the output of an algorithm (for example a trained model) is almost equally likely whether or not any one person's data was included, with \(\varepsilon\) bounding the change in log-probability. In training, DP-SGD clips each example's gradient and adds calibrated noise; smaller \(\varepsilon\) means stronger privacy and usually lower accuracy. Taught in: robustness, fairness and privacy
How does the EU AI Act classify systems, and where would a credit-scoring model fall?
By risk: unacceptable-risk practices are prohibited; high-risk systems carry obligations (risk management, data governance, technical documentation, logging, human oversight, accuracy and robustness, conformity assessment); limited-risk systems have transparency duties; minimal-risk ones have none. Creditworthiness assessment of individuals is listed as high-risk. General-purpose AI models have separate obligations. Taught in: governance and regulation
What is an adversarial example, and why do they exist?
An input altered imperceptibly that changes a model's prediction. In high dimensions, many tiny per-pixel changes aligned with the loss gradient add up to a large change in the output even for nearly linear models; models also rely on predictive but non-robust features humans ignore. Adversarial training improves robustness at some cost in clean accuracy. Taught in: robustness, fairness and privacy
The story of AI¶
What did Minsky and Papert's 1969 book show, and what was its effect?
Perceptrons proved that single-layer perceptrons cannot compute functions such as XOR or connectedness, which are not linearly separable. Although multi-layer networks could, nobody had a practical way to train them, and the book is widely associated with the decline of neural-network funding in the 1970s. Backpropagation answered the training question in the 1980s. Taught in: before the boom
Why was the 1986 backpropagation paper so influential when the chain rule was old?
Rumelhart, Hinton and Williams showed in Nature that backpropagating errors through hidden layers made those layers learn useful internal representations, with demonstrations, which changed what people believed multi-layer networks could do. Reverse-mode differentiation had been described earlier; the contribution was making it the training method for representation learning. Taught in: before the boom
What made AlexNet's 2012 ImageNet result a turning point?
It cut top-5 error to 15.3% against 26.2% for the runner-up, a margin that convinced the field. The ingredients were a large labelled dataset (ImageNet), GPU training, ReLU activations, dropout and data augmentation; none was new alone, but together at that scale they showed deep learning beating hand-engineered features. Taught in: the deep learning reset
What did 'Attention Is All You Need' change?
It replaced recurrence with self-attention, so every position is processed in parallel during training, and long-range dependencies take one step instead of many. The transformer trained faster and better on translation and became the substrate for BERT, GPT and nearly every large model since. Taught in: the transformer and the scale era
What was new about GPT-3 in 2020?
Scale (175B parameters) produced strong in-context learning: the model performed new tasks from a few examples in the prompt, without gradient updates. This shifted attention from task-specific fine-tuning towards prompting general models, and made scaling a deliberate strategy. Taught in: the transformer and the scale era
Why did ChatGPT (November 2022) matter more than the models before it?
The underlying capability existed in earlier models; instruction tuning and RLHF made it usable through a free chat interface that anyone could try, and it reached a mass audience at a speed no earlier AI product had. It turned language models from a research topic into a product category and started the assistant era. Taught in: the assistant era
The research frontier¶
What makes computer-use and long-horizon agents hard to evaluate?
Tasks have many valid paths and few unique answers, environments change and must be reset reproducibly, success may need human judgement, and runs are long and expensive, so sample sizes are small and variance is high. Benchmarks such as SWE-bench and OSWorld use executable checks to make success verifiable. Taught in: computer-use and long-horizon agents
Why is data the bottleneck for robot learning?
Unlike text and images, there is no internet-scale corpus of robot actions: every demonstration costs real-world time on specific hardware, and data from one robot body does not transfer cleanly to another. Responses include pooling datasets across labs and embodiments, simulation, learning from human video, and vision-language-action models that borrow knowledge from web pre-training. Taught in: embodied AI and robotics
What did AlphaFold 2 achieve, and why does it matter beyond biology?
At CASP14 in 2020 it predicted protein structures with accuracy competitive with experimental methods for many targets, solving a 50-year grand challenge, and its predictions were released for hundreds of millions of proteins. It is the clearest case of AI producing a scientific capability that experts could not, and it shaped how AI-for-science projects are designed. Taught in: AI for science
What is the argument for neuro-symbolic approaches?
Neural networks learn flexible patterns from data but struggle with guaranteed correctness, systematic generalisation and long chains of exact reasoning; symbolic systems (logic, search, programs) give exactness but are brittle to build. Combining them, for example a language model proposing steps that a formal verifier checks, aims at both, as in systems that solve olympiad geometry or prove theorems in Lean. Taught in: world models and neuro-symbolic AI
Name three open problems that matter for the next few years.
Reliable evaluation of long-horizon and open-ended capabilities; interpretability good enough to verify what a model is doing; sample-efficient learning (from far less data than current models need); robust alignment as capabilities grow; and continual learning without forgetting. Any three, explained with why they are hard, is a strong answer. Taught in: open problems
How should an engineer keep up with the frontier without drowning?
Follow a small number of high-signal sources, read abstracts widely but papers deeply only when they bear on your work, and reproduce something small from the papers that matter. Track ideas, not model releases: most releases are new numbers on known ideas. Taught in: keeping up with the frontier, how to read a paper
Projects and practice¶
In micrograd, why does every _backward closure use += rather than =?
A node used in several places receives gradient from each use, and the multivariable chain rule sums them. With =, the last contribution overwrites the others: \(y = x\cdot x\) would give \(dy/dx = x\) instead of \(2x\). The same accumulation is why gradients must be zeroed before every backward pass. Taught in: Project: micrograd
Name the four automated checks of the tiny-GPT project and what each catches.
Parameter count (architecture wired as intended); step-0 loss near \(\ln V\) (initialisation and loss wiring); causality (no information from future tokens, invisible in the loss); overfitting one batch (every parameter connected and the optimiser working). All four must pass before a validation loss means anything. Taught in: Project: tiny GPT
In the LoRA project, why is the test set built from different phrasings and unseen merchants?
To test the skill rather than the templates, and to test that pre-trained knowledge (what kind of shop an unseen merchant is) survives fine-tuning. A test drawn from the training distribution would score near 100% and reveal neither problem. Taught in: Project: LoRA
Why did every retriever score recall@5 of 1.00 on the RAG project's easy golden set?
The questions were written with the target page open and reuse its distinctive words, so lexical and semantic matching both find it. Such a set cannot distinguish retrievers; only the paraphrased set did. Golden questions should come from people who have not read the documents. Taught in: Project: RAG and agent
Why test an agent harness with a scripted model?
The harness is ordinary code (tool dispatch, error handling, budgets, message formatting) and deserves deterministic, free, fast tests. A live model makes tests slow, costly and flaky, and cannot be made to produce rare cases (a malicious argument, a model that never stops) on demand. Live-model behaviour is evaluated separately, with a task set. Taught in: Project: RAG and agent
What is the first thing to write in any project on the ladder, and why?
The success criterion, as a number, before any code: it defines the end of the project, forces you to build the evaluation first, and prevents moving the goalposts after seeing results. A baseline comes second. Taught in: the project ladder
First principles¶
What makes a question interview-grade. A good interview question cannot be answered by recall of a definition alone. It asks why a design is the way it is ("why √d_k?"), what breaks if you change it ("what if you removed the residual connections?"), or for a number you can only produce if you understand the mechanism ("how big is the KV cache?"). Each of those requires a model of the system in your head, which is what the interviewer is testing. The questions above are written to that standard; the "Hard" ones additionally require a short derivation or the combination of ideas from two tracks.
Why retrieval practice works. Recalling an answer is itself a learning event: each successful retrieval makes the memory more durable and more accessible, an effect psychologists call the testing effect, and spacing those retrievals out over growing intervals makes it stronger still. Re-reading feels productive because the material becomes familiar, but familiarity is recognition, not recall, and an interview (or a debugging session at 2 a.m.) demands recall.
Why grading 0/½ rather than right/wrong. The middle grade captures the most common and most useful state: you have the idea but not the precise statement. That is where a link back to the teaching page pays most, because you know what you are looking for.
The maths¶
Most questions above contain their maths in the answer. These five are the derivations interviewers most often ask candidates to do at a whiteboard; each takes five minutes or less once you know it. Do them on paper before opening.
Derive the gradient of softmax cross-entropy with respect to the logits.
\(\ell = -\log s_y = -z_y + \log\sum_k e^{z_k}\). Then \(\partial\ell/\partial z_i = -\mathbb{1}[i=y] + e^{z_i}/\sum_k e^{z_k} = s_i - \mathbb{1}[i=y]\), the vector \(\mathbf{s} - \mathbf{y}\). Taught in: information theory, backpropagation
Show that the variance of q·k is d when entries are independent with zero mean and unit variance.
\(\operatorname{Var}(\sum_{i=1}^d q_ik_i) = \sum_i\operatorname{Var}(q_ik_i)\) by independence, and \(\operatorname{Var}(q_ik_i) = \mathbb{E}[q_i^2]\mathbb{E}[k_i^2] - (\mathbb{E}[q_i]\mathbb{E}[k_i])^2 = 1\). So the sum has variance \(d\), and dividing by \(\sqrt d\) restores 1. Taught in: attention
Derive the 6ND estimate of training FLOPs.
A dense layer with \(N\) weights does one multiply and one add per weight per token in the forward pass: \(2N\) FLOPs. Backward computes the gradient with respect to the input and with respect to the weights, two products of the same size: \(4N\). Total \(6N\) per token, \(6ND\) for \(D\) tokens; attention's \(QK^\top\) and \(AV\) add a term proportional to context length that is small unless context is long relative to width. Taught in: compute maths
Derive the closed form of the DDPM forward process q(x_t | x_0).
Each step is \(x_t = \sqrt{1-\beta_t}\,x_{t-1} + \sqrt{\beta_t}\,\varepsilon_t\). Unrolling, \(x_t\) is \(\sqrt{\prod_{s\le t}(1-\beta_s)}\,x_0\) plus a sum of independent Gaussians; their variances telescope to \(1 - \prod_{s\le t}(1-\beta_s)\). With \(\bar\alpha_t = \prod_{s\le t}(1-\beta_s)\): \(x_t = \sqrt{\bar\alpha_t}x_0 + \sqrt{1-\bar\alpha_t}\,\varepsilon\). Taught in: diffusion models
Show that the optimal policy of KL-regularised reward maximisation is π_ref · exp(r/β), normalised.
For one prompt, maximise \(\sum_y\pi(y)r(y) - \beta\sum_y\pi(y)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)}\) subject to \(\sum_y\pi(y) = 1\). This equals \(-\beta\,\mathrm{KL}\!\left(\pi\,\Vert\,\pi_{\text{ref}}e^{r/\beta}/Z\right) + \beta\log Z\), which is maximised when the KL is zero: \(\pi^*(y) = \pi_{\text{ref}}(y)e^{r(y)/\beta}/Z\). This is the step DPO builds on. Taught in: DPO, RLHF with PPO
Build it¶
A minimal Leitner-box scheduler, the classic spaced-repetition system, so that you review weak questions often and strong ones rarely. Questions start in box 1; a correct answer moves a question up a box, a miss sends it back to box 1, and box \(n\) is reviewed every \(2^{n-1}\) days. The simulation below assumes 150 questions, 25 reviews a day, and a random "true" probability of answering each one (between 0.5 and 0.95). Plain Python, standard library only.
"""A Leitner-box review schedule for this page's questions. Box n is reviewed every 2**(n-1) days;
a correct answer moves a question up one box, a miss sends it back to box 1."""
import datetime as dt, random
def review(state, results, today):
"""state: {qid: (box, due_date)}; results: {qid: True/False} for today's session."""
for qid, correct in results.items():
box = min(state[qid][0] + 1, 5) if correct else 1
state[qid] = (box, today + dt.timedelta(days=2 ** (box - 1)))
return state
def due(state, today):
return sorted(q for q, (_, d) in state.items() if d <= today)
random.seed(0)
day0 = dt.date(2026, 10, 1)
state = {f"Q{i:03d}": (1, day0) for i in range(1, 151)}
skill = {q: random.uniform(0.5, 0.95) for q in state} # your chance of answering each one
for day in range(30):
today = day0 + dt.timedelta(days=day)
todo = due(state, today)[:25] # at most 25 reviews a day
state = review(state, {q: random.random() < skill[q] for q in todo}, today)
if day in (0, 6, 13, 29):
boxes = [sum(b == k for b, _ in state.values()) for k in range(1, 6)]
print(f"day {day + 1:2d}: reviewed {len(todo):2d} boxes 1-5: {boxes}")
ranked = sorted(state, key=lambda q: skill[q])
mean_box = lambda qs: sum(state[q][0] for q in qs) / len(qs)
print(f"mean box: weakest quarter {mean_box(ranked[:37]):.2f}, strongest quarter {mean_box(ranked[-37:]):.2f}")
day 1: reviewed 25 boxes 1-5: [129, 21, 0, 0, 0]
day 7: reviewed 25 boxes 1-5: [91, 22, 27, 10, 0]
day 14: reviewed 25 boxes 1-5: [76, 15, 17, 42, 0]
day 30: reviewed 25 boxes 1-5: [34, 17, 13, 34, 52]
mean box: weakest quarter 2.30, strongest quarter 3.95
After a month, more than half the bank sits in boxes 4 and 5 (reviewed every 8 or 16 days) and the questions you find hardest sit, on average, almost two boxes lower, so they come up far more often. That is the whole point: review time goes where recall is weakest.
Things to try. Replace the simulated skill with your own 0/½ grades (treat 2 as correct, 0 and 1 as a miss) stored in a CSV; cap reviews at 15 a day and see how long the backlog takes to clear; add a sixth box with a 32-day interval for questions you have answered correctly five times running.
Check yourself¶
Why answer out loud or on paper rather than in your head?
Answering silently lets you skip the step you do not actually know ("and then it's normalised somehow"). Producing a complete sentence, formula or number forces the gap into the open, which is when you learn from the model answer. Interviews are out loud too.
You score 2 on every question in a track after reading its pages yesterday. What should you conclude?
Little yet. Recall a day after reading is mostly short-term; the test of durable understanding is the same score after a week or more without re-reading, and on questions phrased differently. Schedule the track again and add your own variations.
Why does the Leitner scheduler send a missed question back to box 1 rather than down one box?
A miss is evidence that the memory is not yet durable, and short intervals are what rebuild it. Dropping one box would leave a forgotten item on a long interval. Gentler variants exist (and spaced-repetition software fits intervals per item), but the reset is the simple, safe rule.
Pick any 'Hard' question you got wrong. What two things should you do next?
Re-read the linked section and re-derive the answer on paper without looking. Then find a way to use it: a small computation, a line of code, or the related project on the ladder. Understanding that is used once is far more durable than understanding that is only read.
Go deeper¶
Courses and books
- Neural Networks: Zero to Hero — Andrej Karpathy. Many of the deep-learning and transformer questions, answered by building the systems from scratch.
- Stanford CS336: Language Modeling from Scratch — The systems, scaling and data questions at university depth.
- ARENA — Exercises with solutions for transformers, interpretability, RL and evals; excellent practice for the hard questions.
- Introduction to Information Retrieval — Manning, Raghavan and Schütze. Background for the retrieval questions; free online.
Papers behind the hard questions
- Training Compute-Optimal Large Language Models — Hoffmann et al., 2022. Chinchilla.
- Direct Preference Optimization — Rafailov et al., 2023. The derivation in The maths section, in full.
- DeepSeekMath — Shao et al., 2024. Introduces GRPO.
- Denoising Diffusion Probabilistic Models — Ho, Jain and Abbeel, 2020. The forward-process closed form and the noise-prediction loss.
- Towards Understanding Sycophancy in Language Models — Sharma et al., 2023. Evidence behind the sycophancy question.
- Lost in the Middle — Liu et al., 2023. Evidence behind the long-context question.
Where this leads¶
- The project ladder — turn the questions you could not answer into something you build.
- How to study AI so it sticks — the learning science behind retrieval and spacing, in more depth.
- Formula sheet — the equations from these answers on one page.
- Glossary — for any term in a question you could not define.