ML fundamentals and statistics
Named in 52% of 2253 senior postings · 42 review cards
The breadth round: generalisation, losses and metrics, classical models, feature engineering, statistics and probability, the maths underneath, and the applied specialities that sit on top of them (forecasting, fraud and risk, causal inference, calibration, labelling). Half of the postings name at least one skill in this area, and ML-engineer postings name it most often, usually as “strong ML fundamentals” plus statistics. Interviewers use it to check that a candidate can reason from first principles when a model misbehaves, not only run a library.
What the postings ask for
Share of postings that name each skill, overall and by track.
| Skill | All postings | MLE | AI eng | Research eng | Cards |
|---|---|---|---|---|---|
| Machine learning fundamentals | 28% | 8% | 16% | 11 | |
| Statistics and probability | 20% | 8% | 14% | 7 | |
| Data labeling, curation and quality | 16% | 10% | 20% | 4 | |
| Classical models (GBDT, linear, trees) | 16% | 11% | 3% | 4 | |
| Anomaly, fraud and risk detection | 11% | 7% | 6% | 2 | |
| Data analysis (pandas, numpy, notebooks) | 10% | 6% | 7% | 1 | |
| Feature engineering | 14% | 3% | 2% | 3 | |
| Linear algebra, calculus, optimization math | 6% | 4% | 6% | 4 | |
| Time series and forecasting | 5% | 4% | 5% | 2 | |
| Bayesian and probabilistic modeling | 6% | 2% | 7% | 2 | |
| Causal inference | 5% | 1% | 2% | 2 |
In the postings’ words
5+ years of experience optimizing ML algorithms, configurations, and infrastructure
Advanced degree (Master’s or Doctorate) in Computer Science, Machine Learning, Statistics, or a related quantitative field
Experience building batch and streaming data pipelines and feature stores (e.g., Spark, Flink, Kafka), with attention to data quality and training/serving skew.
Roblox · Senior Software Engineer (Machine Learning) - Economy ML
You operate systems reliably as on-call and root-cause at least one significant production regression.
Experience working on content moderation, spam detection, fraud, or Trust & Safety ML teams.
Python for tooling and analysis, e.g. NumPy and trimesh.
Experience designing and operating production ML systems, including several of: large-scale data and feature pipelines, distributed model training, low-latency inference, model deployment, or production monitoring.
The senior bar
What separates a senior answer from a mid-level one in this area.
- Derives the standard results on a whiteboard (logistic loss and gradient, the XGBoost split gain, the downsampling correction, a sample-size formula) and says what each implies in practice.
- Treats evaluation as a design problem. Chooses the split unit and time gap that match deployment, names the leakage paths, and puts an interval on every reported number.
- Separates ranking quality from calibration and from the decision threshold, and knows which of the three a given product needs.
- Knows what the labels really are. Asks about delay, selection by the previous model, annotator agreement and sampling before trusting a metric.
- Reaches for the simple strong baseline first (regularised linear model, tuned GBDT, seasonal naive) and can say when it stops being enough.
- States the assumptions behind a statistical or causal claim, and what would falsify them, instead of quoting a p-value.
Skills, checklists and questions
Tick an item when you can explain it without notes; ticks are saved in this browser. Open a question to see the answer.
Machine learning fundamentals 16% of postings
- Write the bias-variance decomposition and diagnose which term dominates from learning curves
- Explain why L1 gives exact zeros and L2 does not, with the Laplace and Gaussian prior view
- State what double descent shows and what it does not
- Design a split that matches deployment (group, time, gap) and list the common leakage paths
- Derive the probability correction after negative downsampling and after class weighting
- Say when ROC-AUC, PR-AUC, log loss and NDCG disagree and which one a product needs
- Implement k-means and ROC-AUC from scratch and state their complexity
coreconceptMLE AI REasked at Nvidia, Amazon Explain the bias-variance decomposition. In practice, how do you tell which of the two is limiting a model, and what do you change in each case?
For squared loss at a point \(x\), with \(y = f(x) + \varepsilon\), \(\mathbb{E}[\varepsilon]=0\), \(\operatorname{Var}(\varepsilon)=\sigma^2\), and the expectation taken over training sets \(D\):
\[ \mathbb{E}\big[(y-\hat f_D(x))^2\big] = \underbrace{\big(\mathbb{E}_D[\hat f_D(x)]-f(x)\big)^2}_{\text{bias}^2} + \underbrace{\operatorname{Var}_D[\hat f_D(x)]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}} \]
Diagnosis comes from learning curves, not from the formula:
- High bias: training and validation error are both high and close together; more data does not help.
- High variance: a large train-validation gap; validation error keeps improving with more data; results move a lot across seeds or folds.
Fixes. Bias: more capacity, better features, less regularisation, longer training. Variance: more data, regularisation, early stopping, a simpler model, or averaging. Averaging \(M\) models with variance \(\sigma^2\) and pairwise correlation \(\rho\) gives variance \(\rho\sigma^2 + (1-\rho)\sigma^2/M\), which is why bagging works only as far as the models are decorrelated.
Caveats. The additive form is specific to squared loss. Variance is not monotone in parameter count for over-parameterised models (double descent). The noise term is a floor you should estimate, for example from agreement between duplicate labels, before chasing the last point of error.
Follow-ups
- Why does bagging reduce variance but not bias, while boosting mainly reduces bias?
- How would you estimate the irreducible error on a real dataset?
coretrade-offMLE AI RE Compare L1 and L2 regularisation. Why does L1 produce exact zeros while L2 does not, and when would you choose each?
L2 adds \(\frac{\lambda}{2}\|w\|_2^2\). Its gradient \(\lambda w\) shrinks each weight in proportion to its size, so weights get small but never reach zero. L1 adds \(\lambda\|w\|_1\). Its subgradient \(\lambda\,\mathrm{sign}(w)\) is a constant pull, so any weight whose loss gradient is smaller than \(\lambda\) in magnitude is held exactly at zero.
With an orthonormal design (\(X^\top X = I\), loss \(\frac12\|y-Xw\|^2\)) both have closed forms:
\[ \hat w_j^{\text{ridge}} = \frac{w_j^{\text{OLS}}}{1+\lambda}, \qquad \hat w_j^{\text{lasso}} = \mathrm{sign}(w_j^{\text{OLS}})\,\max\big(|w_j^{\text{OLS}}|-\lambda,\,0\big) \]
Ridge rescales; lasso soft-thresholds. Probabilistically, L2 is MAP with a Gaussian prior and L1 is MAP with a Laplace prior.
Choose L1 for feature selection and sparse serving models (FTRL-Proximal with L1 is the classic sparse CTR setup). It is unstable with correlated features, picking one of a group arbitrarily; elastic net fixes that.
Choose L2 when many features carry small effects or are correlated. It adds \(\lambda\) to every Hessian eigenvalue, so the problem becomes strongly convex and better conditioned.
Pitfalls. The penalty depends on feature scale, so standardise first. Do not penalise the bias. Plain SGD on L1 does not give exact zeros; use a proximal (soft-threshold) update. With Adam, an L2 term in the loss is not the same as weight decay (AdamW).
Follow-ups
- Along a direction where \(X^\top X\) has eigenvalue \(s^2\), by how much does ridge shrink the OLS solution?
- Why must features be standardised before regularising?
seniorconceptMLE RE Early stopping and dropout are both called regularisers. What is each one actually doing, and in what sense is dropout an approximate ensemble?
Early stopping limits how far the parameters travel from initialisation. For gradient descent from zero on a quadratic loss, the component of the solution along a Hessian eigen-direction with eigenvalue \(h\) is scaled by \(1-(1-\eta h)^t\) after \(t\) steps, while L2 scales it by \(h/(h+\lambda)\). The two agree approximately when \(\lambda \approx 1/(\eta t)\): low-curvature directions, the ones the data determines poorly, are learned last. In practice, monitor a validation metric with patience and restore the best checkpoint. The set used for stopping is no longer an unbiased estimate, so keep a separate test set.
Dropout samples a mask per step and trains a random sub-network; all \(2^n\) sub-networks share weights. Inverted dropout multiplies kept activations by \(1/(1-p)\) during training so that inference uses the full network unchanged. That single forward pass approximates averaging the sub-networks’ predictions: it is the exact normalised geometric mean for a single softmax layer and an approximation for deep non-linear networks. For linear regression, dropout on the inputs equals, in expectation, an L2 penalty weighted by each feature’s second moment.
Failure modes. Forgetting model.eval(). Dropout placed before BatchNorm shifts activation variance between training and inference. In large-data pretraining the model under-fits, so dropout is often set to zero. Keeping dropout on at inference (MC dropout) gives a cheap, rough uncertainty estimate.
Follow-ups
- Why is the early-stopped validation score optimistic?
- Why do networks trained on noisy labels benefit from early stopping in particular?
staffconceptMLE REasked at Anthropic What is double descent, and does it contradict the bias-variance trade-off? Be precise about what is established and what is not.
Test error as a function of capacity can fall, rise to a peak near the interpolation threshold (where the model can just fit the training set exactly), and fall again as capacity grows further. The same shape has been reported against training time (epoch-wise) and, near the threshold, against sample size.
It does not contradict the decomposition, which is an identity. It contradicts the assumption that variance grows monotonically with parameter count. Near the threshold there is essentially one interpolating solution and it must fit the noise, so variance spikes. Far beyond it there are many interpolating solutions and the optimiser’s implicit bias picks a low-norm one.
Linear regression makes this concrete. The minimum-norm least-squares solution is \(\hat w = X^{+}y\), and its variance contains \(\sum_i 1/s_i^2\) over the singular values of \(X\). When the number of features is close to \(n\) the smallest singular value approaches zero and the variance blows up.
Established: the phenomenon in deep networks (Belkin et al., 2019; Nakkiran et al., 2019), proofs for linear and random-feature models, a larger peak with more label noise, and that well-tuned regularisation (ridge, weight decay, early stopping) largely removes the peak.
Not established: that bigger is always better, or that parameter count is the right complexity measure. Practical reading: if validation error rises with model size, check regularisation and label noise before concluding the model is too big.
Follow-ups
- Why does the minimum-norm solution generalise better than an arbitrary interpolating one?
- Near the threshold, how can adding training data make test error worse?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Machine Learning Engineer, Apr 2026: Design an experiment to study sample-wise double descent (PracHub)
seniordebuggingMLE AI REasked at OpenAI A model scores 0.93 AUC in 5-fold cross-validation and 0.71 in its first week in production. Walk through how you would find the cause.
A gap this large is usually leakage or a split that does not match deployment, not drift. I check in this order:
- Split unit. Random K-fold assumes independent rows. If the same user, patient, device or near-duplicate appears in train and validation, the model memorises the entity. Use group K-fold on the entity that will be new at serving time.
- Time. A random split trains on the future. Use a forward split with a gap at least as long as the label delay and the longest feature window.
- Feature leakage. Features computed after the label event, or from the label: a target encoding fit on all rows, an aggregate whose window includes the event, a status field updated after the outcome. Rank single-feature AUCs; an implausibly strong feature is the suspect. Compare feature timestamps with prediction time.
- Preprocessing fit on all data. Scalers, imputers, feature selection, PCA or oversampling applied before the split. Fit them inside each training fold.
- Selection on the reported folds. Hyperparameters, early stopping and thresholds tuned on the same folds that produced 0.93. Use nested CV or an untouched test set.
- Training-serving skew. The feature is computed differently online (defaults, freshness, units). Join logged serving features to offline features for the same ids and compare.
- Only then real shift: population, label definition, seasonality.
To confirm, rebuild the split to mimic deployment (time plus group). The offline score should drop towards 0.71; if it does not, the problem is on the serving side.
Follow-ups
- When is plain K-fold fine?
- How do you choose the gap in a temporal split?
- Feature selection never looks at validation predictions. Why is doing it before the split still leakage?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI, Software Engineer, Jul 2025: Debug a churn classifier that generalises poorly (PracHub)
seniorderivationMLE RE You train a CTR model on logs where negatives were downsampled to 10%. Derive the correction that restores calibrated probabilities, and say when you would prefer reweighting, or no resampling at all.
Keep every positive and each negative with probability \(s\). Sampling depends only on the label, so the class-conditional feature densities are unchanged and the odds in the sample are inflated by \(1/s\):
\[ \frac{p_s}{1-p_s}=\frac{1}{s}\cdot\frac{p}{1-p} \;\Rightarrow\; \operatorname{logit}(p)=\operatorname{logit}(p_s)+\log s, \qquad p=\frac{s\,p_s}{1-p_s+s\,p_s}=\frac{p_s}{p_s+(1-p_s)/s} \]
With \(s=0.1\) and \(p_s=0.2\), \(p\approx 0.0244\); multiplying by \(s\) (0.02) is only the small-probability approximation. In serving, add \(\log s\) to the logit.
Alternatives. Weight each kept negative by \(1/s\) in the loss: the weighted loss is unbiased for the full-data loss, so outputs are calibrated directly, at the price of higher gradient variance. Class weights \(w_1, w_0\) in BCE move the optimum to \(w_1 q/(w_1 q + w_0(1-q))\), a logit offset of \(\log(w_1/w_0)\) that you undo the same way.
When. Negative downsampling is a compute decision; it loses little when negatives vastly outnumber positives. Imbalance itself does not break a probabilistic model trained with log loss; what matters is the absolute number of positives. So the default is the natural distribution (or downsample and correct), a threshold chosen from costs, and evaluation on unsampled data. Oversampling duplicates rows and invites overfitting, and focal loss or class weights break calibration unless corrected.
Do not correct twice (weights and offset together), and use per-example rates if sampling depended on features.
Follow-ups
- Hard-negative mining gives each example its own sampling rate. How do you correct then?
- Which of ROC-AUC, PR-AUC and log loss change when you evaluate on the downsampled set?
corederivationMLE AI REasked at Apple Derive the logistic regression loss from maximum likelihood, then its gradient and Hessian. What do they tell you about optimisation?
Model \(y_i\in\{0,1\}\) as Bernoulli with \(p_i=\sigma(z_i)\), \(z_i=w^\top x_i+b\). The likelihood is \(\prod_i p_i^{y_i}(1-p_i)^{1-y_i}\), so the negative log-likelihood is
\[ L(w)=-\sum_i\big[y_i\log p_i+(1-y_i)\log(1-p_i)\big]=\sum_i\big[\log(1+e^{z_i})-y_i z_i\big]. \]
Differentiating the second form, \(\partial L/\partial z_i=\sigma(z_i)-y_i=p_i-y_i\), hence
\[ \nabla_w L=X^\top(p-y),\qquad \nabla_w^2 L=X^\top S X,\quad S=\operatorname{diag}\big(p_i(1-p_i)\big). \]
What follows:
- \(S\succeq 0\), so the loss is convex and any local minimum is global. There is no closed form; use gradient methods, L-BFGS or Newton (IRLS).
- The gradient is residual times input, the same form as least squares and softmax regression. That is the canonical-link property of GLMs.
- On linearly separable data there is no finite maximiser: \(\|w\|\to\infty\). Regularise.
- MSE on a sigmoid output is non-convex in \(w\) and carries a factor \(p(1-p)\) that vanishes exactly when the model is confidently wrong. Log loss cancels that factor.
- Minimising cross-entropy is MLE and equals minimising \(\mathrm{KL}(\text{data}\,\|\,\text{model})\) up to a constant. It is a proper scoring rule, so a well-specified model is calibrated at the optimum.
- With labels in \(\{-1,+1\}\) the same loss is \(\log(1+e^{-y z})\).
- Numerics: compute from logits (
np.logaddexp(0, z) - y*z,BCEWithLogitsLoss), neverlog(sigmoid(z)).
Follow-ups
- What happens to the weights on perfectly separable data, and what does L2 change?
- Write the multiclass version and its gradient.
Reported in interviews (candidate reports on third-party sites, not verified)
- Apple, Data Scientist, Jul 2025: Write the logistic regression loss (PracHub)
coretrade-offMLE AI RE When do ROC-AUC, PR-AUC and log loss disagree, and which would you report for a classifier with 0.1% positives?
They measure different things.
- ROC-AUC is \(P(\text{score of a random positive} > \text{score of a random negative})\). It depends only on the ranking, and is invariant to the class prior and to any monotone transform of the scores. With rare positives the false-positive rate has a huge denominator: at 0.1% prevalence a 1% FPR already means about ten false positives per positive, so ROC can look excellent while precision is poor.
- PR-AUC (average precision) uses precision \(TP/(TP+FP)\), which depends on prevalence. A random classifier scores the prevalence, not 0.5, so values are not comparable across datasets. It concentrates on the top of the ranking.
- Log loss is a proper scoring rule: it rewards calibration and sharpness, and is hurt by a few confident errors and by prior shift. A monotone rescaling changes log loss but not AUC. Compare it with the entropy of the base rate, \(-\pi\log\pi-(1-\pi)\log(1-\pi)\).
Typical disagreements: better AUC with worse log loss means miscalibration, which is fixable post hoc; better log loss with the same AUC means only calibration improved.
At 0.1% positives I report the operating-point metric the product uses (precision at a fixed recall, recall at \(k\) reviews per day, recall at a fixed FPR), PR-AUC as a summary, and calibration if the scores are consumed as probabilities. All with intervals: with 100 positives in the test set, the standard error of recall can be 5 points.
Follow-ups
- Why does negative downsampling leave ROC-AUC unchanged in expectation but change PR-AUC?
- Two models have the same AUC. How can one still be much better in production?
coreconceptMLE AI RE Define NDCG@k. Why is it preferred to precision@k for graded relevance, and what are its pitfalls?
\[ \mathrm{DCG@}k=\sum_{i=1}^{k}\frac{2^{rel_i}-1}{\log_2(i+1)}, \qquad \mathrm{NDCG@}k=\frac{\mathrm{DCG@}k}{\mathrm{IDCG@}k} \]
IDCG is the DCG of the ideal ordering for that query, so NDCG lies in \([0,1]\) and is averaged over queries. Example: grades \([2,3,0]\) give \(\mathrm{DCG}=3+7/\log_2 3=7.42\); the ideal order \([3,2,0]\) gives \(8.89\); NDCG is \(0.83\).
It uses graded labels and discounts by position. Precision@k is binary and ignores order inside the top \(k\); MRR looks only at the first relevant result; MAP is binary.
Pitfalls:
- There are two gain conventions, \(2^{rel}-1\) and \(rel\). Say which one.
- A query with no relevant document has \(\mathrm{IDCG}=0\); scoring it 0 versus skipping it changes the mean.
- Per-query normalisation weights every query equally, whatever its traffic.
- Unjudged documents are usually counted as irrelevant, which penalises a new system that surfaces documents the old one never showed.
- The log discount is a convention, not a measured examination curve; click-derived labels also carry position bias.
- It is piecewise constant in the scores, so training uses surrogates: pairwise logistic loss, LambdaRank / LambdaMART (pair gradients weighted by the \(|\Delta\mathrm{NDCG}|\) of swapping the pair), or listwise softmax.
Follow-ups
- How does LambdaMART optimise NDCG if NDCG has zero gradient almost everywhere?
- What does the unjudged-equals-irrelevant rule do when you compare a new retriever with the incumbent?
corecodingMLE AI REasked at Meta Implement k-means in NumPy with k-means++ initialisation. State the objective, why the algorithm converges, and where it fails.
import numpy as np
def kmeanspp(X, k, rng):
C = [X[rng.integers(len(X))]]
d2 = ((X - C[0]) ** 2).sum(1) # squared distance to the nearest centre so far
for _ in range(k - 1):
C.append(X[rng.choice(len(X), p=d2 / d2.sum())]) # sample proportional to D^2
d2 = np.minimum(d2, ((X - C[-1]) ** 2).sum(1))
return np.array(C)
def kmeans(X, k, iters=100, tol=1e-8, seed=0):
rng = np.random.default_rng(seed)
C = kmeanspp(X, k, rng)
for _ in range(iters):
d2 = (X**2).sum(1)[:, None] - 2 * X @ C.T + (C**2).sum(1) # (n, k), no (n, k, d) tensor
a = d2.argmin(1) # assignment step
newC = C.copy()
for j in range(k):
if (a == j).any(): # empty cluster: keep the old centre
newC[j] = X[a == j].mean(0) # update step
shift = np.abs(newC - C).max()
C = newC
if shift < tol:
break
return C, aObjective: \(J=\sum_i\|x_i-c_{a_i}\|^2\). The assignment step minimises \(J\) over assignments with centres fixed; the update step minimises it over centres with assignments fixed (the mean minimises squared distance). \(J\) never increases and there are finitely many partitions, so it converges, but only to a local optimum. Each iteration costs \(O(nkd)\).
Pitfalls:
- Initialisation matters. Random initialisation can put two centres in one true cluster; k-means++ gives an \(O(\log k)\) approximation in expectation, and you still run several restarts and keep the lowest \(J\).
- Empty clusters must be handled.
- Features must be scaled, because Euclidean distance is scale dependent.
- It assumes roughly spherical clusters of similar size. It is the hard-assignment limit of EM for a Gaussian mixture with shared spherical covariance.
- \(k\) is chosen from outside the algorithm (elbow, silhouette, or the downstream task); \(J\) always falls as \(k\) grows.
Follow-ups
- Why does the mean minimise the within-cluster sum of squares, and what would you use for L1 distance?
- How would you make this work for 100 million points?
Reported in interviews (candidate reports on third-party sites, not verified)
- Meta, Machine Learning Engineer, Sep 2026: k-means clustering from scratch (PracHub)
seniorcodingMLE AI REasked at TikTok Implement ROC-AUC from scratch in O(n log n), handling tied scores correctly. Explain why the formula works.
import numpy as np
def roc_auc(y, s):
y, s = np.asarray(y), np.asarray(s)
_, inv, cnt = np.unique(s, return_inverse=True, return_counts=True)
last = np.cumsum(cnt) # 1-based rank of the last item in each tie group
ranks = (last - (cnt - 1) / 2)[inv] # average rank within ties
n_pos = y.sum()
n_neg = len(y) - n_pos
return (ranks[y == 1].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)Why it works. AUC is the fraction of (positive, negative) pairs ranked correctly, with ties counting one half; this is the Mann-Whitney U statistic divided by \(n_+ n_-\). A positive with ascending rank \(r\) has \(r-1\) items below it. Summing over positives counts positive-negative pairs plus the \(n_+(n_+-1)/2\) positive-positive pairs; subtracting those leaves \(U=\sum_{i\in +} r_i - n_+(n_++1)/2\). Average ranks give tied pairs the half credit.
What an interviewer checks:
- Ties. Sorting and ranking without tie handling makes the result depend on sort order. A constant score must give exactly 0.5.
- Complexity: the sort dominates, \(O(n\log n)\). The brute-force pair count is \(O(n_+ n_-)\) and is a good test oracle.
- Edge case: with only one class present, AUC is undefined. Raise or return NaN, not 0.
- Equivalent route: sweep thresholds over sorted scores, accumulate TPR and FPR, integrate with the trapezoid rule, grouping tied scores into one step.
- Per-group AUC (per query or per user) is a different metric from global AUC and is often the one a ranking product needs.
Follow-ups
- How would you compute a confidence interval for this AUC?
- Modify it to compute average precision. What changes about tie handling?
Reported in interviews (candidate reports on third-party sites, not verified)
- TikTok, Software Engineer, Jan 2026: Implement ROC-AUC, softmax and logistic regression (PracHub)
Statistics and probability 13% of postings
- Define a p-value and a confidence interval exactly and list the usual misreadings
- Derive the per-arm sample size for a two-sample test and use the 16 sigma^2 / delta^2 rule
- Explain family-wise error versus false discovery rate, and why peeking inflates false positives
- Implement a percentile bootstrap, resampling the independent unit, paired for model comparisons
- Solve Bayes-rule problems in odds form and expectation problems with indicators and first-step analysis
- Implement reservoir sampling and prove it is uniform
coreconceptMLE AI RE An A/B test reports p = 0.03 and a 95% confidence interval of [0.1%, 1.9%] for the lift. State precisely what each number means, and name the most common misreadings.
p-value: the probability, under the null hypothesis and the test’s model assumptions, of a statistic at least as extreme as the one observed. It is \(P(\text{data this extreme}\mid H_0)\), not \(P(H_0\mid\text{data})\).
95% confidence interval: the output of a procedure that covers the true parameter in 95% of repeated experiments. This particular interval either contains it or does not. “95% probability the lift is in the interval” is a Bayesian credible-interval statement and needs a prior. The two are linked: a 95% interval that excludes zero corresponds to a two-sided \(p<0.05\) from the same test.
Misreadings:
- Reading \(p\) as the chance the null is true. That depends on the prior and the power: if 10% of tested ideas are real, with 80% power and \(\alpha=0.05\), the share of significant results that are false is \(0.045/(0.045+0.08)=36\%\).
- Not significant is not the same as no effect. Look at the interval width.
- Statistical versus practical significance. With millions of users, negligible effects reach significance.
- Significant estimates from under-powered tests overstate the effect (winner’s curse).
- The guarantee assumes a fixed sample size and one pre-chosen metric. Peeking and many metrics break it.
- The analysis unit must match the randomisation unit. Randomising users but analysing page views understates the variance; use the delta method or a cluster bootstrap.
Report the effect size with its interval, not only the p-value.
Follow-ups
- Define type I and type II errors and relate them to alpha and power.
- Why does treating page views as independent give p-values that are too small?
seniorderivationMLE AI RE Derive the sample size per arm needed to detect an absolute lift delta in a conversion rate with a two-sided test at level alpha and power 1 - beta. What does the formula imply for detecting small effects?
With \(n\) users per arm and per-user variance \(\sigma^2\) (\(=p(1-p)\) for a rate), the difference in means has standard error \(\mathrm{SE}=\sqrt{2\sigma^2/n}\). We reject when \(|\hat\Delta|>z_{1-\alpha/2}\,\mathrm{SE}\). Under the alternative, \(\hat\Delta\sim N(\delta,\mathrm{SE}^2)\), and power \(1-\beta\) requires \(\delta-z_{1-\alpha/2}\,\mathrm{SE}\ge z_{1-\beta}\,\mathrm{SE}\) (the other tail is negligible). Solving for \(n\):
\[ n=\frac{2\sigma^2\,(z_{1-\alpha/2}+z_{1-\beta})^2}{\delta^2}\;\approx\;\frac{16\,\sigma^2}{\delta^2} \quad\text{for }\alpha=0.05,\ \text{power }0.8, \]
since \(2(1.96+0.84)^2\approx 15.7\).
Example. Baseline 5%, target a 2% relative lift, so \(\delta=0.001\) and \(\sigma^2=0.0475\): about 746,000 users per arm.
Implications:
- \(n\propto 1/\delta^2\): halving the minimum detectable effect costs four times the traffic.
- \(n\propto\sigma^2\): variance reduction is worth as much as traffic. CUPED regresses out a pre-experiment covariate and multiplies variance by \(1-\rho^2\); stratification, capping heavy tails and triggered analysis also help.
- Variance is proportional to \(1/n_A+1/n_B\), so a 50/50 split is the most efficient.
- \(\sigma^2\) must be measured at the randomisation unit. With clusters of size \(m\) and intra-class correlation \(\rho\), variance inflates by about \(1+(m-1)\rho\).
- Power is a design-time quantity. Post-hoc “observed power” adds nothing beyond the p-value.
Follow-ups
- How does CUPED work, and what makes a good covariate?
- What changes for a one-sided test, or for a ratio metric such as revenue per session?
seniortrade-offMLE AI RE Your experiment tracks 20 metrics, and the team checks the dashboard every day and wants to stop as soon as something is significant. What goes wrong statistically, and what do you do about it?
Two separate inflations of the false-positive rate.
Many metrics. With 20 independent true-null metrics at \(\alpha=0.05\), the chance that at least one is significant is \(1-0.95^{20}\approx 64\%\). Controls:
- Family-wise error: Bonferroni (\(\alpha/m\), valid under any dependence, conservative) or Holm (step-down, never less powerful than Bonferroni, also valid under any dependence).
- False discovery rate: Benjamini-Hochberg. Sort the p-values, find the largest \(k\) with \(p_{(k)}\le\frac{k}{m}q\), and reject the \(k\) smallest. It controls the expected share of false discoveries at \(q\) under independence or positive dependence.
- In practice: one pre-registered primary metric for the decision, a few guardrails, and FDR control for the exploratory rest.
Peeking. Under the null the p-value wanders, so testing repeatedly and stopping at the first \(p<0.05\) gives a false-positive rate far above 5%, and it tends to 1 as the number of looks grows. Fixes:
- A fixed horizon with a single analysis.
- Group-sequential designs with alpha spending. O’Brien-Fleming boundaries are very strict early and close to nominal at the end.
- Always-valid inference (mixture SPRT, confidence sequences): continuous monitoring is allowed, at the cost of wider intervals.
A third version of the same problem is post-hoc slicing: “it worked for Android users in one country” is a hypothesis for the next experiment, not a result.
The trade-off in every case is power: each correction widens intervals, so limit the number of confirmatory questions.
Follow-ups
- When is Bonferroni far too conservative, and what do you use instead?
- Does a Bayesian analysis make optional stopping harmless?
seniorcodingMLE AI RE Implement a bootstrap confidence interval for an arbitrary metric. Then say how you would use it to compare two models on the same test set, and when the bootstrap fails.
import numpy as np
def bootstrap_ci(x, stat=np.mean, B=10_000, alpha=0.05, seed=0):
"""Percentile bootstrap. x holds one entry per independent unit."""
rng = np.random.default_rng(seed)
x = np.asarray(x)
n = len(x)
reps = np.array([stat(x[rng.integers(0, n, n)]) for _ in range(B)])
lo, hi = np.quantile(reps, [alpha / 2, 1 - alpha / 2])
return stat(x), (lo, hi)
# Paired comparison of models A and B on the same examples:
# est, (lo, hi) = bootstrap_ci(correct_a - correct_b)The bootstrap treats the empirical distribution as the population: resample \(n\) units with replacement, recompute the statistic, and read the interval from the quantiles of the replicates.
What an interviewer checks:
- Resample the independent unit. Users, queries or documents, not rows. Row-level resampling of correlated rows gives intervals that are too narrow.
- Pair the comparison. Resample example indices once and compute both models on the same resample, or bootstrap the per-example difference as above. Unpaired intervals ignore the strong correlation between the two models’ errors and are far too wide.
- For metrics that are not a mean of per-example values (AUC, F1, NDCG), resample indices and recompute the whole metric on each replicate.
- \(B\): about 1,000 is enough for a standard error; use 10,000 for 95% limits.
- Failures: small \(n\); extreme statistics such as the maximum; heavy tails where a few values dominate; dependence in time (use a block bootstrap). The percentile interval is biased for skewed statistics; BCa corrects that.
- It quantifies sampling noise in the test set only. It does not cover training-seed variance or distribution shift.
Follow-ups
- Model B beats A by 0.4 points on 2,000 examples. Is that real, and how would you decide?
- Why does each bootstrap sample contain only about 63% of the distinct original points, and does that matter?
coreconceptMLE AI RE A fraud detector flags 95% of fraudulent transactions and 5% of legitimate ones. 1% of transactions are fraud. A transaction is flagged: what is the probability it is fraud? What if a second, independent detector with the same rates also flags it?
About 16%.
\[ P(F\mid +)=\frac{0.95\times 0.01}{0.95\times 0.01+0.05\times 0.99}=\frac{0.0095}{0.059}\approx 0.161 \]
The table version is the fastest check: of 10,000 transactions, 100 are fraud and 95 are flagged; 9,900 are legitimate and 495 are flagged; \(95/590=16\%\).
Odds form scales to further evidence: posterior odds = prior odds × likelihood ratio. Prior odds are \(1:99\) and the likelihood ratio is \(0.95/0.05=19\), giving \(19:99\). A second flag that is conditionally independent given the class multiplies by 19 again: \(361:99\), or 78.5%. In log-odds, evidence adds, which is exactly the structure of naive Bayes and of logistic regression.
What the question tests:
- Base-rate neglect. Precision depends on prevalence: the same detector at 0.1% prevalence gives 1.9%.
- The independence that matters is conditional on the class. Two detectors built on the same features are correlated, and multiplying their likelihood ratios double-counts evidence.
- Translation into ML terms: 95% is recall, 5% is the false-positive rate, and the answer is precision.
Follow-ups
- What prevalence would make the precision of a single flag 50%?
- How would you estimate the likelihood ratio of a detector from data?
coreconceptMLE AI RE Probability rounds lean on a few expectation tricks. Show them on: (a) the expected number of fixed points of a random permutation of n items, (b) the expected number of draws to collect all n coupons, (c) the expected number of fair-coin flips until two heads in a row.
(a) Linearity with indicators. Let \(I_i=1\) if item \(i\) stays in place; \(\mathbb{E}[I_i]=1/n\). Then \(\mathbb{E}[\sum_i I_i]=n\cdot\frac1n=1\) for every \(n\). Linearity needs no independence, and the indicators here are dependent.
(b) Split into geometric stages. With \(k\) distinct coupons in hand, the wait for a new one is geometric with success probability \((n-k)/n\) and mean \(n/(n-k)\). Summing over stages gives \(n\sum_{j=1}^{n}\frac1j=nH_n\approx n(\ln n+0.577)\). For \(n=10\) that is 29.3 draws.
(c) First-step analysis. Let \(E\) be the expected flips from the start and \(E_H\) the expected flips after one head:
\[ E=1+\tfrac12E_H+\tfrac12E,\qquad E_H=1+\tfrac12\cdot 0+\tfrac12E \]
Substituting gives \(E=6\).
The rest of the toolkit:
- Tower rule \(\mathbb{E}[X]=\mathbb{E}[\mathbb{E}[X\mid Y]]\) and total variance \(\operatorname{Var}(X)=\mathbb{E}[\operatorname{Var}(X\mid Y)]+\operatorname{Var}(\mathbb{E}[X\mid Y])\).
- Tail sum: \(\mathbb{E}[X]=\sum_{k\ge1}P(X\ge k)\) for non-negative integer \(X\).
- Symmetry: the \(k\)-th element of a random order is a running maximum with probability \(1/k\), so the expected number of records is \(H_n\); the expected maximum of \(n\) uniforms on \([0,1]\) is \(n/(n+1)\).
- Jensen: \(\mathbb{E}[f(X)]\ge f(\mathbb{E}[X])\) for convex \(f\), so \(\mathbb{E}[1/X]\ne 1/\mathbb{E}[X]\) and the mean of ratios is not the ratio of means.
Sanity-check small cases (\(n=1,2\)) before stating a result.
Follow-ups
- What is the variance of the number of fixed points?
- Expected flips until the pattern HT instead of HH. Why is it different?
corecodingMLE AI RE Sample k items uniformly at random from a stream of unknown length in one pass and O(k) memory. Implement it and prove that it is uniform.
import random
def reservoir_sample(stream, k, rng=random):
res = []
for i, x in enumerate(stream): # i is 0-based; i + 1 items seen so far
if i < k:
res.append(x)
else:
j = rng.randint(0, i) # inclusive on both ends: uniform over i + 1 values
if j < k:
res[j] = x # happens with probability k / (i + 1)
return resProof by induction. Claim: after \(m\ge k\) items, each is in the reservoir with probability \(k/m\). It holds at \(m=k\). When item \(m+1\) arrives it enters with probability \(k/(m+1)\). An item already in the reservoir survives unless the newcomer enters and picks its slot: \(1-\frac{k}{m+1}\cdot\frac1k=\frac{m}{m+1}\). So its probability becomes \(\frac{k}{m}\cdot\frac{m}{m+1}=\frac{k}{m+1}\).
Time is \(O(n)\), memory \(O(k)\).
What an interviewer checks:
- Off-by-one in the random index.
randint(0, i)is inclusive; with NumPy userng.integers(0, i + 1). - The newcomer replaces a uniformly chosen slot. Always replacing the oldest item is not uniform.
- Weighted version (Efraimidis-Spirakis): give each item the key \(u^{1/w}\) with \(u\sim U(0,1)\) and keep the \(k\) largest keys in a heap.
- Distributed version: reservoirs from shards cannot simply be concatenated; merge by sampling from each in proportion to its shard’s count, or use the random-key method (keep the \(k\) smallest uniform keys), which merges trivially.
- Typical uses: an unbiased sample of logs for labelling or evaluation, and bounded replay buffers.
Follow-ups
- Each inclusion probability is k/m. Does that alone prove every k-subset is equally likely?
- How would you sample uniformly per user instead of per event?
Data labeling, curation and quality 13% of postings
- Compute Cohen’s kappa and explain why raw agreement misleads under class imbalance
- Explain how random and systematic label noise affect training and evaluation differently
- Design an active-learning loop and name its sampling-bias pitfalls
- Describe weak supervision with labelling functions and how to validate it
- Build a test set with known sampling weights when positives are rare
seniorconceptMLE AI REasked at Apple Two annotators agree on 85% of items. Is that good? Explain how you measure label quality and what label noise does to training and to evaluation.
It cannot be judged without chance agreement. Cohen’s kappa corrects for it:
\[ \kappa=\frac{p_o-p_e}{1-p_e},\qquad p_e=\sum_c p_{1,c}\,p_{2,c} \]
where \(p_{a,c}\) is the share of items annotator \(a\) assigns to class \(c\). With balanced binary labels \(p_e=0.5\) and \(\kappa=0.70\). If both annotators mark 90% negative, \(p_e=0.82\) and \(\kappa\approx0.17\): barely above chance. For more than two annotators use Fleiss’ kappa; for missing ratings or ordinal scales, Krippendorff’s alpha. Kappa moves with prevalence, so report per-class agreement and the annotator confusion matrix as well.
What low agreement means. Unclear guidelines (the cheapest thing to fix: tighten the guideline and add examples), genuinely ambiguous items (keep the label distribution instead of forcing a majority), or weak annotators (gold questions, per-annotator accuracy; Dawid-Skene estimates each annotator’s confusion matrix and the true labels jointly with EM).
Training. Random, class-independent noise mostly costs sample efficiency and calibration. Large models tolerate a fair amount but eventually memorise it, so early stopping helps. Systematic noise that depends on class or features is learned as signal. Mitigations: relabel the most suspicious items (confident learning flags examples whose out-of-fold probability for the given label is low), noise-robust losses or label smoothing, and extra annotations where disagreement is high.
Evaluation. Noise here is worse. It caps the measurable score, compresses the differences between models and can reorder them. Spend labelling budget first on a clean, multiply-annotated, adjudicated test set. Human-human agreement is the reference ceiling for the metric.
When an LLM is the annotator, measure it against human gold with the same statistics and look for systematic bias it shares with the model under evaluation.
Follow-ups
- With a fixed budget, do you label 3N items once or N items three times?
- {‘Majority vote versus Dawid-Skene’: ‘when does the difference matter?’}
- Annotators agree with each other but are consistently wrong. How would you find out?
Reported in interviews (candidate reports on third-party sites, not verified)
- Apple, Machine Learning Engineer, Aug 2025: Annotation agreement, and LLM versus human judges (PracHub)
staffdesignMLE AI RE You have 5 million unlabelled items, budget to label 20,000, and a positive rate of about 1%. Design the labelling and curation plan.
1. Definition and test set first. Write the guideline, pilot a few hundred items with two or three annotators, measure kappa and revise until agreement is acceptable. Then build the test set before anything else. A uniform sample of 5,000 holds about 50 positives, too few for a usable recall estimate. So stratify: over-sample strata that are likely positive (by heuristic or model score), record each item’s inclusion probability, and weight by its inverse to recover unbiased population metrics. Label it multiple times, adjudicate, and freeze it.
2. Enrich for positives. Random sampling returns 1%. Use weak signals: rules and keywords, an existing model’s scores, user reports, nearest neighbours of known positives in embedding space, zero-shot LLM scoring. Label a mix of enriched and random items.
3. Weak supervision for breadth. Write labelling functions (rules, distant supervision, LLM prompts). A label model estimates their accuracies and correlations without ground truth and outputs probabilistic labels for the whole pool, which train the end model. It is cheap and inherits the systematic errors of the functions, so validate on the gold set.
4. Active-learning loop. Train, score the pool, select a batch, label, repeat, for example five rounds of 3,000. Select by uncertainty (margin or entropy) or committee disagreement, combined with diversity (spread across embedding clusters) so a batch is not near-duplicates. Keep 10 to 20% of each batch random.
Pitfalls:
- The labelled set is no longer i.i.d. It cannot serve as an evaluation set, and it biases the training distribution.
- Uncertainty sampling is drawn to ambiguous and noisy items, where annotators also disagree.
- Cold start: early models have meaningless uncertainty. Begin with diverse or enriched sampling.
- Gains over random sampling are often modest with strong pretrained encoders. Measure them using the random slice.
5. Quality control. Interleaved gold items, per-annotator accuracy, 10% double labelling, model-assisted relabelling of suspicious items, and a dataset version tied to the guideline version.
Follow-ups
- Why keep a random slice in every active-learning round?
- How do you get unbiased precision and recall from a stratified test set?
- When would you replace human labels with LLM labels, and how would you check them?
staffdesignMLE AI RE A new data source (a vendor-labelled set, or a large scrape) is proposed for the training corpus. How do you decide whether it should go in, before paying for a full training run?
Treat it as a change that needs evidence at three levels: the rows, the distribution, and the effect on the model.
1. Row-level audit.
- Read a random sample yourself before computing anything. A few hundred rows reveal most systematic problems: boilerplate, truncation, wrong language, templated or machine-generated text, labels that follow a shortcut.
- Estimate the error rate with an interval. Auditing about 385 random rows gives at most ±5 points at 95% confidence; stratify by source and label so that no slice hides.
- For vendor labels, seed gold items, double-label a subset and compute kappa against your own annotators.
2. Set-level checks.
- Duplicates. Exact (hash of normalised content) and near-duplicates (MinHash / LSH or embedding similarity), both inside the new set and against the existing corpus. Duplicates silently reweight the training distribution.
- Evaluation contamination. Overlap with every test and benchmark set, by the same exact and near-duplicate methods. Any overlap invalidates later comparisons.
- Coverage. Compare with the target distribution, not only with the old corpus: language, domain, length, class balance, time range. Ask what the source adds that was missing.
- Provenance. Licence, personal data, and how the source was selected, since selection bias becomes model bias.
3. Model-level evidence.
- Run a small-scale ablation with and without the source at equal training budget, with at least a few seeds, and read slice metrics rather than one average. A source can help its own domain and hurt elsewhere.
- Filter rather than accept or reject wholesale: heuristics, a quality classifier or a model-based score, with the threshold chosen on the ablation and not by intuition.
- Decide how to mix: sampling weight or cap per source, so a large low-quality source cannot dominate.
4. Make it reversible. Version the dataset, keep lineage from each row to its source and filter version, and record the audit numbers, so a regression found months later can be traced and the source removed.
Follow-ups
- The ablation shows no difference at small scale. Does that mean the data is useless at full scale?
- How would you detect near-duplicates across a billion documents?
- What would make you reject a source that improves the headline metric?
seniorcodingMLE REasked at OpenAI Each item has labels from three annotators of unknown and unequal quality. Implement majority vote, say how accurate it is, then beat it. How would you find the bad annotations, and how should the classifier be trained on the result?
Majority vote weights every annotator equally. With three independent annotators of accuracy \(p\) on a binary task it is right with probability \(p^3 + 3p^2(1-p)\): 0.896 for \(p = 0.8\). It helps when annotators are similar and hurts when one is much better: with accuracies 0.95, 0.65 and 0.60 the vote is right 83.7% of the time, worse than the best annotator alone.
Beat it by estimating who to trust (Dawid and Skene, 1979). Treat the true label as latent and give each annotator a confusion matrix. EM alternates between the posterior over true labels and the confusion matrices:
import numpy as np
def majority_vote(L, K):
"""L: (N, A) integer labels. Returns labels and (N, K) vote shares."""
counts = np.stack([(L == k).sum(1) for k in range(K)], axis=1)
return counts.argmax(1), counts / counts.sum(1, keepdims=True)
def dawid_skene(L, K, iters=50, eps=1e-6):
"""Returns posterior (N, K) and confusion (A, K, K) as conf[a, true, observed]."""
onehot = np.eye(K)[L] # (N, A, K)
post = majority_vote(L, K)[1] # initialise from vote shares
for _ in range(iters):
prior = post.mean(0) # M-step
conf = np.einsum("nk,nal->akl", post, onehot) + eps
conf /= conf.sum(2, keepdims=True)
logp = np.log(prior)[None] + np.einsum("nal,akl->nk", onehot, np.log(conf))
logp -= logp.max(1, keepdims=True) # E-step
post = np.exp(logp); post /= post.sum(1, keepdims=True)
return post, confOn 20,000 simulated items with those three accuracies, this reaches 95.0% against 83.5% for the vote, because it learns to follow the strong annotator. With only three annotators the estimates converge slowly and stay loose; five or more, or a small gold set to initialise the confusion matrices, makes them reliable. Missing labels need a mask in both steps.
The assumption that fails: errors are independent given the true label. Annotators share confusions on hard items, so agreement overstates confidence. Item difficulty can be modelled too (GLAD, or item-response models).
Finding bad annotations.
- Per annotator: the estimated confusion matrix, accuracy on hidden gold items, agreement with the consensus, time per item.
- Per label: train with cross-validation and flag items where the out-of-fold predicted probability of the given label is low (confident learning). Review the flags; hard and rare examples are flagged too, and deleting them biases the data.
Training on the result.
- Use the posterior as a soft target instead of its argmax, which keeps the uncertainty.
- Or train on every annotator’s label with an annotator-specific noise layer on top of a shared classifier, which uses the input to resolve disagreement.
- Spend relabelling budget where the posterior is uncertain, not uniformly.
- Keep a clean, adjudicated test set. Noisy test labels cap measured accuracy and can reorder models.
Follow-ups
- Two of the three annotators copy each other. What does that do to majority vote and to the EM estimate?
- You can buy 10,000 more labels. Do you label new items once or relabel existing ones?
- When is the disagreement itself the signal and not noise?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI, Machine Learning Engineer, Oct 2026: Majority-vote labels from three noisy annotators, then beat that baseline (PracHub)
- OpenAI, Machine Learning Engineer, Apr 2026: Improve training when labels come from noisy annotators (PracHub)
- OpenAI, Machine Learning Engineer, Feb 2026: Improve a classifier trained on noisy multi-annotator labels (PracHub)
- OpenAI, Machine Learning Engineer, Apr 2026: Filter bad human annotations (PracHub)
Classical models (GBDT, linear, trees) 12% of postings
- Derive the XGBoost leaf weight and split gain from the second-order expansion
- Implement a split search in O(n log n) per feature with prefix sums
- Implement logistic regression with mini-batch SGD and a numerically stable loss
- Explain why boosted trees win on tabular data and where they lose
- Compare random forests and boosting in bias-variance terms and name the main hyperparameters
corecodingMLE AI REasked at TikTok Implement binary logistic regression with mini-batch SGD and L2 regularisation in NumPy, including a numerically stable loss.
import numpy as np
def sigmoid(z):
return np.exp(-np.logaddexp(0, -z)) # stable for large |z|
def fit_logreg(X, y, lr=0.1, l2=1e-4, epochs=20, batch=64, seed=0):
rng = np.random.default_rng(seed)
n, d = X.shape
w, b = np.zeros(d), 0.0
for _ in range(epochs):
perm = rng.permutation(n) # reshuffle every epoch
for i in range(0, n, batch):
idx = perm[i:i + batch]
g = sigmoid(X[idx] @ w + b) - y[idx] # dL/dz = p - y
w -= lr * (X[idx].T @ g / len(idx) + l2 * w)
b -= lr * g.mean() # no penalty on the bias
return w, b
def log_loss(X, y, w, b):
z = X @ w + b
return np.mean(np.logaddexp(0, z) - y * z) # log(1 + e^z) - y zCost is \(O(\text{epochs}\cdot n\cdot d)\).
What an interviewer checks:
- The gradient is \(X^\top(p-y)/m\); you should be able to derive it, and verify it with finite differences.
- Stability:
1 / (1 + np.exp(-z))overflows for large negativez, andlog(p)gives-infwhenprounds to 0. Work with logits. - Shapes:
ymust be(n,). If it is(n, 1),p - ybroadcasts to(n, n)without an error. - Mean rather than sum over the batch, so the learning rate does not depend on batch size.
- Standardise features: SGD on badly scaled inputs is slow, and the L2 penalty is scale dependent.
- Zero initialisation is fine here because the problem is convex and has no hidden-unit symmetry to break.
- Stopping: a fixed epoch count is a placeholder; in practice monitor validation loss.
Follow-ups
- Extend it to multiclass softmax regression. What changes in the gradient?
- How would you add L1 so that weights become exactly zero?
Reported in interviews (candidate reports on third-party sites, not verified)
- TikTok, Software Engineer, Jan 2026: Implement ROC-AUC, softmax and logistic regression (PracHub)
seniorderivationMLE REasked at TikTok Derive how XGBoost sets a leaf weight and scores a candidate split. Why second order, and what do lambda, gamma and min_child_weight do?
Boosting adds one tree per round: \(\hat y^{(t)}=\hat y^{(t-1)}+f_t(x)\). Expand the loss to second order around the current prediction, with \(g_i=\partial_{\hat y}\ell(y_i,\hat y_i^{(t-1)})\) and \(h_i=\partial^2_{\hat y}\ell\):
\[ \text{obj}^{(t)}\approx\sum_i\Big[g_if_t(x_i)+\tfrac12h_if_t(x_i)^2\Big]+\gamma T+\tfrac12\lambda\sum_{j=1}^{T}w_j^2 \]
A tree sends each example to one of \(T\) leaves with weight \(w_j\). With \(G_j=\sum_{i\in j}g_i\) and \(H_j=\sum_{i\in j}h_i\) the objective separates by leaf, \(\sum_j\big[G_jw_j+\tfrac12(H_j+\lambda)w_j^2\big]+\gamma T\), so
\[ w_j^*=-\frac{G_j}{H_j+\lambda},\qquad \text{gain}=\frac12\left[\frac{G_L^2}{H_L+\lambda}+\frac{G_R^2}{H_R+\lambda}-\frac{(G_L+G_R)^2}{H_L+H_R+\lambda}\right]-\gamma . \]
Split search. For each feature, scan sorted values (exact) or at most a few hundred histogram bins (hist, LightGBM), accumulating \(G_L,H_L\), and keep the best gain. Missing values get a learned default direction by trying both sides.
Why second order. The leaf weight is a Newton step, so each leaf gets a correctly scaled step for any twice-differentiable loss. For squared loss \(h=1\) and it reduces to the mean residual. For log loss \(g=p-y\) and \(h=p(1-p)\).
Regularisers. \(\lambda\) shrinks leaf weights, most where \(H\) is small. \(\gamma\) is the minimum gain needed to keep a split. min_child_weight is a lower bound on a child’s \(H\); for log loss \(H\) is small where predictions are already confident, so it stops splitting nearly pure nodes. Shrinkage (the learning rate) and row or column subsampling act on top.
Variants: LightGBM grows leaf-wise and adds GOSS and feature bundling; CatBoost uses ordered boosting, ordered target statistics and symmetric trees.
Follow-ups
- What goes wrong with a custom loss whose second derivative can be zero or negative?
- How does a random-forest split criterion differ from this?
Reported in interviews (candidate reports on third-party sites, not verified)
- TikTok, Data Scientist, Oct 2025: Tune XGBoost and prevent overfitting (PracHub)
seniorcodingMLE RE Implement the best-split search for a regression decision stump in NumPy. It should run in O(n log n) per feature, not O(n^2).
import numpy as np
def best_split(X, y):
"""Return (gain, feature, threshold) maximising the reduction in squared error."""
n, d = X.shape
total = y.sum()
best = (0.0, None, None)
for j in range(d):
order = np.argsort(X[:, j], kind="mergesort")
xs, ys = X[order, j], y[order]
left = np.cumsum(ys)[:-1] # sum of y in the left child for a split after row i
nl = np.arange(1, n)
gain = left**2 / nl + (total - left)**2 / (n - nl) - total**2 / n
gain[xs[1:] == xs[:-1]] = -np.inf # cannot split between equal values
i = int(gain.argmax())
if gain[i] > best[0]:
best = (float(gain[i]), j, float((xs[i] + xs[i + 1]) / 2))
return bestWhy the formula. The squared error of a node around its mean is \(\sum y^2-S^2/n\) with \(S=\sum y\). The \(\sum y^2\) terms cancel between parent and children, so
\[ \text{gain}=\frac{S_L^2}{n_L}+\frac{S_R^2}{n_R}-\frac{S^2}{n}. \]
One sort and one prefix sum per feature evaluate every threshold in \(O(n)\) after an \(O(n\log n)\) sort. Recomputing child means per threshold is the \(O(n^2)\) version.
What an interviewer checks:
- Thresholds only between distinct values; midpoints as thresholds.
- A feature that is constant, or no positive gain, returns no split.
min_samples_leafis a mask onnlandn - nl.- Classification is the same scan with per-class prefix counts and Gini or entropy.
- The XGBoost gain is this formula with \(S\to G\), \(n\to H+\lambda\) and a factor \(\frac12\).
- Production libraries sort once (or pre-bin into histograms) and reuse that across nodes, and build the sibling histogram by subtraction.
Follow-ups
- Extend this to a full tree. What is the complexity for depth D?
- How would you handle a categorical feature with 1,000 levels?
seniortrade-offMLE AI RE Why do gradient-boosted trees still tend to beat neural networks on tabular data, and when would you pick a linear model or a neural network instead?
Tabular data has heterogeneous features, targets with sharp thresholds, many uninformative columns and usually \(10^4\) to \(10^6\) rows. The inductive bias of trees fits that; an MLP’s does not.
- Splits are axis-aligned and invariant to monotone transforms: no scaling, heavy tails are harmless, missing values are handled natively.
- Piecewise-constant functions capture thresholds and interactions directly, while MLPs are biased towards smooth functions.
- Greedy split selection ignores useless features. An MLP is rotation invariant and needs more data to find which axes matter (Grinsztajn et al., 2022, on medium-sized benchmarks).
- Good defaults, minutes on CPU, little tuning.
Boosting versus random forest. Boosting reduces bias with many shallow trees fit sequentially; it needs a learning rate and early stopping and is more sensitive to label noise. A forest averages deep decorrelated trees to cut variance; it parallelises, is hard to mis-tune and gives out-of-bag estimates.
Where trees lose. Extrapolation: predictions are constant outside the training range, which hurts with trends. Very high-cardinality ids, raw text, images and sequences. Online updates. Multi-task learning and shared representations.
Pick a linear model for very sparse high-dimensional features with huge data and online updates (hashed crosses with FTRL), when monotonic, auditable scores are required (credit), for microsecond latency, and always as the baseline.
Pick a neural network when the signal is in ids and sequences (large recommender systems), when inputs are multimodal, or when pretraining transfers. Hybrids are common: embeddings fed to a GBDT, or GBDT leaf indices fed to a linear model.
Tabular foundation models report wins on small datasets; treat that as benchmark specific and always run a tuned GBDT baseline.
Follow-ups
- A tree cannot extrapolate a linear trend. How do you work around that in a forecasting problem?
- What do monotonic constraints buy you, and what do they cost?
Anomaly, fraud and risk detection 8% of postings
- Explain how delayed chargebacks and blocking by the previous model bias labels, and how to correct each
- Derive the cost-based threshold c_FP / (c_FP + c_FN) and say why it needs calibrated scores
- Choose metrics for extreme imbalance (precision at k, recall at a fixed false-positive rate) with intervals
- Describe unsupervised detectors (isolation forest, reconstruction error) and how to evaluate them without labels
staffdesignMLE You own a payment-fraud model. Labels arrive as chargebacks up to 90 days later, and the current system blocks the transactions it scores as risky. What does that do to your training data and evaluation, and how do you design around it?
There are two different biases, and they need different fixes.
1. Delayed labels (censoring). A recent transaction with no chargeback is unlabelled, not negative. Training on recent weeks as they stand teaches the model to under-predict, and calibration drifts. Options:
- Train only on matured data. Measure the delay distribution and choose the window from it. The price is staleness against an adversary that adapts.
- Use recent data with a correction: weight observed positives by the inverse probability that a fraud of that age would already have been reported, or fit a delayed-feedback model of outcome and delay jointly.
- Use faster proxy labels (issuer fraud alerts, customer reports, manual review), treated as noisy.
Always evaluate on matured windows.
2. Selective labels. Blocked transactions never produce an outcome, so the labelled population is “approved by the previous model”. The new model is trained and scored only where the old one said yes, features the old model relied on look weaker than they are (range restriction), and blind spots stay invisible.
- Exploration. Approve a small random share of would-be blocks, with amount caps, and log the propensity. It is the only source of unbiased labels in the blocked region, and it has a cost that needs a budget and an owner.
- Inverse propensity weighting near the threshold. It needs overlap; a deterministic block has propensity zero and cannot be corrected.
- Other outcomes for declines: manual review, customer disputes of false declines, confirmed fraud on the same card elsewhere.
- Classical reject inference (extrapolating labels onto rejects) rests on assumptions you cannot test. Say so if you use it.
Also. Label noise (friendly fraud, unreported fraud), adversarial drift (time-based validation, frequent retraining, velocity and graph features), extreme imbalance, and amount-dependent costs.
Evaluation. A time split with a maturity gap. Report at the operating point, for example fraud value caught at a fixed false-decline rate, with intervals. Online, an A/B test that reads chargeback rate, approval rate and false-decline complaints after maturity.
Follow-ups
- How large should the exploration slice be, and who signs off on its cost?
- How do you compare a new model with the old one offline when the old one decided which rows have labels?
- How would you notice a new fraud pattern before any chargebacks arrive?
seniortrade-offMLE AI With 0.1% positives and a false negative costing 50 times a false positive, how do you set the decision threshold? What changes if you have no reliable labels at all?
With a calibrated probability \(p\), flag when the expected cost of not flagging exceeds the cost of flagging, \(p\,c_{FN}>(1-p)\,c_{FP}\):
\[ p>\frac{c_{FP}}{c_{FP}+c_{FN}}=\frac{1}{51}\approx 2\% \]
Not 0.5, and not a function of prevalence: prevalence enters through \(p\). So:
- Keep \(p\) calibrated: train on the natural distribution, or downsample and apply the logit correction.
- Check calibration where the decision is made, around 2%. A global ECE is dominated by the mass near zero.
- If cost varies per case (transaction amount), threshold the expected loss \(p\times\text{amount}\) against the review cost.
- If review capacity is fixed, take the top \(k\) by expected loss and measure precision and recall at \(k\).
- Pick the threshold on validation data and report on test with intervals. At 0.1%, a thousand positives needs a million rows.
Avoid tuning for F1 by default (it encodes an arbitrary cost ratio) and avoid rebalancing to 50/50 and then thresholding at 0.5. When costs are soft, show the precision-recall or cost curve and let the owner choose. Revisit the choice as prevalence drifts: precision at a fixed threshold moves with the base rate even when the model does not.
No labels. Use unsupervised detectors: isolation forest (anomalies are isolated by few random splits), distance or density methods (kNN, LOF), reconstruction error from PCA or an autoencoder, and robust or seasonal residuals for metric time series. They find “unusual”, not “bad”, so expect benign rarities. Evaluate by analyst review of the top \(k\) alerts, by injecting synthetic anomalies, and by replaying known incidents. Use the reviewed alerts as labels and move to a supervised or positive-unlabelled model as soon as there are enough.
Follow-ups
- How does the threshold change if the model was trained on negatives downsampled to 10% and not corrected?
- The scores are not calibrated and you cannot recalibrate. How do you still choose a threshold?
Data analysis (pandas, numpy, notebooks) 8% of postings
- Run a first-pass data audit (grain, keys, label, missingness over time, availability at prediction time)
- Avoid pandas pitfalls such as index alignment, NaN group keys, chained assignment and join fan-out
- Vectorise with NumPy broadcasting and know the shape bugs it can hide
- Know when to leave pandas for Polars, DuckDB or Spark
coredebuggingMLE AI RE You are handed a 50 GB events table and asked whether it is usable for training. What do you check in a notebook, and which pandas / NumPy pitfalls do you watch for while doing it?
Checks, in the order they usually find problems:
- Grain and keys. What is one row? Are there duplicates on the supposed key? Count rows before and after every join;
merge(..., validate="m:1")turns fan-out into an error. - Label. Base rate over time and by segment, how it is generated, how long it takes to arrive.
- Missingness. Null rate per column over time; a step change is a pipeline change. Look for sentinels (-1, 0, 9999, empty string) posing as data.
- Distributions. Quantiles rather than means, units, impossible values, cardinality, constant columns, gaps in time coverage.
- Availability. Is each column known at prediction time?
Plot everything against time first; most data bugs appear as discontinuities.
Pitfalls.
- Scale: do not load 50 GB into pandas. Read only the needed Parquet columns, aggregate in DuckDB, Polars or Spark, and bring a small frame into pandas. Sample by hashing a key (all rows of a user together), not with
head. apply(axis=1)anditerrowsare Python loops. Use column operations,np.where,groupby().aggortransform.- NaN:
NaN != NaN;groupbydrops NaN keys unlessdropna=False;meanskips NaN silently;countexcludes NaN whilesizedoes not; an integer id column with NaN becomes float64 and loses exactness above \(2^{53}\). - Index alignment: assigning a Series aligns on the index, not position, so after a filter or sort you get silent NaNs or misplaced values.
- Chained assignment (
df[mask]["col"] = v) does not reliably modifydf, and never does under copy-on-write; usedf.loc[mask, "col"] = v. - NumPy broadcasting:
(n,)minus(n, 1)gives(n, n)without an error. Assert shapes. Basic slices are views, and integer sums can overflow int32. - Reproducibility: seed with
np.random.default_rng(seed)and record the query and the snapshot date.
Follow-ups
- How do you sample 1% of the data so that each sampled user keeps all of their rows?
- When is
groupby().transformthe right tool instead ofaggplus a merge?
Feature engineering 7% of postings
- Explain target-encoding leakage and build an out-of-fold, smoothed, time-aware encoding
- Compare the hashing trick, learned embeddings and explicit crosses for high-cardinality ids
- Make a windowed aggregate feature point-in-time correct and test for training-serving skew
seniordebuggingMLE You add a target encoding of merchant id and validation AUC jumps, but the model does worse online. What happened, and how do you do target encoding safely?
The encoding of each training row included that row’s own label. For a rare category the encoding is almost the label itself (a merchant with one row is encoded as its \(y\)), so the model learns to trust the feature. At serving time the encoding comes from other rows and is far noisier. If the encoding was fit before the split, validation rows leaked in the same way, which is why validation looked good.
Doing it safely:
- Out-of-fold. Encode each training row from the other folds only; encode validation and test rows from training data only. Fit the encoder inside each CV fold.
- Smooth towards the prior. \(\hat\mu_c=\dfrac{n_c\,\bar y_c+m\,\bar y}{n_c+m}\), where \(m\) is a pseudo-count. Rare categories shrink to the global mean. This is the posterior mean of a Beta-Binomial model.
- Respect time. Use only labels that existed, and had matured, before the row’s timestamp. CatBoost’s ordered target statistics apply the same idea over random permutations. This is also what the online feature can actually see.
- Unseen categories get the prior. Add the count \(n_c\) as a feature so the model knows how much to trust the encoding.
How to recognise the leak: feature importance dominated by the encoded column; the encoded values are more extreme on training rows than on validation rows; performance collapses on low-count categories.
Label-free alternatives are count or frequency encoding, hashing with a linear model, and learned embeddings.
Follow-ups
- How would you choose the pseudo-count m?
- Out-of-fold training rows are encoded from (K-1)/K of the data, serving rows from all of it. Does that matter?
seniortrade-offMLE You have categorical features with tens of millions of values (user id, item id, query tokens) and want feature crosses. Compare the hashing trick, learned embeddings and explicit crosses, including what breaks.
Hashing trick. Index = hash(feature name, value) mod \(2^b\). Memory is fixed, there is no vocabulary to maintain, and new values work without a pipeline change. The cost is collisions: \(n\) values in \(m\) buckets give about \(n^2/(2m)\) colliding pairs, and collisions between frequent values hurt most. Mitigations are more bits, a separate hash space per feature, a signed hash (a second hash picks the sign, which makes inner products unbiased; Weinberger et al., 2009), and several hash functions into a shared table. Hashes are not invertible, so debugging is harder.
Learned embeddings. A \(V\times d\) table trained end to end shares strength between similar ids. Ten million ids at \(d=64\) in fp32 is 2.56 GB, so the table dominates model size. Rows for rare and new ids are barely trained: use a frequency threshold with an out-of-vocabulary bucket, hashed embeddings, or content features as a fallback. Gradients are sparse, so use sparse or per-coordinate optimisers.
Crosses. An explicit cross A×B memorises specific combinations (the wide part of Wide & Deep). Cardinality multiplies, so crosses are hashed and need L1 or a minimum count. Factorisation machines model the interaction as \(\langle v_i,v_j\rangle\) and generalise to pairs never seen together; deep models and GBDTs learn crosses implicitly. The choice is memorisation against generalisation, and production rankers usually combine both.
What breaks.
- An id memorises the label and nothing transfers to new users; validate with a split by group and time.
- Vocabulary drift between training and serving.
- Changing the hash seed or the modulus silently remaps every feature.
- A cross with a high-cardinality id explodes the feature space with almost no support per value.
Follow-ups
- How many bits would you give the hash space, and how would you measure the damage from collisions?
- When would you drop the id and rely on content features only?
seniordesignMLE A model uses “the user’s purchase count over the last 30 days”. Design the feature computation so that training and serving agree, and list the failure modes.
The rule: every training row must see the value that was available at its prediction time, not the value as of the day the dataset was built.
Options, most reliable first.
- Log and wait. Log the feature vector actually served with each request and train on those logs. Skew is zero by construction. The cost is that a new feature needs weeks of logging before it can be trained on.
- Point-in-time join. Join each label event (entity, \(t_{\text{pred}}\)) to the latest feature snapshot with timestamp at most \(t_{\text{pred}}\) minus the real availability lag. Never join on “latest”.
- One definition, two execution paths. The same feature spec drives the batch backfill and the streaming update (the job of a feature store), with a recurring check that offline values match online logged values on a sample, reported as a match rate per feature.
Failure modes.
- The window includes the label event itself, or events after it.
- Event time versus processing time, time zones and late-arriving events at the window boundary.
- Freshness: the online aggregate refreshes hourly while the offline one is exact to the second, so training sees fresher data than serving.
- Corrections and backfills rewrite history that the online system never saw.
- Different handling of missing values (0 versus null) and different code in training (Python) and serving (C++ or Java).
- Entity-key mismatches, such as logged-out versus logged-in ids.
Monitoring. Null rate and distribution per feature, online against training (PSI or quantiles), plus a shadow recomputation for a sample of requests.
Follow-ups
- {‘Log-and-wait versus backfill’: ‘when is each the right call?’}
- A feature has been in production for a year. How do you find out whether it is skewed?
Linear algebra, calculus, optimization math 5% of postings
- Relate PCA, the covariance eigendecomposition and the SVD, and state Eckart-Young
- Check convexity from the Hessian and connect the condition number to gradient-descent speed
- Write gradients and Hessians for least squares and logistic regression in matrix form
- Set up a Lagrangian, state the KKT conditions and interpret a multiplier as a price
coreconceptMLE RE How are PCA, the eigendecomposition of the covariance matrix and the SVD related? What does each give you computationally, and where does PCA mislead?
Centre \(X\in\mathbb{R}^{n\times d}\). The covariance \(C=\frac{1}{n-1}X^\top X=V\Lambda V^\top\) is symmetric positive semi-definite, so it has orthonormal eigenvectors and non-negative eigenvalues. The SVD \(X=U\Sigma V^\top\) has the same \(V\), with \(\lambda_i=s_i^2/(n-1)\) for singular values \(s_i\). The principal directions are the columns of \(V\), the projected data is \(XV=U\Sigma\), and component \(i\) explains \(s_i^2/\sum_j s_j^2\) of the variance.
Optimality (Eckart-Young). The truncated SVD \(X_k=U_k\Sigma_kV_k^\top\) is the best rank-\(k\) approximation in Frobenius and spectral norm, with Frobenius error \(\sqrt{\sum_{i>k}s_i^2}\). Maximising projected variance and minimising reconstruction error are the same problem, and a linear autoencoder recovers the same subspace.
Computation. Take the SVD of \(X\) rather than the eigendecomposition of \(X^\top X\): forming the product squares the condition number. Full SVD costs \(O(\min(nd^2,n^2d))\); for the top \(k\) use randomised SVD or Lanczos, about \(O(ndk)\).
Eigen versus SVD. Eigendecomposition needs a square matrix, and orthogonal eigenvectors need a symmetric (normal) one. The SVD exists for every matrix. For symmetric PSD matrices the two coincide.
Where PCA misleads. It is scale dependent, so standardise. High variance is not relevance to the label; the discriminative direction can be a low-variance one. It is linear, sensitive to outliers, and its components are defined only up to sign (and up to rotation when eigenvalues tie). Fit it on training data only.
The same decomposition gives the pseudo-inverse \(X^{+}=V\Sigma^{+}U^\top\) (minimum-norm least squares), the condition number \(s_{\max}/s_{\min}\), and the low-rank view behind LoRA and embedding compression.
Follow-ups
- Why are the normal equations numerically worse than QR or SVD for least squares?
- You keep 95% of the variance and downstream accuracy drops sharply. What happened?
seniorconceptMLE RE What makes an optimisation problem convex, how do you check it from the Hessian, and what do the Hessian’s eigenvalues tell you about how gradient descent behaves?
\(f\) is convex if its domain is convex and \(f(\theta x+(1-\theta)y)\le\theta f(x)+(1-\theta)f(y)\). Equivalently, the function lies above its tangents, or, for twice-differentiable \(f\), \(\nabla^2f\succeq0\) everywhere. Then every local minimum is global; with strong convexity (\(\nabla^2f\succeq\mu I\), \(\mu>0\)) the minimiser is unique.
Convex: least squares (Hessian \(X^\top X\)), logistic loss (\(X^\top SX\)), hinge loss, L1 and L2 penalties, log-sum-exp, sums and maxima of convex functions. Not convex: anything with a hidden layer (permuting hidden units already gives equivalent minima), matrix factorisation \(\|M-UV^\top\|^2\) (convex in each factor separately, hence alternating least squares), k-means.
Gradient descent on a quadratic with Hessian eigenvalues in \([\mu,L]\):
- It converges only if \(\eta<2/L\): the largest eigenvalue caps the learning rate.
- With \(\eta=1/L\) the error along an eigen-direction with eigenvalue \(h\) shrinks by \(1-h/L\) per step, so the flattest direction contracts by \(1-1/\kappa\), where \(\kappa=L/\mu\) is the condition number. \(\kappa=1000\) means thousands of steps.
- Remedies all precondition: standardising features, momentum (dependence on \(\sqrt\kappa\) instead of \(\kappa\)), Newton’s method (rescales by \(H^{-1}\) at \(O(d^3)\) cost), Adam-style diagonal scaling, normalisation layers.
Deep networks. In high dimension, saddle points are far more common than poor local minima, and gradient noise helps leave them. With full-batch gradient descent the top Hessian eigenvalue is observed to rise until it hovers near \(2/\eta\) (the edge of stability; Cohen et al., 2021).
Mechanics. The gradient of a scalar is a vector in \(\mathbb{R}^d\); the Hessian is \(d\times d\) and symmetric. You almost never form it: a Hessian-vector product costs about two backward passes.
Follow-ups
- Is the composition of two convex functions convex?
- Why does momentum help on ill-conditioned problems?
- How would you estimate the top Hessian eigenvalue of a network with a billion parameters?
seniorderivationMLE RE Use a Lagrangian to show that the maximum-entropy distribution over K outcomes with a fixed expected score is a softmax. Then state the KKT conditions and one place they matter in ML.
Maximise \(H(p)=-\sum_k p_k\log p_k\) subject to \(\sum_k p_k=1\) and \(\sum_k p_ks_k=c\).
\[ \mathcal{L}=-\sum_k p_k\log p_k+\lambda\Big(\sum_k p_ks_k-c\Big)+\nu\Big(\sum_k p_k-1\Big) \]
Stationarity in \(p_k\): \(-\log p_k-1+\lambda s_k+\nu=0\), so \(p_k\propto e^{\lambda s_k}\), and normalising gives
\[ p_k=\frac{e^{\lambda s_k}}{\sum_j e^{\lambda s_j}}. \]
The multiplier \(\lambda\) is fixed by the constraint value \(c\) and acts as an inverse temperature. The objective is concave and the constraints are linear, so this stationary point is the global maximum; the solution is strictly positive, so the constraints \(p_k\ge0\) are inactive.
KKT conditions for \(\min f(x)\) subject to \(g_i(x)\le0\), \(h_j(x)=0\), with \(\mathcal{L}=f+\sum_i\mu_ig_i+\sum_j\nu_jh_j\):
- Stationarity: \(\nabla_x\mathcal{L}=0\).
- Primal feasibility: \(g_i\le0\), \(h_j=0\).
- Dual feasibility: \(\mu_i\ge0\).
- Complementary slackness: \(\mu_ig_i(x)=0\).
For a convex problem satisfying Slater’s condition they are necessary and sufficient, and strong duality holds.
Where they matter.
- SVM: complementary slackness gives non-zero multipliers only for points on or inside the margin (the support vectors), and the dual touches the data only through inner products, which is what admits kernels.
- Ridge and lasso: the penalised form and the constrained form \(\|w\|\le t\) are the same problem, with \(\lambda\) the multiplier.
- A multiplier is a price: the rate of change of the optimum per unit of constraint relaxation. Budget pacing, constrained RL and “maximise engagement subject to a guardrail” are solved by ascending on \(\lambda\) while optimising the Lagrangian.
Follow-ups
- What does a multiplier of zero tell you about its constraint?
- Why can the duality gap be non-zero for a non-convex problem?
coreconceptMLE AI REasked at Google Define KL divergence and explain where it appears in language modelling. Why does the direction matter, what happens when the supports differ, and how do you compute it safely from logits?
\[D_{\mathrm{KL}}(p \,\|\, q) = \sum_x p(x) \log \frac{p(x)}{q(x)} \ge 0,\]
zero only when \(p = q\). It is the expected extra code length (in nats, or bits with \(\log_2\)) from coding samples of \(p\) with a code built for \(q\). It is not symmetric and not a distance: for \(p = (0.5, 0.5)\) and \(q = (0.9, 0.1)\), \(D_{\mathrm{KL}}(p\|q) = 0.51\) and \(D_{\mathrm{KL}}(q\|p) = 0.37\) nats.
Link to the training loss. Cross-entropy decomposes as \(H(p, q) = H(p) + D_{\mathrm{KL}}(p\|q)\). The data entropy \(H(p)\) does not depend on the model, so minimising next-token cross-entropy is minimising the forward KL from the data distribution to the model. Perplexity is \(\exp\) of that cross-entropy.
Direction.
- Forward, \(D_{\mathrm{KL}}(p_\text{data}\|q_\theta)\): the expectation is under the data. The model is punished wherever the data has mass and the model has little, so it spreads to cover everything (mass-covering). This is maximum likelihood, and one reason a language model puts some probability on implausible text.
- Reverse, \(D_{\mathrm{KL}}(q_\theta\|p)\): the expectation is under the model. The model is punished for putting mass where the target has none, so it can ignore modes (mode-seeking). It needs samples from the model and a target density, which is the situation in variational inference and in policy optimisation.
Support. If \(q(x) = 0\) where \(p(x) > 0\), the divergence is infinite; where \(p(x) = 0\) the term is 0 by convention. A softmax never outputs exactly zero, so in practice the problem appears as huge values from tiny probabilities, and with top-k or nucleus truncation, which does create zeros. Jensen-Shannon divergence is the bounded, symmetric alternative.
Where it appears in language models.
- Distillation: minimise \(D_{\mathrm{KL}}(p_\text{teacher}\|p_\text{student})\) per token, often at temperature \(T\) with the loss scaled by \(T^2\).
- Label smoothing: cross-entropy against a smoothed target equals a KL to that target plus a constant.
- Keeping a fine-tuned policy close to a reference: a KL penalty or constraint in policy-gradient fine-tuning, and the KL term of a VAE.
- Measuring change: mean per-token KL between a model and its quantised or fine-tuned version, on the same inputs, is more sensitive than accuracy.
Computing it. Work in log space from logits; never take log of a softmax.
import numpy as np
def kl_from_logits(zp, zq):
"""KL(p || q) per row in nats, logits of shape (..., V)."""
lp = zp - zp.max(-1, keepdims=True); lp = lp - np.log(np.exp(lp).sum(-1, keepdims=True))
lq = zq - zq.max(-1, keepdims=True); lq = lq - np.log(np.exp(lq).sum(-1, keepdims=True))
return (np.exp(lp) * (lp - lq)).sum(-1)Pitfalls: PyTorch’s F.kl_div(input, target) expects log-probabilities as input and probabilities as target, and computes \(D_{\mathrm{KL}}(\text{target}\|\text{input})\); its default reduction='mean' averages over every element, so use 'batchmean' or sum over the vocabulary yourself. For sequences, mask padding and say whether you report per token or per sequence.
Follow-ups
- Fit a single Gaussian to a two-mode distribution under each direction. What do you get?
- Why is the distillation loss multiplied by T squared?
- Two models have the same perplexity on a test set. Can the KL between them be large?
Reported in interviews (candidate reports on third-party sites, not verified)
- Google, Machine Learning Engineer, Aug 2026: KL divergence in language models, including direction and support (PracHub)
Time series and forecasting 5% of postings
- Design a rolling-origin backtest that matches the production horizon, cadence and data latency
- Write the pinball loss, show its minimiser is the quantile, and check quantile coverage
- Encode seasonality (lags, calendar and Fourier features) and pick a scale-free metric such as MASE
- Name the baselines every forecast must beat (seasonal naive, exponential smoothing)
seniordesignMLE RE How do you evaluate a demand-forecasting model so that the offline number predicts production accuracy? Describe the backtest.
Use a rolling-origin (walk-forward) backtest that replays how the model will be used.
Procedure. For cut-offs \(t_1<\dots<t_K\): train on data up to \(t_k\) (expanding or sliding window), forecast the horizon \(t_k+1,\dots,t_k+h\), score, and move on. Report error per horizon step, because it grows with lead time, and the spread across cut-offs.
Match production.
- Same retraining cadence and horizon.
- Same data availability. If actuals arrive two days late, the freshest usable lag at cut-off is two days old.
- Covariates only as known at the cut-off: calendar and planned promotions are fine, weather must be the forecast issued then, not the actuals.
- If history gets revised, use the vintage available at the cut-off.
Leakage paths.
- Random K-fold on time-ordered data.
- Scaling with statistics computed over the whole series.
- Rolling features that include the current value, or lags shorter than the forecast horizon.
- Global models trained across many series must be cut by time for all series, not split by series.
- Tuning on the same windows you report. Keep the last windows as a final holdout.
Coverage. Test windows should span at least one full seasonal cycle, including peaks and holidays.
Metrics. MAE and RMSE are scale dependent. MAPE is undefined at zero and asymmetric. WAPE \(=\sum|e|/\sum|y|\) suits aggregates. MASE divides MAE by the in-sample MAE of the seasonal-naive forecast, so below 1 beats naive. Use pinball loss and coverage for quantiles. Always include seasonal-naive and exponential-smoothing baselines.
Follow-ups
- {‘Expanding or sliding training window’: ‘how do you decide?’}
- Stock-outs censor demand. What does that do to both training and evaluation?
seniorconceptMLE RE A forecast drives inventory decisions, so the business wants the 90th percentile of demand, not the mean. What loss do you train with, why does it work, and how do you handle seasonality and intermittent demand?
Train with the pinball (quantile) loss at \(\tau=0.9\):
\[ L_\tau(y,q)=\max\big(\tau\,(y-q),\ (\tau-1)\,(y-q)\big) \]
Under-prediction costs \(\tau\) per unit and over-prediction \(1-\tau\). Setting the derivative of the expected loss to zero, \(-\tau\,P(y>q)+(1-\tau)\,P(y\le q)=0\), gives \(F(q)=\tau\): the minimiser is the \(\tau\)-quantile. \(\tau=0.5\) is MAE and the median. The newsvendor result picks the level: \(\tau=c_{\text{under}}/(c_{\text{under}}+c_{\text{over}})\).
Several quantiles. One output per \(\tau\) with summed losses. Quantiles can cross; sort them or predict positive increments. Evaluate coverage (the share of actuals below \(\hat q_\tau\) should be close to \(\tau\)) alongside mean pinball loss. Alternatives are a parametric likelihood (negative binomial for counts) and conformal intervals, whose guarantee assumes exchangeability that time series violate.
Why not MSE. MSE targets the conditional mean. Log-transform plus MSE targets the median on the original scale: for log-normal data the mean is \(e^{\mu+\sigma^2/2}\), so naive back-transformation under-forecasts totals.
Seasonality. Calendar features, holiday flags (moving holidays need an explicit calendar), Fourier terms \(\sin(2\pi kt/P)\) and \(\cos(2\pi kt/P)\), seasonal lags such as \(y_{t-7}\) and \(y_{t-364}\), or decompose (STL) and model the remainder. Tree models cannot extrapolate a trend, so difference the target or predict a ratio to a lag.
Intermittent demand. With many zeros, MAPE is useless. Use count likelihoods (Poisson, negative binomial, zero-inflated) or Croston-type methods, evaluate at the level decisions are made, and remember that stock-outs censor observed demand.
Follow-ups
- Your 90% quantile forecast covers 80% of actuals. How do you investigate?
- SKU-level and total forecasts disagree. What do you do?
Bayesian and probabilistic modeling 4% of postings
- Define calibration, compute ECE, and explain why ECE alone is not enough
- Compare Platt scaling, isotonic regression and temperature scaling
- Do a Beta-Binomial update and relate MAP to regularised MLE
- Separate epistemic from aleatoric uncertainty and name practical estimators (ensembles, MC dropout, GPs)
seniorconceptMLE AI REasked at Nvidia What does it mean for a classifier to be calibrated, how do you measure it, and how do Platt scaling, isotonic regression and temperature scaling differ?
Calibrated means \(P(Y{=}1\mid\hat p=p)=p\): of the cases scored 0.2, 20% are positive. It matters whenever the score is used as a probability: bids (\(\text{pCTR}\times\text{value}\)), expected loss, cost-based thresholds, combining models. It is irrelevant to pure ranking, since AUC is invariant to monotone maps.
Measuring. A reliability diagram with bin counts, and
\[ \mathrm{ECE}=\sum_b\frac{|B_b|}{n}\,\big|\,\bar y_b-\bar p_b\,\big| . \]
ECE depends on the binning, is usually top-label only in multiclass, and is zero for a constant predictor that outputs the base rate. Pair it with a proper scoring rule (NLL or Brier), a ranking metric, and the aggregate ratio of mean prediction to mean label, by slice.
Post-hoc methods, all fit on held-out data, never on the training set:
| Method | Map | Notes |
|---|---|---|
| Platt scaling | \(\sigma(az+b)\) | Two parameters, low variance, fine with little data; assumes a sigmoid-shaped distortion |
| Temperature scaling | \(\mathrm{softmax}(z/T)\) | One parameter fit by NLL; keeps the argmax, so accuracy is unchanged; cannot fix a base-rate shift or per-class bias |
| Isotonic regression | Non-decreasing step function | Non-parametric and flexible; needs more data, creates ties, noisy in the tails |
All three are monotone, so ranking is preserved up to ties.
Sources of miscalibration. Resampling and class weights (correct analytically), focal loss and label smoothing, over-parameterised networks trained to near-zero training loss (over-confident, \(T>1\)), boosted trees and SVM margins, and distribution shift, since calibration is always relative to a population.
A model can be calibrated overall and miscalibrated in every segment; check slices. Version the calibrator with the model: retraining the model invalidates it.
Follow-ups
- Can a model be perfectly calibrated and useless?
- Why does temperature scaling not change accuracy, and when is that a limitation?
- Negatives were downsampled in training. Do you fix that with Platt scaling or analytically?
Reported in interviews (candidate reports on third-party sites, not verified)
- Nvidia, Machine Learning Engineer, Feb 2026: Bias-variance trade-off, calibration and model drift (PracHub)
seniorconceptMLE RE Give a Bayesian treatment of estimating a click-through rate from a handful of impressions. How does it relate to MLE, MAP and regularisation, and when is the extra machinery worth it?
Prior \(\theta\sim\mathrm{Beta}(\alpha,\beta)\); data \(k\) clicks in \(n\) impressions. The Beta is conjugate to the binomial, so the posterior is \(\mathrm{Beta}(\alpha+k,\ \beta+n-k)\) with mean
\[ \frac{\alpha+k}{\alpha+\beta+n}=\frac{n}{n+\alpha+\beta}\cdot\frac{k}{n}+\frac{\alpha+\beta}{n+\alpha+\beta}\cdot\frac{\alpha}{\alpha+\beta}. \]
The prior acts as \(\alpha+\beta\) pseudo-impressions. With 0 clicks in 3 impressions the MLE says 0; under \(\mathrm{Beta}(1,19)\) (prior mean 5%) the posterior mean is \(1/23\approx4.3\%\). The posterior mean is also the predictive probability of a click on the next impression.
Relations. MLE maximises \(p(D\mid\theta)\). MAP maximises \(p(D\mid\theta)\,p(\theta)\), which is MLE plus a regulariser: a Gaussian prior gives L2 and a Laplace prior gives L1. MAP is still a point estimate. Full Bayes keeps the posterior and predicts with \(p(y^*\mid D)=\int p(y^*\mid\theta)\,p(\theta\mid D)\,d\theta\).
What the posterior buys.
- Uncertainty that shrinks with data, hence credible intervals.
- Exploration: Thompson sampling draws \(\theta\) from the posterior and acts greedily on the draw.
- Partial pooling: estimate the prior from all items (empirical Bayes, hierarchical models) so long-tail items borrow strength. Smoothed target encoding is this.
Vocabulary. Epistemic uncertainty comes from limited data and is reducible; aleatoric is noise in the outcome and is not.
Beyond conjugacy. MCMC (asymptotically exact, slow), variational inference (maximise an ELBO; fast, tends to under-estimate variance), Laplace approximation. Gaussian processes give an exact posterior over functions at \(O(n^3)\) cost and are used for small data and Bayesian optimisation. For deep networks, ensembles and MC dropout are the pragmatic approximations, and ensembles are usually the stronger baseline.
It is worth it with little data per entity, a need for exploration, or decisions that depend on uncertainty. With abundant data the posterior concentrates and a point estimate is enough.
Follow-ups
- How would you choose alpha and beta from historical data?
- Compare Thompson sampling with UCB.
- What is the difference between a credible interval and a confidence interval?
Causal inference 3% of postings
- Write the selection-bias decomposition and the assumptions behind adjustment (unconfoundedness, overlap, SUTVA)
- Write the IPW and doubly robust estimators and name their failure modes
- Apply difference-in-differences and say how to probe parallel trends
- Distinguish uplift from response modelling and evaluate uplift with a Qini curve
seniorconceptMLE RE Users who received a push notification show 30% higher retention. Why can’t you read that as the effect of the notification, and how would you estimate the effect from observational data?
Notifications were targeted, so treated and untreated users differ in ways that also drive retention. That is confounding:
\[ \mathbb{E}[Y\mid T{=}1]-\mathbb{E}[Y\mid T{=}0] =\underbrace{\mathbb{E}[Y(1)-Y(0)\mid T{=}1]}_{\text{effect on the treated}} +\underbrace{\mathbb{E}[Y(0)\mid T{=}1]-\mathbb{E}[Y(0)\mid T{=}0]}_{\text{selection bias}} \]
Randomising removes the second term. Without it, adjustment needs three assumptions: unconfoundedness \((Y(0),Y(1))\perp T\mid X\), which is untestable; overlap \(0<e(x)<1\) for the propensity \(e(x)=P(T{=}1\mid X{=}x)\); and no interference between units (SUTVA).
Estimators:
- Regression adjustment: model \(\mu_t(x)=\mathbb{E}[Y\mid X{=}x,T{=}t]\) and average \(\mu_1-\mu_0\).
- Inverse propensity weighting: \[ \hat\tau_{\text{IPW}}=\frac1n\sum_i\left[\frac{T_iY_i}{\hat e(X_i)}-\frac{(1-T_i)Y_i}{1-\hat e(X_i)}\right] \]
- Doubly robust (AIPW): the regression estimate plus an IPW correction of its residuals. It is consistent if either the outcome model or the propensity model is correct.
Failure modes:
- Propensities near 0 or 1 give huge weights. Clip or trim, use self-normalised weights, and report the effective sample size. A propensity model with AUC near 1 means there is no overlap, not that the model is good.
- Adjust only for pre-treatment covariates. Conditioning on a mediator or a collider adds bias.
- Unmeasured confounders: run sensitivity analysis and negative controls, or look for an instrument or natural experiment.
Checks: covariate balance after weighting (standardised mean differences below about 0.1) and a placebo outcome, for example retention before the notification, which should show no effect.
The same weighting underlies off-policy evaluation and position-bias correction in ranking.
Follow-ups
- Why does a more accurate propensity model sometimes make the estimate worse?
- What is the difference between ATE and ATT, and which does a launch decision need?
- Give an example of a collider in a product dataset.
stafftrade-offMLE Two causal questions. (a) A feature launched in one country only, with no experiment. How do you estimate its effect? (b) You ran a randomised promotion experiment and must decide who gets the promotion. How is that different from predicting who will buy?
(a) Difference-in-differences.
\[ \hat\tau=(\bar Y_{T,\text{post}}-\bar Y_{T,\text{pre}})-(\bar Y_{C,\text{post}}-\bar Y_{C,\text{pre}}) \]
It removes fixed differences between the groups and shocks common to both. The assumption is parallel trends: without the launch, both would have moved alike. It cannot be tested after launch; probe it with pre-period trends (an event-study plot whose pre-launch coefficients should be near zero) and placebo launch dates. Threats are concurrent events in one group, spillovers, anticipation and a changing user mix. With one treated country there are very few independent clusters, so naive standard errors are far too small; use cluster-robust or permutation inference. If no control is parallel, a synthetic control builds a weighted mix of untreated units that tracks the pre-period.
(b) Uplift. The target is \(\tau(x)=\mathbb{E}[Y(1)-Y(0)\mid X{=}x]\), not \(\mathbb{E}[Y\mid X{=}x]\). Likely buyers include “sure things” who buy anyway, so targeting on purchase propensity wastes the budget; you want those whose behaviour changes. Nobody is observed under both arms, so there is no per-row label.
- Methods: T-learner (one model per arm, subtract; noisy when the effect is small relative to outcome variance), S-learner (treatment as a feature; tends to shrink the effect towards zero), X-, R- and DR-learners, causal forests. With randomised data and propensity \(e\), the transformed outcome \(Y(T-e)/(e(1-e))\) has conditional mean \(\tau(x)\).
- Evaluation: rank by predicted uplift and compare treated against control outcomes within each top fraction (uplift or Qini curve), then A/B test the targeting policy against treating everyone and against random targeting.
- Decision: treat when \(\tau(x)\times\text{value}>\text{cost}\); under a budget, rank by uplift per unit cost.
Effects are small relative to noise, so uplift models need much larger experiments than response models.
Follow-ups
- What does a violated pre-trend look like, and what do you do then?
- Why can’t you evaluate an uplift model with RMSE?