Whole course
All flashcards
Reviewing needs JavaScript. You can read every card in the list below.
Loading your cards...
Read all 191 cards as a list
The learning problem: generalization, bias-variance and regularization
- Front
- What is empirical risk, and what is it a proxy for?
- Back
- The average loss on the training set. It stands in for expected risk, the average loss on unseen data from the same source, which we cannot measure directly. Learning works only if the first tracks the second.
- Front
- Parameter versus hyperparameter?
- Back
- Parameters (weights) are learned from training data by the optimizer. Hyperparameters (learning rate, tree depth, lambda) are set by you and chosen with validation data.
- Front
- What is the job of each split: train, validation, test?
- Back
- Train fits the parameters. Validation chooses hyperparameters and models. Test is used once at the end for an unbiased estimate. Train learns, validation chooses, test judges.
- Front
- Name three data leaks and the fix for each.
- Back
- Scaler or imputer fitted before splitting: fit inside the training fold (a Pipeline). Rows of one entity on both sides: group k-fold. Random split on time-ordered data: forward-chaining split.
- Front
- Write the squared-error decomposition and say what each term means.
- Back
- Expected error = bias squared + variance + irreducible noise. Bias is systematic error from a too-simple model, variance is sensitivity to the training sample, noise is label noise no model can remove.
- Front
- Train error 2%, validation error 25%. Diagnosis and fixes?
- Back
- High variance (overfitting). After ruling out leakage: more data, regularization, a simpler model, early stopping, augmentation, or bagging. A bigger model makes it worse.
- Front
- What do learning curves show, and when does more data not help?
- Back
- Train and validation error against training-set size. Both plateau high and close together means bias: more data will not help, add capacity or features. A large gap that narrows with data means variance: more data helps.
- Front
- Why does L1 give exact zeros but L2 does not?
- Back
- The L1 gradient has constant size, so it can push a small weight all the way to zero (the solution is a soft threshold). The L2 gradient shrinks in proportion to the weight, so it approaches zero but does not arrive. Geometrically the L1 diamond has corners on the axes.
- Front
- What does raising lambda do to training error and to validation error?
- Back
- Training error never falls (it rises or stays flat), because the penalty makes the fit to the training data worse. Validation error usually falls first as variance drops, then rises once the model underfits. Choose lambda at the validation minimum.
- Front
- Why standardize features before an L1 or L2 penalty?
- Back
- The penalty adds up weight sizes, and a weight's size depends on the feature's units. Without scaling, the penalty treats metres and millimetres differently. Fit the scaler on training data only.
Linear models, loss functions and gradient descent
- Front
- Derive the gradient of the log loss for logistic regression.
- Back
- With p = sigmoid(z) and z = w.x + b: dl/dp = -y/p + (1-y)/(1-p) and dp/dz = p(1-p). The p(1-p) cancels the denominators, leaving dl/dz = p - y, so the gradient with respect to w is (p - y) x and with respect to b is p - y.
- Front
- Why use log loss, not squared error, with a sigmoid?
- Back
- Log loss is the Bernoulli negative log-likelihood and is convex in the weights. Squared error on a sigmoid keeps a p(1-p) factor in its gradient, which is near 0 when the model is confidently wrong, so learning stalls, and the loss is not convex.
- Front
- What happens to unpenalised logistic regression on perfectly separable data?
- Back
- The loss approaches 0 as the weights grow, so there is no finite minimiser and the weights never stop growing (slowly). An L2 or L1 penalty, or early stopping, keeps them finite.
- Front
- Write the normal equation and say when to avoid it.
- Back
- w = (X'X)^-1 X'y, from setting the gradient to zero, meaning the residual is orthogonal to every column of X. Avoid it when d is large (cost about n d^2 plus d^3), when data must stream, when there is no closed form, and when columns are collinear so X'X is nearly singular. Ridge fixes the last case.
- Front
- Collinear features: what breaks and what does not?
- Back
- Individual coefficients become unstable, with large variance and possibly wrong signs, because the data cannot separate the features' effects. Predictions usually stay fine. Fix with ridge, or drop or merge the correlated features.
- Front
- Which constant minimises squared error, and which minimises absolute error?
- Back
- The mean minimises squared error and the median minimises absolute error. For [1, 2, 3, 4, 100] the mean is 22 and the median is 3, which is why squared error is outlier-sensitive.
- Front
- Describe Huber loss and when to use it.
- Back
- Quadratic for small residuals, linear for large ones, so outliers get a lesser weight without being ignored. Use it when outliers are likely and you do not want to chase them, after checking why they exist.
- Front
- Hinge loss versus log loss: what is each for?
- Back
- Hinge is max(0, 1 - m) with margin m = y f(x): it is exactly 0 beyond a margin of 1, so only points near or past the boundary matter, and it gives no probability. Log loss, log(1 + e^-m), keeps a shrinking penalty on every point and gives probabilities you can threshold by cost.
- Front
- What does the learning rate do, and what do diverging, oscillating and crawling losses tell you?
- Back
- It scales the step: w = w - lr * gradient. On a quadratic with curvature h it converges only when lr is below 2/h. Loss rising or NaN means too high (or unscaled inputs, or log of 0). Bouncing at the same level means right at the limit. A barely moving loss means too low.
- Front
- What do momentum and Adam each add to gradient descent?
- Back
- Momentum keeps a leaky sum of past gradients: agreeing directions speed up and zigzags cancel. Adam keeps running averages of the gradient and its square, divides one by the root of the other with bias correction, so every parameter gets its own step size (first step about the learning rate). Both have hyperparameters to tune, and neither always wins.
- Front
- Why standardise features before gradient descent, and what is the catch?
- Back
- Different scales make the loss a thin canyon (high condition number), so the stable learning rate is set by the steepest direction and the rest crawls. In the lesson's experiment, steps fell from about 97,000 on raw features to 3 on standardised ones. Fit the scaler on training data only.
Decision trees, random forests and gradient boosting
- Front
- Define Gini impurity and Gini gain, and compute the gain for (5+, 5-) split into (4+, 1-) and (1+, 4-).
- Back
- Gini = 1 - sum of p_k squared; gain = parent impurity minus the size-weighted child impurity. Parent 0.5, each child 1 - (0.8^2 + 0.2^2) = 0.32, so gain = 0.5 - 0.32 = 0.18. Entropy gain for the same split is 0.2781 bits.
- Front
- What does 'greedy' mean for a decision tree, and what does it miss?
- Back
- Each split is the best one now, with no look-ahead, because finding an optimal tree is NP-complete. On XOR no single split has any gain, yet two levels of splits are perfect, so a tree that only accepts positive gain stops at the root.
- Front
- A tree has 100% training accuracy and the data has 15% label noise. What does that tell you?
- Back
- The best possible accuracy on fresh data is about 85%, so a training score above that means the tree memorised wrong labels. Limit max_depth or min_samples_leaf, or prune with cost-complexity pruning, and choose the setting by validation accuracy.
- Front
- Write the variance of the average of B predictors with variance sigma^2 and pairwise correlation rho. What does each term teach?
- Back
- rho sigma^2 + (1 - rho) sigma^2 / B. The second term shrinks with more trees. The first is a floor that no number of trees removes, so lowering the correlation (bootstrap samples, random feature subsets) is what moves the floor.
- Front
- What does feature subsampling in a random forest buy, and what does it cost?
- Back
- Fewer candidate features per split makes trees less alike (lower rho), which lowers the variance floor. Each tree gets worse (higher variance and bias). In the lesson's six-feature example rho fell from 0.127 to 0.056 but squared bias rose from 0.273 to 0.467, so max_features is tuned.
- Front
- What is out-of-bag error, and why are about 36.8% of rows out of bag?
- Back
- A row is missed by one bootstrap sample with probability (1 - 1/n)^n, which tends to 1/e = 0.368. Predicting each row only with the trees that never saw it gives a validation estimate with no held-out set. It is noisy on small data.
- Front
- Describe gradient boosting in one pass, naming what each tree is fitted to.
- Back
- Start from a constant. Each round fits a small tree to the negative gradient of the loss at the current predictions (the residual y - F for squared error, y - p for log loss) and adds it scaled by the learning rate: F_m = F_(m-1) + eta h_m.
- Front
- How do learning rate, number of rounds and depth interact in boosting?
- Back
- A smaller learning rate takes smaller steps and needs more rounds; given enough rounds it often reaches a lower validation error (in the lesson, rate 0.01 had not caught up with 0.1 by the 800-round cap). Rounds act as regularisation, so choose them by early stopping on validation data, not training loss. Depth sets how many features interact in one tree; shallow trees are the norm.
- Front
- Bagging versus boosting: what is each tree trained on, and what is the failure mode of each?
- Back
- Bagging trains deep trees independently on bootstrap samples and averages them; it cuts variance, and more trees only stop helping. Boosting trains shallow trees in sequence on the remaining errors; it builds up the fit, and too many rounds or too large a step overfits.
- Front
- Why not trust a forest's default feature importance, and what do you use instead?
- Back
- Impurity importance comes from training statistics and favours features with many distinct values; in the lesson, noise columns took about 75% of it. Use permutation importance on held-out data, and permute correlated features together because they dilute each other.
- Front
- How do tree models treat missing values, and why can that beat mean filling?
- Back
- Scikit-learn trees, histogram boosting and XGBoost learn which child missing values go to, so missingness can be a signal. Mean filling puts missing rows among real values and hides it: in the lesson, 0.693 against 0.656 validation accuracy.
- Front
- How should a 50,000-level categorical feature be encoded for a tree ensemble?
- Back
- Prefer native categorical support or cross-fitted target encoding; plain one-hot makes 50,000 sparse columns and naive target encoding leaks the label. Scikit-learn's TargetEncoder cross-fits, and fit_transform should be used on training data.
k-NN, k-means, PCA, SVM and naive Bayes: the classical toolkit
- Front
- How does k-NN classify a point, and what does choosing k trade off?
- Back
- It stores the training data, finds the k closest rows and takes a majority vote. Small k follows noise (high variance; 1-NN scores 100% on its own training set, barring duplicate rows with different labels); large k blurs the boundary (high bias). Choose k on validation data.
- Front
- What is the curse of dimensionality for distance-based methods?
- Back
- As dimension grows, the nearest point's distance approaches the farthest point's (Beyer et al.: seen from about 10 to 15 dimensions in their experiments). In the lesson's random-data run, nearest/farthest was 0.04 at d = 2 and 0.91 at d = 1000. Neighbours then carry little local information, unless the data has low-dimensional structure.
- Front
- Why must columns be scaled before k-NN, and what happens if you do not?
- Back
- Euclidean distance adds squared differences, so a column in large units decides the neighbours. In the lesson, one noise column at 100 times the scale took 5-NN from 0.950 to 0.530, below the 0.607 majority baseline. Fit the scaler on training data only.
- Front
- State the two steps of Lloyd's k-means loop and what it minimises.
- Back
- Assign each row to its nearest centre; move each centre to the mean of its rows; repeat until assignments stop changing. It minimises the inertia J, the sum of squared distances to the assigned centre. J never rises, so the loop converges, but only to a local optimum.
- Front
- What does k-means++ change, and what does it not guarantee?
- Back
- After a random first centre, each next centre is drawn with probability proportional to its squared distance from the nearest chosen centre. It is O(log k)-competitive in expectation. In the lesson it raised good runs from 72% to 87% but its worst run was still 2.4 times the best J, so also restart and keep the lowest J.
- Front
- How do you choose k in k-means, and why not just minimise inertia?
- Back
- Inertia falls as k grows and is zero at k = n. Look for the elbow where the drop slows, and the silhouette s = (b - a) / max(a, b) (between -1 and 1; higher is better separated), then check stability across restarts and usefulness for the decision. There is no rule that always works.
- Front
- Name three ways k-means fails and the fix for each.
- Back
- Non-convex shapes such as rings (purity 0.52 in the lesson): use DBSCAN or single linkage. Unscaled columns: standardise. Outliers (one point at distance 100 took a whole cluster): remove or cap them, or use a method that labels noise. In all three the objective, a sum of squared distances to a mean, is the cause.
- Front
- List the PCA steps and what the explained variance ratio is.
- Back
- Centre the columns, form the covariance matrix (divide by n - 1), take its eigenvectors sorted by eigenvalue, project onto the top k. Each component's explained variance is its eigenvalue; the ratio is that eigenvalue over the sum of all eigenvalues. Example: covariance rows (2, 1) and (1, 2) has eigenvalues 3 and 1, ratios 3/4 and 1/4.
- Front
- When does PCA mislead?
- Back
- Units: an unscaled big-unit column takes PC1 (0.999998 of the variance in the lesson). Quiet signal: PCA never sees labels, so a class signal in a low-variance direction is dropped (PC1 only 0.508, PC2 only 1.000). Curved structure: PCA is linear. Readability: components mix all columns.
- Front
- State the linear SVM objective and what C does.
- Back
- Minimise 1/2 ||w||^2 + C times the sum of hinge losses max(0, 1 - y f(x)). The first term widens the margin (width 2/||w||); the hinge charges points inside it. Low C gives a wide, smooth margin; high C a narrow one that fits training points. Points beyond margin 1 have zero loss. SVMs are not scale invariant.
- Front
- What is the kernel trick, in one example?
- Back
- A kernel computes the inner product of lifted features without building them. For two columns, (x . z)^2 = x1^2 z1^2 + 2 x1 x2 z1 z2 + x2^2 z2^2, the dot product of the lifted vectors (x1^2, sqrt2 x1 x2, x2^2). It lets a linear SVM separate a disc (0.604 linear, 0.978 with x1^2 + x2^2 added).
- Front
- State the naive Bayes assumption and why it still classifies well.
- Back
- Features are independent given the class, so P(y | x) is proportional to P(y) times the product of P(x_j | y). Classification needs only which class scores higher. Duplicating every feature 3 times left accuracy at 0.800 but raised confidence from 0.810 to 0.928: decisions survive, probabilities do not. One dominant duplicate can break it (0.650).
- Front
- What do a Gaussian mixture, Isolation Forest and t-SNE add to k-means and PCA, and what is the catch of each?
- Back
- GMM fits Gaussians with their own covariance by EM (soft assignments, local optimum, BIC for the number of components). Isolation Forest scores points by how few random splits isolate them (shorter path means more anomalous). t-SNE draws 2-3 D maps only: seed-dependent, no transform for new rows, so its islands are not features.
Neural networks and backpropagation: gradients, checks and initialisation
- Front
- Why does a neural network need a non-linear activation?
- Back
- An affine function of an affine function is affine: W2(W1 x + b1) + b2 = (W2 W1) x + (W2 b1 + b2). Without an activation, any number of layers is one linear layer, and XOR cannot be solved (a linear rule gets at most 3 of 4 points). Two ReLU units, relu(a+c) and relu(a+c-1) with output h1 - 2 h2, solve it.
- Front
- Shapes and parameter count of a 2-layer network (d inputs, h hidden units, k classes)?
- Back
- W1 is h x d, b1 is h, W2 is k x h, b2 is k, so there are h(d+1) + k(h+1) parameters: 101,770 for 784, 128 and 10. A batch X of n rows gives Z1 = X W1^T + b1 of shape n x h. A gradient always has the shape of its parameter.
- Front
- Sigmoid and tanh: what is saturation, in numbers?
- Back
- Far from zero both flatten, so their derivatives collapse. Sigmoid derivative: 0.25 at 0, 0.0066 at 5, 4.5e-5 at 10 (never above 0.25). Tanh derivative: 1 at 0, 1.8e-4 at 5, 8.2e-9 at 10. Ten sigmoid layers shrink the derivative part of the gradient by at least 0.25^10, about 1e-6.
- Front
- What is a dead ReLU, and how does GELU differ?
- Back
- The ReLU derivative is exactly 0 for negative inputs, so a unit that is negative on all the data gets no gradient and cannot recover. GELU = z times the normal CDF of z is smooth and gives small non-zero values for negative z (-0.159 at z = -1), so gradients still flow.
- Front
- Write the backward pass of a 2-layer ReLU network with softmax cross-entropy.
- Back
- delta2 = p - onehot(y); dW2 = delta2 a1^T; db2 = delta2; da1 = W2^T delta2; delta1 = da1 * 1[z1 > 0]; dW1 = delta1 x^T; db1 = delta1. Each gradient has its parameter's shape. Cache z1, a1 and p from the forward pass.
- Front
- Why is backprop cheap, and what does it cost in memory?
- Back
- It evaluates the chain rule from the output backwards, reusing the gradient of the layer after and the saved forward values, so one sweep gives every parameter's gradient. The saved activations stay in memory until the backward pass ends and grow with depth and batch size, so training needs more memory than prediction.
- Front
- How do you gradient-check a backward pass, and what errors mean what?
- Back
- Nudge one parameter by +h and -h and compare (L(w+h) - L(w-h)) / 2h with the analytic gradient, in double precision on a few examples. Relative error 1e-7 or less is good; above 1e-2 is probably a bug (CS231n; deeper nets accumulate error, so 1e-2 may be fine for 10 layers). In the lesson the correct code gave 2.4e-11 and a missing ReLU mask gave 1.0.
- Front
- Two cheap sanity checks before training a network?
- Back
- The initial loss should be about ln C for C balanced classes (2.3026 for 10; 0.693 for 2), and the model must be able to overfit a tiny batch to near zero loss (4 points reached 0.0067 in the lesson). If either fails, look for a bug before tuning anything.
- Front
- What causes vanishing and exploding gradients?
- Back
- The gradient through L layers is a product of L per-layer factors (weight scale times activation derivative). Below 1 it shrinks exponentially, above 1 it grows exponentially. In the lesson's 20-layer test the per-layer gradient factor was 0.227 for sigmoid with Xavier weights and 2.10 for ReLU with twice He's variance. Saturation does not guarantee vanishing: tanh with std 1.0 exploded.
- Front
- Xavier versus He initialisation, and why not zero?
- Back
- Xavier: variance 2/(n_in + n_out), about 1/n for a square layer, for roughly linear layers. He: variance 2/n_in for ReLU, which zeroes half the pre-activations; with Xavier a ReLU net had its activation rms multiplied by about 0.71 per layer. All-equal weights, zero included, make every unit in a layer identical, so symmetry never breaks.
Training deep networks: normalisation, regularisation, AdamW and debugging
- Front
- Batch norm versus layer norm?
- Back
- Batch norm takes mean and variance per feature across the batch, so one example's output depends on its batch, the statistics are noisy for small batches (spread about 1/sqrt(B)), and eval mode uses running estimates. Layer norm takes them per example across features and is the same in train and eval, which suits sequences and small batches.
- Front
- What changes between training and evaluation mode?
- Back
- Dropout is on in training and the identity in eval. Batch norm uses batch statistics in training and running estimates in eval. Call model.eval() for validation and serving; torch.no_grad() only turns off gradient tracking and is a separate switch. Forgetting eval() leaves noise and batch dependence in your results.
- Front
- How does dropout work in modern libraries?
- Back
- Training: zero each activation with probability p and multiply survivors by 1/(1-p), so the expected activation is unchanged. Inference: identity. The original paper scaled weights at test time instead; the two agree in expectation. In the lesson's tiny two-moons test, dropout 0.3 helped on only 3 of 8 seeds, so treat the rate as a setting to tune.
- Front
- L2 penalty versus weight decay?
- Back
- The L2 form adds lambda x W to the gradient. Under plain SGD it is equivalent to weight decay once the decay is scaled by the learning rate. Under Adam it is not, because the penalty gets divided by the gradient scale; that is why AdamW decouples the decay. Usually applied to weights, not biases.
- Front
- AdamW versus Adam with L2, in numbers?
- Back
- Adam with L2 divides the penalty by sqrt(v-hat), so its strength follows about 1/G for loss gradient scale G: with decay 0.01 and learning rate 0.001, the extra shrinkage per step was 1e-3 for G = 0, 7.07e-4 for 0.01, 1e-5 for 1 (equal to AdamW) and 1e-7 for 100. AdamW applies w <- w - lr x decay x w before the moment updates: 1e-5 at every G (a stylised setup with w fixed at 1).
- Front
- What does early stopping do, and what must you watch when reporting results?
- Back
- It keeps the weights from the epoch with the lowest validation loss. The best epoch ranged from 2 to 188 over 8 seeds, so it must be found on held-out data. The chosen validation loss is optimistic, so report the final number on a separate test set.
- Front
- What did the two-moons experiment show (30 points, 8 seeds)?
- Back
- No regularisation: train loss 0.123, test loss 0.616, accuracy 0.826. Weight decay 0.01: test loss 0.417 (better on 7 of 8 seeds), accuracy 0.828. Dropout 0.3: 0.595 (better on 3 of 8, within noise), accuracy 0.822. Early stopping beat the last epoch on 8 of 8 seeds (test loss 0.380). Weight decay improved the loss, not the accuracy, and dropout changed little, in this one tiny problem.
- Front
- What do warmup and cosine decay do?
- Back
- Warmup ramps the rate from near 0 to the peak over the first steps (used for large-minibatch SGD and the original transformer: 4,000 steps). Cosine decay then follows eta_min + 0.5 (peak - eta_min)(1 + cos(pi t/T)); a quarter of the way down it is still at 85% of the peak. Why warmup helps Adam is still studied.
- Front
- How does clipping by global norm work?
- Back
- Compute one norm over all parameter gradients as if concatenated; if it exceeds max_norm, multiply every gradient by max_norm/norm. The direction is kept and the length capped; gradients below the limit are untouched. (3, 4) has norm 5 and becomes (0.6, 0.8) at limit 1. It guards against rare spikes.
- Front
- Loss is NaN: what is your checklist?
- Back
- Find the first non-finite step. NaN at step 0: inspect data and labels for NaN or inf, then the loss code (softmax overflow, log of 0; use logsumexp). After a rise: learning rate too high (lower it, warm up, clip). Sudden: a bad batch, zero variance in a norm layer, exploding activations. Then overfit 4 examples and run a gradient check.
- Front
- Loss is flat from the start: what do you check, in order?
- Back
- The initial loss against ln C; whether the model can overfit four examples (if not, a bug in data, loss or backward pass); the learning rate, including a schedule that already decayed to zero; the initial weight scale (tiny init or dead units). The classic slip is a softmax before a loss that expects logits.
- Front
- Softmax before CrossEntropyLoss: what goes wrong?
- Back
- PyTorch's CrossEntropyLoss expects unnormalised logits. Feeding it softmax outputs applies softmax twice; with 3 classes the true-class probability can never exceed e/(e+2), about 0.58 (derived), so learning is weak while the code still runs.
CNNs, ResNets, transfer learning and recurrent networks, with RMSNorm and label smoothing
- Front
- Output size and parameter count of a convolution layer?
- Back
- Per axis: floor((n + 2p - k) / s) + 1, with p zeros on each side; height and width are separate. Parameters: k_h x k_w x c_in x c_out + c_out, independent of the image size. A 3x3 conv from 3 to 64 channels has 1,792; a dense layer to the same 32x32x64 output would need 201,326,592 weights.
- Front
- How do you compute a receptive field for a stack of layers?
- Back
- Start with r = 1 and jump j = 1. For each (kernel k, stride s): r = r + (k - 1) * j, then j = j * s. Three 3x3 stride-1 layers: 7. Three 3x3 stride-2 layers: 15. Pool (2, stride 2) then a 3x3 conv: 6; the other order: 4. Derived here; it matches CS231n's 7x7 for three 3x3 layers.
- Front
- What does weight sharing give a convolution, and what does pooling add?
- Back
- Sharing one kernel across positions gives far fewer parameters and translation equivariance: shift the input and the output shifts. Pooling has no parameters and works per channel; it gives invariance only to shifts inside its window (a pixel moving from position 3 to 4 changed the 2x2 stride-2 pooled output in the lesson's script).
- Front
- Why does y = x + F(x) help deep networks train, and what does it not do?
- Back
- He et al. report degradation (deeper plain nets have higher training error, not from overfitting) and fix it by fitting the residual F(x) = H(x) - x; doing nothing means F near 0. The Jacobian is I + J_F, so a gradient has an identity path (derived here). It does not cap the gradient: an unscaled residual stack returned a gradient norm of 22.6 at depth 50, against 0.0183 plain.
- Front
- What is the fine-tuning recipe, and what must augmentation respect?
- Back
- Pretrain on a source task, copy everything except the output layer, randomly initialise a new output layer, train it from scratch at a larger rate (10x in the book) and fine-tune the rest at a small rate. Freeze the backbone with very little data (common practice). Augmentation is training-only and must keep the label: a left-right flip is fine for a cat, wrong for digits or text.
- Front
- Why do RNN gradients vanish or explode, and what does clipping fix?
- Back
- dh_T/dh_0 is a product over steps of diag(1 - h^2) W_h. With zero input the state stays near 0 and the factor is w: w = 0.9 gives 0.00515 at 50 steps, w = 1.5 gives 6.38e8. With constant input 0.1 the large weight saturates the state (h = 0.894 for w = 1.5, 0.996 for w = 3), the factor w(1 - h^2) is 0.302 or 0.025, and the gradient vanished (7.55e-24 and 6.55e-75 at 50 steps). Clipping caps large gradients but cannot raise vanished ones.
- Front
- Write the LSTM update and say why it helps gradients.
- Back
- i, f, o = sigmoid(...), g = tanh(...); c_t = f * c_(t-1) + i * g; h_t = o * tanh(c_t). The direct derivative of c_t with respect to c_(t-1) is diag(f), with no matrix multiplication or squashing, so gates near 1 keep the gradient (0.99^100 = 0.366, 0.5^100 = 7.89e-31). The full derivative has extra terms through the gates, so this is the direct path.
- Front
- Write the GRU update. Parameter counts for d = 10, H = 20?
- Back
- r, z = sigmoid(...); n = tanh(W_in x + b_in + r * (W_hn h + b_hn)); h_t = (1 - z) * n + z * h_(t-1) in PyTorch's convention; z near 1 keeps the old state. PyTorch has two biases per gate: LSTM 4H(d + H + 2) = 2,560 and GRU 3H(d + H + 2) = 1,920, against 2,480 and 1,860 with one bias. The counts do not depend on sequence length.
- Front
- RMSNorm versus layer norm?
- Back
- RMSNorm divides by sqrt(eps + mean(x^2)) and does not subtract the mean. Both ignore a global rescale; only layer norm ignores adding a constant (x + 5 left layer norm unchanged and changed RMSNorm). The paper says re-centring is dispensable and reports 7% to 64% less running time on its models.
- Front
- Label-smoothed target, loss floor and optimal logit gap?
- Back
- q_k = (1 - eps) * [k = y] + eps / K: for K = 10 and eps = 0.1 that is 0.91 and 0.01. The gradient on the logits is p - q, so the best gap is ln(0.91 / 0.01) = 4.511, and the loss floor is the entropy of q, 0.5003, not 0. Loss values are not comparable across smoothing settings. The paper used eps = 0.1 and reported about 0.2 points of error.
Transformers, large language models, sampling and fine-tuning
- Front
- What does attention compute, and what are the shapes?
- Back
- softmax(Q K^T / sqrt(d_k)) V. Q is n_q x d_k, K is n_k x d_k, V is n_k x d_v; scores n_q x n_k, output n_q x d_v. Self-attention takes Q, K, V from the same X. With n = 10, d_model = 256, h = 4 each head has 10 x 64 queries and a 10 x 10 score matrix.
- Front
- Why divide by sqrt(d_k)?
- Back
- With independent components of mean 0 and variance 1, q.k has variance d_k. Dividing by sqrt(d_k) restores variance 1 so softmax is not saturated. In the script, unscaled scores at d_k = 256 gave a largest weight of 0.9981 and a Jacobian norm of 0.00366; scaled gave 0.2970 and 0.37223 (one draw).
- Front
- How is the causal mask applied, and what goes wrong if it is applied late?
- Back
- Set scores for keys later than the query to minus infinity before the softmax, so those weights are exactly 0 and rows still sum to 1. Zeroing weights after the softmax leaves the future scores in the denominator (information leaks) and rows no longer sum to 1.
- Front
- What is the cost of attention in sequence length?
- Back
- The score matrix is n x n: O(n^2 d) time and O(n^2) memory if stored. Going from 1,000 to 2,000 tokens takes the entries per head from 1,000,000 to 4,000,000, four times as many. Recurrent layers need O(n) sequential steps; attention needs O(1).
- Front
- Why does attention need positions, and how are they added?
- Back
- Unmasked attention treats its input as a set: shuffling the rows shuffles the outputs the same way (a causal mask leaks some position implicitly, per Haviv et al.). Add a position encoding to the embeddings: sinusoidal PE(p,2i) = sin(p / 10000^(2i/d)), PE(p,2i+1) = cos(same angle), a learned table (nearly identical results in the original paper), or rotary embeddings that rotate queries and keys by position.
- Front
- What is byte pair encoding and what is an embedding lookup?
- Back
- BPE starts from characters and repeatedly merges the most frequent adjacent pair into a new token, so rare words become pieces. An embedding lookup selects a row of a V x d_model matrix, equal to a one-hot vector times the matrix. Vocabulary 50,000 and width 768 give 38,400,000 parameters (illustrative).
- Front
- Describe the pre-norm block and why it is preferred.
- Back
- h = x + Attention(Norm(x)), then out = h + MLP(Norm(h)). The residual path is never normalised, and Xiong et al. report well-behaved gradients at initialisation and training without warm-up with comparable results; post-norm, LayerNorm(x + Sublayer(x)), has large gradients near the output at the start.
- Front
- Estimate the parameters of a transformer stack.
- Back
- Per layer 4d^2 (attention) + 2 d d_ff (MLP) = 12d^2 when d_ff = 4d; about 12 L d^2 for L layers, ignoring biases, norms and embeddings. d = 1024, L = 24: 301,989,888. d = 4096, L = 32: 6,442,450,944. Two thirds of a layer is the MLP.
- Front
- GELU versus SiLU?
- Back
- GELU = x Phi(x) with the normal CDF; SiLU = x sigmoid(x). Both are smooth, slightly negative for negative inputs and close to x for large positive ones. At x = -1: GELU -0.1587, SiLU -0.2689; at x = 3: 2.9960 and 2.8577. Which is better is empirical.
- Front
- How is a decoder-only model trained, and how does it generate?
- Back
- Teacher forcing: feed the true sequence once, the causal mask hides the future, position t predicts token t+1, so n tokens give n-1 targets; loss is mean cross-entropy (a uniform guess over 50 tokens: ln 50 = 3.9120). Generation is autoregressive: sample a token, append, repeat.
- Front
- What does the KV cache save and cost?
- Back
- Earlier keys and values do not change, so store them instead of recomputing: 5,050 projections for 100 tokens without a cache against 100 with. Memory: 2 x L x H_kv x d_head x T x bytes per sequence; 32 layers, 32 heads, width 128, 4,096 tokens, 2 bytes: 2.0 GiB; with 8 KV heads: 0.5 GiB.
- Front
- Temperature, top-k and top-p?
- Back
- Temperature divides logits: lower is sharper. Logits [2,1,0.5,0,-1] at T=1 give top probability 0.5630; at T=0.5, 0.8292. Top-k keeps k tokens (k=2: 0.7311, 0.2689). Top-p keeps the smallest set reaching p, so it shrinks when the model is confident. Both renormalise.
- Front
- What does LoRA train, and what does merging do?
- Back
- W' = W + (alpha/r) B A with A r x d_in and B d_out x r, W frozen, B starting at 0. Trained weights r(d_in + d_out): a 4096 x 4096 matrix has 16,777,216 weights, rank 8 trains 65,536 (0.3906%). Merging gives one matrix again, so no extra inference cost.
- Front
- How do SFT, RLHF and DPO differ, and when use RAG or fine-tuning?
- Back
- SFT trains on example answers; RLHF uses ranked answers to train a reward model, then optimises the model against it; DPO uses a classification-style loss on preference pairs without a separate reward model or RL loop. Missing or changing facts and citations: retrieval. Behaviour and style: fine-tuning. Hallucination follows from a likelihood objective with no truth signal.
Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classes
- Front
- Which splitter for which data?
- Back
- Independent rows: k-fold. Rare class: stratified k-fold (every fold keeps about the same class mix). Several rows per patient, user or device: group k-fold (no group on both sides). Time order: forward-chaining, train on the past and test on the next block, with an optional gap. Use the test set once, after every choice is made.
- Front
- Why can cross-validation still mislead you?
- Back
- Choosing the best of many configurations on the same folds makes the winner's score optimistic, so keep a test set for one final look or use nested cross-validation. Small data also gives wide error bars: Varoquaux saw roughly 10 points of uncertainty at about 100 samples in neuroimaging, and the standard error across folds underestimates it.
- Front
- Name the main kinds of leakage and one fix each.
- Back
- Target (a feature known only after the outcome): fix a prediction time and audit features. Preprocessing before the split: fit inside the training fold with a pipeline. Shared entities or duplicates: group k-fold, de-duplicate. Temporal (random split of time data): forward-chaining. Resampling before the split: resample the training fold only.
- Front
- How big can a preprocessing leak be?
- Back
- In the lesson's script, with 100 rows of noise and 2,000 noise features, selecting 10 features on all rows gave a test accuracy of 0.817 and selecting on the training rows only gave 0.492 (chance). The scikit-learn docs show 0.76 against about 0.5 with 200 samples and 10,000 noise features. Put every fitted step in a Pipeline.
- Front
- What are the red flags for a leak, and the cheap checks?
- Back
- Flags: a score too good for the problem, one feature carrying most of the importance, a big gap between cross-validation and a later holdout. Checks: test rows that exactly duplicate training rows, group ids on both sides of a split, and for every feature the question of when it becomes known. In the script, row-level CV on patient data gave 0.944 against 0.490 for group CV.
- Front
- Why does 99.8% accuracy tell you little with 0.2% positives?
- Back
- A model that never flags anything scores 99.8% and finds nothing. Use the confusion matrix, precision (TP over flagged), recall (TP over real positives), F1 (their harmonic mean), and a cost. In the lesson's example a model with lower accuracy and F1 but higher recall was cheaper (12,100 against 26,250 at 5,000 per miss and 50 per false alarm).
- Front
- ROC-AUC versus PR-AUC on rare positives?
- Back
- ROC-AUC is the chance a random positive outranks a random negative, so adding more negatives of the same kind barely moves it (it does not change in expectation). Average precision depends on the positive rate. Same ranker in the script: ROC-AUC 0.903 against 0.911 but AP 0.910 against 0.091 when negatives went from 100 to 49,900. A constant score gets an AP equal to the positive rate.
- Front
- How do you pick a threshold from costs?
- Back
- For calibrated probabilities, predict positive when p exceeds C_FP over (C_FP plus C_FN). A miss of 5,000 and a false alarm of 50 give 0.0099, and in the script that cost 14.54 per row against 191.23 at 0.5, at 20% precision. If capacity is limited, choose the threshold that matches the alert volume. Tune it on validation data, not on the training data.
- Front
- What is calibration and how do you check it?
- Back
- Among cases scored near 0.8, about 80% should be positive. Check with reliability bins, expected calibration error, log loss or Brier score. It is separate from ranking: doubling the logits left ROC-AUC at 0.8346 and moved ECE from 0.011 to 0.093. Fix with Platt sigmoid, isotonic (more than about 1,000 samples) or temperature scaling, fitted on held-out data.
- Front
- MAE, RMSE, R-squared and MAPE: when each?
- Back
- MAE is the typical miss (best constant is the median). RMSE squares errors so big misses dominate (errors 1, 1, 1, 1, 20: MAE 4.8, RMSE 8.99). R-squared compares with predicting the mean. MAPE is unstable near zero: an actual of 0.1 predicted as 1.1 is a 1000% error.
- Front
- In what order do you treat class imbalance?
- Back
- Baseline and a suitable metric, stratified splits with the test set at the natural rate, class weights, tune the threshold on validation, resample only inside training folds if needed, recalibrate, then consider anomaly framing or more labels. Balanced class weights are n over (classes times class count): 0.5051 and 50.0 for 99 negatives and 1 positive.
- Front
- Why must resampling and SMOTE happen inside the fold?
- Back
- Copies or interpolated points of a minority row would sit in both training and validation, and the validation rate stops matching real traffic. In the script, duplicating first gave a balanced accuracy of 0.972 on noise and doing it inside the folds gave 0.495. SMOTE interpolates between neighbours, so its points may be unrealistic and it needs a variant for categorical data.
- Front
- What do weights and resampling do to probabilities?
- Back
- They keep the ranking but shift the probabilities: weighting positives by w multiplies the odds by w, so a true 0.01 becomes 0.500 at w = 99. Recalibrate on held-out data at the natural rate before using the score as a probability or in a cost-based threshold.
- Front
- What do baselines and error analysis add?
- Back
- A metric means little without a baseline: DummyClassifier most_frequent, a constant score (AP equal to the positive rate), the base-rate log loss, a simple model, and the current rule. Then slice: 9,000 rows at 95% and 1,000 at 70% make 92.5% overall. Read the worst errors, group them by cause and fix the biggest group first.
Statistics and experimentation: intervals, tests, power, A/B tests and fair model comparison
- Front
- What is the standard error of a sample mean, and what does quadrupling n do?
- Back
- It is sigma / sqrt(n): the spread of the sample mean across repeated samples. Quadrupling the data halves the noise. The shape of the sampling distribution is Gaussian only for large n: with skewed data and n = 5, only 0.1% of means fell below the mean minus 1.96 SE and 4.4% fell above the mean plus 1.96 SE.
- Front
- What does a 95% confidence interval mean?
- Back
- The procedure that built it contains the true value in about 95% of repeated experiments. It is not a 95% probability that the parameter is in the one interval you computed, and it is not a range for single observations.
- Front
- Bias versus variance of an estimator: when does a biased one win?
- Back
- Mean squared error is bias squared plus variance. For a mean of 0.5 from 10 draws with sd 1, the sample mean had an error of 0.1003 and 0.8 times the mean had 0.0743: a bias of -0.1 bought a larger cut in variance. Dividing squared deviations by n averages 0.798 for a true variance of 1 at n = 5, so use n - 1.
- Front
- When do you use the bootstrap, and when does it fail you?
- Back
- When no formula exists for the statistic (median, AUC, ratio): resample with replacement, compute the statistic, read the percentiles. It does not rescue small or heavy-tailed samples: on lognormal data with n = 15 both the normal-approximation and the percentile intervals covered the true mean only about 80% of the time, and 96% of the misses were below the true mean.
- Front
- State what a p-value is and three things it is not.
- Back
- The probability, assuming no effect, of data at least as extreme as observed. It is not the probability that the null is true, not the size of the effect and not proof of importance. A large p-value from a small test is inconclusive, not evidence of no effect.
- Front
- Which test for which data?
- Back
- Two conversion rates: two-proportion z-test with the pooled error. Two means: t-test (Welch if variances differ). Counts against a design (SRM): chi-square goodness of fit, with observed and expected counts at least 5. Small or odd data, or any statistic: permutation test, exact when every split can be listed, otherwise (extreme + 1) / (B + 1).
- Front
- Type I error, type II error, power: define each.
- Back
- Type I: rejecting a true null, probability alpha. Type II: keeping a false null, probability beta. Power is 1 - beta, the chance of detecting a real effect of the assumed size. Under a true null the p-value is uniform: 2,000 A/A tests gave 4.1% below 0.05 and 49.5% below 0.5.
- Front
- How do you size an A/B test, and what does halving the lift cost?
- Back
- Fix the metric, baseline, minimum effect, alpha and power. For two proportions n = (z_alpha/2 + z_power)^2 (p1 q1 + p2 q2) / (p1 - p2)^2 per arm. At a 10% baseline: 3,839 for 12%, 14,749 for 11%, 57,760 for 10.5%. Halving the lift quadruples n. A shortcut is n = 16 sigma^2 / delta^2.
- Front
- Bonferroni versus Benjamini-Hochberg?
- Back
- Bonferroni tests each of m hypotheses at alpha / m and controls the chance of any false positive; it is strict. BH controls the expected share of false discoveries and rejects more. With p = 0.001, 0.012, 0.018, 0.030, 0.45 Bonferroni rejects 1 and BH rejects 4 at q = 0.05. With 20 true nulls the chance of at least one p < 0.05 is 0.642.
- Front
- Why is peeking a problem and what replaces it?
- Back
- Every look is another chance to cross the threshold. In 1,000 simulated A/A tests with up to 10 looks the false-positive rate was 0.058 at the planned end and 0.219 when stopping at the first significant look. Use a fixed horizon, or a sequential method built for continuous monitoring.
- Front
- What is a sample ratio mismatch and what do you do?
- Back
- The arm sizes differ from the design by more than chance allows: check with a chi-square test on the counts. 50,500 against 49,500 gives chi-square 10.0 (p = 0.0016); 520 against 480 gives 1.6 (p = 0.206). When it fires, find the assignment or logging bug first and do not read the treatment effect.
- Front
- What goes wrong if you randomise by user but analyse by page view?
- Back
- Views from one user are correlated, so the standard error is too small by a design effect 1 + (m - 1) rho. With m = 20 views and rho = 0.0909 it is 2.73, and 21.4% of A/A tests came out significant at 5%. Analyse at the level you randomised.
- Front
- The offline metric improved and the A/B test shows nothing. What do you check?
- Back
- In order: power for the expected lift, then metric mismatch (offline metric is not what users respond to), then selected or stale offline data, distribution shift, a training-serving bug and novelty. Keep guardrails in every test.
- Front
- Why can a correlation not prove that X causes Y?
- Back
- A confounder can drive both. With a hidden Z behind X and Y, the correlation was 0.502 although X had no effect; assigning X at random gave -0.008. Randomisation is the clean fix. Without it, designs such as matching or difference-in-differences need stated assumptions.
- Front
- Why compare two models with a paired test?
- Back
- They are scored on the same items, so errors overlap. On 1,000 constructed items with accuracies 0.770 and 0.798, McNemar on the disagreements (29 and 57) gave p = 0.0036 while the unpaired test gave p = 0.128. Report an interval for the gain. McNemar uses one training set, so it ignores training-set variability.
- Front
- Why is a plain t-test on cross-validation or repeated splits too optimistic?
- Back
- Training sets overlap, so scores are positively correlated and the variance is underestimated. The Nadeau-Bengio statistic uses (1/k + n_test / n_train) s^2 under the root. On ten constructed gaps from 90/10 splits it cut t from 8.95 to 6.16. Dietterich found the random-split t-test has a high type I error rate.
- Front
- Work the base-rate problem: 1% prevalence, 90% sensitivity, 10% false-positive rate.
- Back
- Use natural frequencies for 10,000 people: 100 sick, 90 test positive; 9,900 healthy, 990 test positive. P(sick | positive) = 90 / 1,080 = 0.0833. With 99% and 5% it is 0.1667; at 10% prevalence it is 0.5. Rare condition, mostly false alarms.
Data, features and production ML: preprocessing, encodings, point-in-time features, skew, drift and operations
- Front
- What are MCAR, MAR and MNAR, and which one can the observed data repair?
- Back
- MCAR: missingness depends on nothing, so the observed rows are a fair sample. MAR: it depends on other observed columns, so imputing within groups of those columns repairs the bias (observed mean 47.58, group-wise fill 50.00, true 50.06). MNAR: it depends on the missing value itself, and the observed data cannot fully repair it (48.36 after the same fill).
- Front
- Why add a missing indicator next to an imputer?
- Back
- Missingness is often a signal. In the script a lab value was missing for 70% of healthy and 20% of sick patients: disease rate 0.109 where missing, 0.538 where measured. A filled column hides that. The indicator keeps it. SimpleImputer(add_indicator=True) adds one.
- Front
- What goes wrong when you mean-impute a column?
- Back
- The mean of the observed values stays wrong if the missingness is MAR or MNAR (47.58 against a true 50.06), and the spread shrinks even under MCAR: sd 8.35 against a true 9.94 with about 29% filled. The model also sees no trace that a value was filled, unless you add an indicator.
- Front
- State the rule for fitting preprocessing, and what breaks if you ignore it.
- Back
- Learn every statistic (fill value, mean, category list, encoding) on training rows only, and apply it unchanged elsewhere. Fitting on train and test hid a real shift: a test mean of 1.529 looked like 0.617 after scaling. A pipeline makes the rule automatic inside cross-validation.
- Front
- One outlier in a column: what does standard scaling do, and what are the alternatives?
- Back
- One value of 1,000 among 99 values with sd 2 pushed the standard deviation to 98.49 and shrank the scaled spread of the other values from 1.000 to 0.020. Median and IQR scaling kept it at 0.794. Also clip, or log-transform a skewed feature (skewness 5.15 became 0.02). Trees do not need scaling.
- Front
- Which encoding for which categorical feature?
- Back
- Few unordered levels: one-hot. Real order: ordinal. Many levels with a supervised signal: target encoding, out-of-fold and smoothed. Huge or open vocabularies: hashing (500 categories in 256 buckets still left 438 sharing a bucket) or learned embeddings. Cyclical numbers such as the hour: sin and cos.
- Front
- Why does target encoding leak, and what is the cure?
- Back
- A row's own label sits inside its own encoding if it is fitted and applied on the same rows. With labels independent of the category, the in-sample AUC was 0.770 and the out-of-fold AUC 0.501. Encode each fold from the other folds, use the full-train encoding for test and live rows, and give unseen levels the prior. Leave-one-out is not safe: on one constant level its training AUC was 0.000 against 0.473 for 5-fold.
- Front
- Write the smoothed target encoding and say what the smoothing does.
- Back
- (sum of targets in the level + m x overall mean) / (rows in the level + m). A level with few rows is pulled to the overall mean. With overall mean 0.3220 and m = 10, a one-row level with target 1 became 0.384 (raw 1.000) and a 100-row level at 0.800 became 0.757. It is a safeguard for rare levels, not a leakage fix.
- Front
- When does a feature cross help?
- Back
- When the effect exists only in a combination and the model is additive. With y positive when x1 times x2 is above 0, the best sign rule on x1 scored 0.500 and on x2 0.504, while the cross scored 0.952. Trees and networks learn crosses themselves. Crosses of high-cardinality features explode in width.
- Front
- State the point-in-time rule and two ways to break it.
- Back
- A feature for a prediction at time t may use only information that existed at t. Break it with a window that reaches past t, or by joining the latest value instead of the value as of t. Counting 7 days past t raised churn AUC from 0.773 to 0.921, from information that does not exist at prediction time.
- Front
- How does a point-in-time join work?
- Back
- For each event (key, time) take the latest feature row with the same key and a time not after the event, and ignore it if a TTL says it is too old. Rows (time 1, 3), (5, 4), (9, 10): an event at 8 gets 4, an event at 0 gets nothing, an event at 100 gets 10 or nothing with a TTL of 3. Rolling features use only earlier values.
- Front
- What is training-serving skew and how do you defend against it?
- Back
- A difference between performance in training and in serving, caused by different handling of data in the two pipelines, a change in the data, or a feedback loop. Defences: reuse code, log the features you served and compare, golden tests, monitoring. A 0 instead of the median for nulls cut precision from 0.831 to 0.556.
- Front
- What does a Pipeline with a ColumnTransformer buy you, and what does it not?
- Back
- One fitted object holds preprocessing and model, so cross-validation refits imputers, scalers and encoders in each fold and the saved object is the served one. By default unnamed columns are dropped (remainder='drop'). It does not cover features computed outside it, such as SQL joins and windows.
- Front
- Name the three kinds of drift and where each shows.
- Back
- Covariate (data) drift: P(X) changes with P(y | X) fixed, seen in input distributions with PSI or KS. Label shift: P(y) changes with P(X | y) fixed, hinted by the predicted positive rate (P(X) also moves, so input PSI can fire too). Concept drift: P(y | X) changes, seen only in labelled outcomes. Real changes can mix. Inputs PSI 0.0003 with accuracy falling from 1.000 to 0.659 is concept drift.
- Front
- Compute PSI and name its pitfalls.
- Back
- PSI = sum over bins of (actual share - expected share) x ln(actual / expected). Shares (0.5, 0.5) against (0.3, 0.7) give 0.1695. Pitfalls: empty bins need a floor (a new category gave 0.708 or 1.170 for floors of 1e-4 or 1e-6), bins change the value (0.2060, 0.2417, 0.2669 for 5, 10, 20 bins), and small samples add noise: about 0.095 at 100 rows with no drift.
- Front
- What does the KS statistic measure and what is its large-sample problem?
- Back
- The largest gap between two empirical CDFs, with no bins. With 100,000 rows each side, a mean shift of 0.02 gave KS 0.0076, above the approximate 5% critical value 0.0061, while PSI was 0.00033. A test can flag a shift too small to matter, so pair it with a size threshold.
- Front
- How do you monitor a model with delayed labels?
- Back
- Watch data quality, feature and score drift now; report true metrics by cohort once labels mature; compare cohorts of the same age. With a mean delay of 20 days, a 14-day-old cohort had only 0.510 of its positives labelled (rate 0.0253 against 0.0496).
- Front
- Compare retraining triggers.
- Back
- Schedule, drift threshold, performance drop on matured labels, or enough new labelled data. In the toy drift run: never 0.609 mean accuracy, every 10 weeks 0.908 with 3 retrains (worst week 0.673), accuracy trigger 0.952 with 15 retrains (worst week 0.854). Cost of retraining against cost of staleness decides.
- Front
- Describe a safe rollout and the feedback-loop trap.
- Back
- Offline validation, shadow mode (score but do not act), canary with guardrails, ramp, with rollback and a fallback. Feedback loop: if only approved applicants have outcomes, a retrained model never learns about the rejected. Keep an exploration or hold-out slice where decisions do not depend on the model.
- Front
- What do you record to reproduce a model, and why?
- Back
- Code version, a snapshot or hash of the training data, feature definitions, library versions, hyperparameters and seeds, stored with the model. A hash of a dataset changed when one cell changed. It lets you answer what changed and restore the previous model.
- Front
- In what order do you debug a model that works in the notebook and fails in production?
- Back
- 1 Inputs valid (schema, nulls, units, ranges). 2 Skew: served against training features for the same case. 3 Leakage in the original evaluation. 4 Drift (PSI per feature). 5 Label or definition mismatch. 6 Silent fallbacks, timeouts, wrong artifact. 7 Only then a real concept change: retrain or redesign.
ML system design: framing, budgets, two-stage retrieval, serving, rollout and monitoring
- Front
- When should you not start with ML, and what do you ship instead?
- Back
- When rules already solve the problem acceptably, there is no label or feedback signal, an error is too costly without human review, or explainability rules out opaque models. Ship a heuristic baseline first, log its decisions and corrections as labels, and build a model only if the remaining errors justify the cost.
- Front
- Business goal, training objective and metric. How do they differ, and what is a guardrail?
- Back
- The goal is why the system exists (more orders). The objective is what the model optimises (probability of an order). Metrics decide whether it worked (NDCG@k offline, order rate online). A guardrail is a metric you will not let get worse, such as delivery ETA or cancellations. A proxy objective such as clicks can rise while the goal falls.
- Front
- List the nine steps of the ML system design framework.
- Back
- 1 Clarify and frame. 2 Data and labels. 3 Baseline. 4 Features. 5 Model. 6 Offline evaluation. 7 Serving. 8 Online evaluation and rollout. 9 Monitoring and risks. A suggested 35-minute split is 4, 4, 2, 4, 5, 3, 5, 3, 5 minutes. Say the trade-off, start with a baseline, name the failure mode first.
- Front
- Batch, online and streaming inference. When does each fit?
- Back
- Batch: scores computed on a schedule, good when freshness tolerates it, stale between runs. Online: computed per request, needs a tight latency budget. Streaming: features updated as events arrive, most moving parts. Real systems mix them, using the slowest mode each feature's freshness allows.
- Front
- State Little's law and use it to size a service.
- Back
- In flight L = arrival rate x time in system. Feed example: 694.44 requests per second x 0.060 s = 41.7 in flight. With 8 concurrent per server loaded to 50%, each carries 4, so 11 servers; at $0.40 per server-hour that is $5.28 per million requests. Every assumption (peak factor, service time, utilisation) is a lever to state.
- Front
- Why budget p99 latency instead of the mean, and how do parallel calls combine?
- Back
- In the script the mean was 45.2 ms but p99 was 126.2 ms and the slowest request 277.5 ms. Serial steps add; parallel calls cost the slowest one (5 + [10, 40] = 45 ms, not 55). With 10 parallel calls each slow 1% of the time, 1 - 0.99^10 = 0.0956 of requests wait on a slow one.
- Front
- What is a timeout with a fallback, and what does it cost?
- Back
- Stop waiting at a threshold and return a cheaper answer. A 100 ms timeout with a 5 ms fallback sent 3.20% of requests to the fallback and capped the slowest served request at 105.0 ms instead of 277.5 ms. The price is quality on those requests, so the fallback rate is a metric to alert on.
- Front
- Why use a retrieve-then-rank funnel, and what does each stage optimise?
- Back
- Scoring every item with the best model is too slow or costly. Candidate generation (two-tower plus ANN, popular, recent) keeps a few hundred and is judged by recall. The ranker orders them with rich features and is judged by NDCG or precision at the top. The re-ranker applies diversity, rules, fairness and exploration.
- Front
- Why does final quality depend on retrieval recall? Give the numbers.
- Back
- The ranker cannot promote an item it never sees. In the synthetic funnel, final NDCG@10 was 0.472 with 50 candidates (recall 0.165), 0.772 with 500 and 0.903 with 2,000, against 0.944 when the ranker scored all 20,000 items. More candidates raise quality and ranker cost together.
- Front
- Define recall@k and NDCG@k.
- Back
- Recall@k = relevant items in the top k divided by all relevant items. NDCG@k = DCG@k / ideal DCG@k, where DCG sums gain / log2(rank + 1). A perfect list scores 1. By hand, gains 1 and 3 in the order (1, 3) give 2.893 / 3.631 = 0.797.
- Front
- What are the special problems of fraud and ads designs?
- Back
- Fraud: extreme imbalance, delayed and selective labels (keep a random approval holdout), adaptive adversaries, a decision from costs: act when p > F / (F + L), for example 4 / 84 = 0.0476, which needs calibrated scores. Ads: value is pCTR x bid, so calibration matters; an overstated pCTR (0.04 instead of 0.02) doubles the value from $0.03 to $0.06.
- Front
- How do you keep training and serving features consistent?
- Back
- Use one feature definition for both paths, re-use code, log the features actually served, and train on the logs. A feature store (offline side with point-in-time joins, online side for low latency) gives the definition a home; it adds a system to run, so it pays off when many models share features.
- Front
- Name the four serving levers and the cost of each.
- Back
- Cache: stale answers and a hit rate that depends on skew (0.391 at 1% of keys in the script). Batching: throughput up, latency up (batch 16 gives 1000 items/s at 16 ms). Quantisation: 400 MB to 100 MB for 100M parameters, some accuracy lost. Distillation: train a smaller student from a larger teacher, pay for training twice.
- Front
- Describe the rollout ladder.
- Back
- Offline evaluation, then shadow (score and log, users see nothing), canary (small share of real traffic), A/B test (randomised, primary metric with guardrails), ramp to 100%, with rollback ready at each stage. Each step answers a different question: does it run, does it break anything, is it better, does it hold at scale.
- Front
- What is a feedback loop in an ML system, and how do you limit it?
- Back
- The model's output changes what users see, which changes its next training data. In the toy loop, always showing the best observed item gave one item 0.998 of impressions and found the truly best item in 14 of 100 runs. Exploring 10% of the time found it in 55 of 100. Keep an exploration or random holdout slice and log propensities.
- Front
- What should you monitor after launch beyond accuracy?
- Back
- Data quality, feature drift, score drift, and performance once labels mature, plus latency percentiles, error and timeout rates and the fallback rate. A fallback rate that rises unnoticed means users quietly get a worse answer while accuracy on the requests the model did answer looks fine.
- Front
- Name the ML-specific risk factors from the technical debt paper and a defence for one.
- Back
- From its abstract: boundary erosion, entanglement, hidden feedback loops, undeclared consumers, data dependencies, configuration issues, changes in the external world, system-level anti-patterns. Defence example: for undeclared consumers, version your outputs and keep a registry of who reads them. Every part needs an owner, a test and a monitor.
- Front
- What belongs in a fallback and human-review design?
- Back
- A fallback ladder (full model, cheaper model, cached or popular default, rule) decided in advance, timeouts shorter than each call's budget share, an explicit fail-open or fail-closed choice for safety checks, and human review for the uncertain middle band and costly errors. Reviewer capacity and alert fatigue limit how wide that band can be.
Training at scale: memory arithmetic, parallelism, mixed precision and scaling laws
- Front
- How much memory per parameter does mixed-precision Adam need, and what is in it?
- Back
- 16 bytes, before activations. 2 for fp16 weights, 2 for fp16 gradients, and 12 for optimizer states (an fp32 copy of the weights plus two fp32 Adam moments). A 7B model needs 112 GB of state; 1.5B needs 24 GB; 70B needs 1,120 GB. Activations, buffers and fragmentation come on top.
- Front
- Which memory line item grows with batch size and sequence length?
- Back
- Activations. Weights, gradients and optimizer states depend on the parameter count and the optimizer. So a model whose state fits can still run out of memory when you raise the batch, and the fixes (smaller micro-batch, checkpointing) target activations.
- Front
- What is the linear scaling rule, and why warmup?
- Back
- Multiply the batch by k, multiply the learning rate by k, keep other hyperparameters. It assumes the gradient barely changes over k steps, which fails early in training, so ramp the rate gradually to the target. In the ImageNet study it held from batch 64 to 8,192 and degraded after. Re-tune for adaptive optimizers.
- Front
- How do you accumulate gradients correctly, and what does it not fix?
- Back
- Add the per-sample gradients of each micro-batch and divide by the total number of samples once, so a short last chunk counts for its size. In the lesson script the weighted result matched -28.885, an unweighted mean gave -35.375 and an undivided sum -106.125. Batch norm still sees only the micro-batch. For token-level losses (causal LMs), sum the token losses and divide by the total non-padding tokens of the effective batch, not by an average of per-micro-batch means.
- Front
- Why master weights, loss scaling, and dynamic scale in fp16 training?
- Back
- Master weights, because 1.0 + 0.0001 rounds back to 1.0 in fp16, so small updates must accumulate in fp32 (100 updates give 1.0100 against 1.0). Loss scaling, because a gradient of 1e-8 flushes to 0 in fp16 and is kept at scale 1,024. Dynamic scale, because too large a scale overflows to infinity (max 65,504): skip the step and halve on overflow, double after a clean run.
- Front
- What does DDP do, and what does it not do?
- Back
- Every device holds a full model copy, runs its slice of the batch, and the gradients are averaged with a bucketed all-reduce overlapped with the backward pass, so all copies apply the same update. It does not reduce memory per device. Ring all-reduce time is about 2S/B almost regardless of the device count.
- Front
- What do the ZeRO stages shard, and what does FSDP call them?
- Back
- Stage 1 shards optimizer states, stage 2 adds gradients, stage 3 adds weights. For a 7B model on 8 devices that is 38.5, 26.2 and 14.0 GB against 112 GB. Stage 3 costs about 50% more communication in the paper. FSDP FULL_SHARD is the stage-3 analogue and SHARD_GRAD_OP the stage-2 analogue; HYBRID_SHARD shards in a node and replicates across nodes. PyTorch 2.15 also ships FSDP2 (fully_shard, per-parameter DTensor sharding) and suggests FSDP1 users consider migrating.
- Front
- Tensor versus pipeline parallelism. Where does each run, and what is the bubble?
- Back
- Tensor parallelism splits matrices inside a layer and communicates in every layer, so keep it inside a server. Pipeline parallelism splits layers into stages and passes activations. The bubble is the idle share, (p - 1) / (m + p - 1): 8 stages with 63 microbatches give 10%. More stages need more microbatches, so a bigger batch.
- Front
- What does activation checkpointing trade, and how much?
- Back
- Memory for compute. Keep k segment boundaries and recompute the rest in the backward pass. Peak is about k + n/k layer units, best near the square root of n (100 layers: 100 units down to 20). The price is one extra forward pass, about a third more compute if backward is twice forward. Chen et al. report about 30% more time.
- Front
- How do you tell a data-loader bottleneck, and how many workers do you need?
- Back
- Accelerator utilisation is low and step time falls when you add loader workers or does not depend on the model. A step takes max(compute, load / workers). With compute 0.25 s and load 0.9 s per worker, 1 to 4 workers give 0.9, 0.45, 0.3 and 0.25 s. Workers beyond 4 change nothing.
- Front
- What goes in a checkpoint, and how often should you write one?
- Back
- Weights, optimizer states, schedule and step position, data position and random states, written per shard in sharded training so they can reshard on load. First-order best interval is sqrt(2 x write x MTBF): 3 min write and a failure every 360 min give 46.5 min and about 13% of time lost. Reproducible experiments, not bit-identical runs.
- Front
- Estimate the cost of training a model.
- Back
- FLOPs about 6ND (N parameters, D tokens: 2N forward, 4N backward per token), days = FLOPs / (devices x peak x utilisation x 86,400). 7B parameters on 1T tokens is 4.2e22 FLOPs, 3.96 days on 1,024 devices at an assumed 300 TFLOP/s peak and 40% utilisation. State the assumptions. The rule ignores attention cost. Against the paper's 5.76e23 for Gopher's budget, 6ND is 12.5% low for Gopher and 2.1% high for Chinchilla.
- Front
- What did Kaplan and Hoffmann find about model size and data?
- Back
- Kaplan et al.: loss follows power laws in size, data and compute, and large models on modest data are compute-efficient. Hoffmann et al.: scale model size and tokens in equal proportion. Chinchilla (70B, 1.4T tokens) beat Gopher (280B, 300B tokens) at the same compute. About 20 tokens per parameter is that one result's ratio, not a law, and ignores serving cost.
The ML interview playbook: structure, answer method, debugging procedures, estimates and project defence
- Front
- Name the common ML interview round types and the method for each.
- Back
- Fundamentals (ladder: intuition, maths, code, pitfall), coding (clarify, simple version, edge cases, then speed), system design (nine steps), applied case (ten-step method), project deep dive and behavioural (STAR). This is a common pattern, not a verified list for any company, so ask the recruiter what each round covers.
- Front
- How should you treat the six-round map of an ML interview loop?
- Back
- As a common pattern. Loops differ by company and level, rounds overlap (a coding question can turn into how you would evaluate it), and names vary. Check the actual loop with the recruiter.
- Front
- List the ten steps of the answer method for an open ML question.
- Back
- 1 Clarify, 2 state assumptions, 3 baseline, 4 metric, 5 data, 6 model, 7 evaluation, 8 failure modes, 9 trade-offs, 10 monitoring. Say the step names aloud so the interviewer can redirect you. The baseline and metric come before the model.
- Front
- What is the ladder for explaining a concept, and which rung signals experience?
- Back
- Intuition, maths, code, pitfall. The pitfall rung (when it fails, what is commonly misread) signals that you have used the idea. Stop at the rung where the interviewer signals enough.
- Front
- What do you do when you are stuck or cannot recall a formula?
- Back
- Restate the question, start from the smallest case, state assumptions, name a baseline, or ask a clarifying question. Say plainly that you do not remember the exact form, then give the idea and how you would derive it. Do not invent a half-remembered formula.
- Front
- Loss is NaN. What is the first step?
- Back
- Find the first step at which anything is non-finite before changing anything. NaN at step 0 points to data, labels or the loss code (log of zero, softmax overflow). A loss that rose first points to a too-high learning rate. A sudden jump points to a bad batch or a division by zero variance.
- Front
- Loss is flat from step 1. What is the first step?
- Back
- Check the starting loss against the expected value (about ln C for C classes, since a uniform prediction gives ln C), then try to overfit a tiny batch. If it cannot, suspect a pipeline bug. If it can, tune the learning rate, initialisation or normalisation.
- Front
- Validation score is too good to be true. Name three checks.
- Back
- Each catches a different leak. Shuffle the labels and rerun the whole pipeline: a score well above chance means label-using preprocessing (target encoding or feature selection on all rows). Count ids shared between training and validation: group leaks. Inspect the top feature: proxies known only after the outcome (a proxy falls to chance on shuffled labels, so the shuffle misses it). In the script a proxy scored AUC 1.000 against 0.718 for an honest feature, the chance baseline on shuffled labels was 0.503, and a target-encoded noise category scored 0.758, still 0.784 on shuffled labels.
- Front
- Offline metric up, A/B flat. In what order do you check?
- Back
- Cheapest first: the experiment itself (assignment, sample ratio, power), then serving features against training features (skew), then whether the offline metric matches the business metric, then novelty or interference. Do not extend the test until it turns significant.
- Front
- Give the base-rate formula and the worked example.
- Back
- PPV = pi s / (pi s + (1 - pi) f). With 10,000 people, 1% sick, 99% sensitivity and a 5% false-positive rate: 99 sick positives and 495 healthy positives, so 99 / 594 = 0.1667.
- Front
- Why compute the majority baseline, and what did the script show?
- Back
- Accuracy means nothing without it. With 100 frauds in 10,000, always predicting legitimate scores 0.9900. A model at 0.9920 accuracy had precision and recall of 0.60 each, which is what tells its story.
- Front
- How do you count parameters and forward FLOPs of a dense network?
- Back
- A layer has in x out weights plus out biases. A forward pass costs about 2 x batch x in x out operations. Widths 784, 256, 128, 10 give 235,146 parameters (0.94 MB in fp32) and 469,504 operations per example. State your throughput assumption (an assumed 10 GFLOP/s gives 3.0 ms for a batch of 64).
- Front
- How sure is 182 correct out of 200, and why is 3 points over 176 not a claim?
- Back
- The 95% Wilson interval is 0.862 to 0.942, against 0.828 to 0.918 for 176 of 200, so they overlap heavily. With ten times the data they are 0.897 to 0.922 and 0.865 to 0.894. Both models share the test items, so compare them with a paired test.
- Front
- What does a strong project story contain beyond STAR?
- Back
- The baseline you compared against, the evaluation design (split by time or group, leakage checked), a measured result with its uncertainty, and what you would change. One university career centre (UW) suggests roughly 20% situation, 10% task, 60% action and 10% result. Claim only what you measured.
- Front
- Name five common traps in ML interview answers.
- Back
- Hand-waving, a metric without a baseline, ignoring leakage, jumping to a model before the frame, false precision, reciting without a failure case, silence, bluffing a formula, over-claiming a team's work.
- Front
- What is a repeatable mock-interview routine?
- Back
- Short daily drills (90 seconds aloud), a weekly 45-minute mock (5 intro and project, 12 fundamentals, 25 design or coding, 3 your questions), and a one-line rule for each miss, re-answered cold a few days later. That time split is this course's suggestion, not a rule.