ML, AI & LLMs
Maths and statistics, classical ML, deep learning, transformers, LLM training and alignment, RAG, agents, evaluation, safety, inference, and ML system design with 3 full walkthroughs.
00Full ML, LLM & GenAI topic atlas
A navigation map from problem framing through modeling, evaluation, and production. The detailed reference sections follow below.
End-to-end topic map#
Use this atlas for breadth, then follow the colored section links in the coverage map below for the detailed recipes already in the sheet.
Route by the learning objective#
flowchart LR
S[What decision or output is needed?] --> Q{{Objective}}
Q -->|class or numeric value| SUP[Supervised learning: classification / regression]
Q -->|ordered results or items| REC[Ranking / recommendation: retrieve then rank]
Q -->|future values in time| TS[Forecasting: naive baseline → statistical / ML / DL]
Q -->|groups or compact representation| UNS[Unsupervised: clustering / embeddings / PCA]
Q -->|rare or novel events| AN[Anomaly detection: rules → isolation / density / reconstruction]
Q -->|effect of an intervention| CA[Causal inference: experiment if possible, otherwise adjustment]
Q -->|action with delayed reward| RL[Bandit / reinforcement learning]
Q -->|new content or continuation| GEN[Generative model: VAE / diffusion / autoregressive LM]
SUP --> MOD{{Data modality}}
MOD -->|tabular| TAB[Linear baseline → GBDT]
MOD -->|image / audio / text| PRE[Pretrained representation → fine-tune]
REC --> RANK[Evaluate retrieval recall and ranking quality]
TS --> SPLIT[Time-ordered backtest]
CA --> ASSUME[State assumptions and validate effects]
RL --> SAFE[Offline policy checks → guarded online test]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,MOD decChoose the task before choosing the model. Check label availability, data volume, leakage risk, latency, interpretability, and cost.
Check yourself 2 questions
The output is an ordered list of items. Which family?
Show answer
Ranking or recommendation.
The output is a class or a number?
Show answer
Supervised classification or regression.
Takeaway Start from the decision needed: class or value → supervised, ordered results → ranking, groups → clustering, text → LLM.
Classical ML lifecycle and decision gates#
flowchart TD
P[Problem + success metric] --> D[Collect, inspect, label]
D --> S[Split by time / group / entity]
S --> B[Simple baseline]
B --> F[Features + candidate models]
F --> V[Cross-validation + tuning]
V --> E[Holdout, calibration, slices]
E --> G{{Quality, fairness, latency, cost pass?}}
G -->|no| I[Inspect errors / data / objective] --> F
G -->|yes| C[Canary / shadow / A-B]
C --> M[Monitor drift, quality, latency, cost]
M -->|feedback| D
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class G decSplit before fitting any learned transform. Match the split to the deployment unit: time, person, site, or group.
Check yourself 2 questions
Why build a simple baseline early?
Show answer
Every fancier model must beat it to justify its cost.
How should data be split?
Show answer
By time, group or entity, to avoid leakage.
Takeaway Problem and metric, data and labels, a leakage-safe split, a simple baseline, features and models, validation, then deploy and monitor.
Choose an LLM application architecture#
flowchart TD
S[Start with a strong hosted or open model] --> Q{{What is missing?}}
Q -->|nothing beyond task instructions| P[Prompt + structured output]
Q -->|fresh, private, or cited knowledge| R[RAG: retrieve → rerank → ground]
Q -->|stable behavior, style, or task format| FT[Fine-tune / LoRA with curated examples]
Q -->|API or external action required| A[Bounded tool workflow / agent]
Q -->|model capability itself is missing| M[Distill, continue pretraining, or train]
P --> E[Evaluate quality, safety, latency, and cost]
R --> E
FT --> E
A --> E
M --> E
E --> G{{Pass offline and red-team gates?}}
G -->|no| FIX[Improve data, retrieval, prompt, model, or tools] --> E
G -->|yes| SH[Canary → monitor → rollback-ready]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class Q,G decUse RAG for changing facts and source grounding; use fine-tuning for repeatable behavior. Add agents only when a bounded tool action is needed.
Check yourself 2 questions
What's missing if you need fresh, private or cited knowledge?
Show answer
Retrieval: add RAG.
When does fine-tuning make sense?
Show answer
When behaviour, format or style must change and prompting isn't enough.
Takeaway Start with a strong model and prompts; add RAG for fresh or private knowledge, tools for actions, fine-tuning for behaviour.
Evaluation is a stack, not one score#
| Layer | Questions | Examples |
|---|---|---|
| Data & split | Is the test set representative and uncontaminated? | Time/group split, dedup, label audit |
| Task quality | Does the model solve the actual task? | PR-AUC, calibration, NDCG/MRR, exact match |
| Robustness & slices | Where does it fail, and for whom? | Subgroup slices, stress tests, shift tests |
| LLM / RAG | Are answers grounded, useful, safe, and complete? | Retrieval recall, faithfulness, citation checks, human review |
| Production | Can it meet service constraints? | p95 latency, availability, tokens/request, cost, fallback rate |
| Online evidence | Did the change improve outcomes safely? | Shadow, canary, A/B, rollback thresholds |
Use automated metrics for broad regression coverage and human review for ambiguous quality and safety judgments.
Common evaluation traps
- Near-duplicate examples across train and test inflate scores; deduplicate before splitting.
- Tuning on the test set: use a validation set and touch the test set once.
- Averages hide failing slices; report metrics per segment.
- An offline gain is not a business gain until an online test confirms it.
- LLM judges drift: pin the judge model and prompt, and spot-check with humans.
- Pick the metric for the decision it drives: precision@k for a feed, calibration for a threshold, recall for safety filters.
Check yourself 2 questions
First layer of the evaluation stack?
Show answer
Data and split: representative and uncontaminated.
Why isn't one offline score enough?
Show answer
It misses robustness, fairness, cost, latency and real user impact.
Takeaway Evaluate data and split, task quality, robustness and fairness, cost and latency, and online impact.
Coverage map — detailed reference sections#
| Topic family | Patterns and decisions | Jump |
|---|---|---|
| Problem framing & model choice | Learning objective, modality, baseline, algorithm selection | §01 · §0 objective flow |
| Data & classical ML | Preprocessing, leakage-safe validation, model families, metrics, time series, HPO | §04 |
| Deep learning & generation | Training loop, architectures, optimization, VAE/GAN/diffusion/flows | §08 |
| LLM training & applications | Pretraining, SFT/alignment, prompting, RAG, agents, hallucination | §11 |
| Inference & serving | Prefill/decode, KV cache, parallelism, quantization, latency/cost levers | §15 |
| System design & MLOps | Deployment, feature/data systems, monitoring, incidents, governance | §16 |
Check yourself 2 questions
What does the coverage map help with?
Show answer
Jumping to the section that covers a topic family.
Name one topic family listed.
Show answer
Any of: problem framing, data and classical ML, deep learning, LLMs, MLOps.
Takeaway The coverage map points each topic family to its detailed section.
Advanced routes to recognize#
| Signal | Route | Key check |
|---|---|---|
| Personalized ranking at scale | Candidate retrieval → feature-rich ranker → re-rank / constraints | Offline NDCG/Recall plus online experiment; watch popularity and position bias. |
| Estimate treatment impact | Randomized experiment → causal effect; observational data → matching / weighting / doubly robust | State identification assumptions, interference, and uncertainty. |
| Choose actions from feedback | Contextual bandit → constrained RL only when delayed state matters | Safe exploration, off-policy evaluation, reward hacking checks. |
| Relational inputs | Graph features / message-passing GNN | Compare against tabular and embedding baselines; guard against neighbor leakage. |
| Text, image, audio, video together | Pretrained modality encoders → fusion / cross-attention → task head or generative model | Align timestamps, modality failures, and evaluation by modality. |
| Small labeled dataset | Transfer learning, frozen embeddings, PEFT, augmentation, active labeling | Keep validation independent; avoid synthetic-data leakage. |
| Model quality regresses after launch | Trace data → features/retrieval → model → serving → user outcome | Separate input drift, label/concept drift, retrieval failure, and service failure. |
Check yourself 2 questions
Personalised ranking at scale: the route?
Show answer
Candidate retrieval, a feature-rich ranker, then re-ranking with constraints.
Which checks matter for it?
Show answer
Offline NDCG or recall plus an online experiment, watching popularity and position bias.
Takeaway Personalised ranking, retrieval at scale and similar advanced routes each have a recognisable shape and key check.
01Map & algorithm selection
Ml-overview/19-revision-guide/*, 03-classical-ml/03-algorithms.md §14
Algorithm selection (start here)#
| Problem | First choice | Why |
|---|---|---|
| Tabular, mixed types | XGBoost / LightGBM | handles missing, non-linearity natively |
| Tabular, needs interpretability | Logistic regression + FE | coefficients meaningful, calibrated |
| Images | pretrained CNN / ViT fine-tuned | representation learning |
| Text classification | fine-tuned LM | pretrained context |
| Anomaly, no labels | Isolation Forest, DBSCAN, autoencoder | unsupervised |
| Small data, odd structure | KNN / SVM-RBF | non-parametric / kernel |
- Always a simple baseline first (LR / single tree) — tells you if complexity buys anything
- RF vs XGBoost: noisy data / little tuning → RF; time to tune → XGBoost; XGB more outlier-sensitive (fits residuals)
- Logistic regression is linear in log-odds; non-linear boundary → bias, more data won't help; sklearn
C= inverse regularisation
Check yourself 2 questions
First choice for tabular mixed-type data?
Show answer
XGBoost or LightGBM.
Tabular data needing interpretability?
Show answer
Logistic regression with feature engineering.
Takeaway Tabular → gradient boosting; interpretable → logistic regression; images → CNNs or ViTs; text → transformers.
02Math and statistics foundations
The math that interviewers ask you to derive or explain on the spot.
Linear algebra#
- Dot product a·b = |a||b|cosθ: similarity, projections, attention scores.
- Matrix multiply (m×n)(n×p): cost m·n·p; a linear layer is
y = Wx + b. - Eigen Av = λv; covariance eigenvectors = principal components.
- SVD A = UΣVᵀ: PCA, low-rank approximation (LoRA intuition), recommender MF.
- Rank: number of independent directions; low rank → compressible.
- Norms: L1 (sparsity), L2 (energy), Frobenius, spectral.
- Positive semi-definite: covariance and kernel matrices; convex quadratic forms.
Check yourself 2 questions
Cost of multiplying (m×n) by (n×p)?
Show answer
m·n·p.
What are the eigenvectors of a covariance matrix?
Show answer
Principal components (PCA directions).
Takeaway Dot products measure similarity, matrix multiplies are layers, eigenvectors of covariance are principal components.
Calculus and optimisation#
- Chain rule is backprop: ∂L/∂x = ∂L/∂y · ∂y/∂x.
- Gradient points uphill; step against it. Jacobian for vector outputs; Hessian for curvature.
- Convex → any local minimum is global (linear/logistic regression, SVM).
- Neural nets are non-convex; saddle points matter more than bad local minima.
- Lagrange multipliers: constrained optimisation (SVM dual).
- Learning rate too high → divergence; too low → slow; use warmup + decay.
Check yourself 2 questions
What is backprop, mathematically?
Show answer
Repeated application of the chain rule.
In a convex problem, what's special about a local minimum?
Show answer
It's the global minimum.
Takeaway The chain rule is backprop, gradients point uphill, and convex problems have no bad local minima.
Probability essentials#
- Independence: P(A∩B)=P(A)P(B). Conditional independence underlies Naive Bayes.
- CLT: sample means → normal, std error σ/√n.
- LLN: averages converge to the expectation.
- Base-rate fallacy: 99% accurate test on a 1% disease → ~50% precision.
Check yourself 2 questions
Bayes' rule?
Show answer
P(A|B) = P(B|A)·P(A) ÷ P(B).
Var(X) in terms of expectations?
Show answer
E[X²] − E[X]².
Takeaway Bayes' rule, linearity of expectation, variance identities, independence and the CLT underpin ML.
Distributions to know#
| Distribution | Models | Mean / var |
|---|---|---|
| Bernoulli(p) | One yes/no trial | p / p(1−p) |
| Binomial(n,p) | Successes in n trials | np / np(1−p) |
| Poisson(λ) | Event counts per interval | λ / λ |
| Geometric(p) | Trials to first success | 1/p |
| Exponential(λ) | Time between events; memoryless | 1/λ / 1/λ² |
| Normal(μ,σ²) | Sums of many effects; 68-95-99.7 | μ / σ² |
| Beta(α,β) | Prior over a probability (Thompson sampling) | α/(α+β) |
| Categorical / Dirichlet | Multi-class outcome / prior over it | — |
Check yourself 2 questions
Poisson mean and variance?
Show answer
Both λ.
Binomial(n, p) variance?
Show answer
np(1 − p).
Takeaway Bernoulli, binomial, Poisson, geometric, normal and more, each with a mean and variance to know.
Estimation and information theory#
- MLE: maximise likelihood. Gaussian noise → MSE; Bernoulli → cross-entropy.
- MAP: MLE + prior. Gaussian prior = L2; Laplace prior = L1.
- Entropy H(p) = −Σ p log p; cross-entropy H(p,q) = −Σ p log q.
- KL divergence = H(p,q) − H(p); asymmetric; used in VAEs, RLHF penalty, distillation.
- Bias–variance: error = bias² + variance + noise. More capacity ↓bias ↑variance.
- Mutual information: shared information; feature selection.
Check yourself 2 questions
Which prior corresponds to L2 regularisation?
Show answer
A Gaussian prior.
MLE with Gaussian noise gives which loss?
Show answer
MSE.
Takeaway MLE maximises likelihood; MAP adds a prior (Gaussian = L2, Laplace = L1); cross-entropy and KL measure distribution gaps.
Hypothesis tests and A/B testing#
- p-value: P(data this extreme | H₀). Not P(H₀ true).
- Type I (α, false positive) vs type II (β, missed effect); power = 1−β, aim 0.8.
- Sample size per arm ≈
16σ²/δ²for α=0.05, power 0.8. - Tests: t-test (means), z/χ² (proportions), Mann-Whitney (non-normal), bootstrap CIs.
- Pitfalls: peeking (use sequential tests), multiple comparisons (Bonferroni/BH), novelty effects, sample ratio mismatch, network interference.
- CUPED: subtract pre-period covariate to cut variance.
- Guardrail metrics (latency, revenue, complaints) alongside the primary metric.
Check yourself 2 questions
What does a p-value measure?
Show answer
P(data this extreme | H₀), not P(H₀ true).
Rule-of-thumb sample size per arm?
Show answer
About 16σ² ÷ δ² for α = 0.05 and power 0.8.
Takeaway A p-value is P(data this extreme | H₀); aim for power 0.8; sample size per arm ≈ 16σ²/δ².
Causal inference toolkit#
| Method | Key assumption | Use when |
|---|---|---|
| Randomised experiment (A/B) | Random assignment; no interference between units | You can control who gets the treatment |
| Regression adjustment | All confounders are measured and modelled correctly | Observational data with rich covariates |
| Propensity matching / weighting (IPW) | No unmeasured confounding; overlap between groups | Treatment chosen by observed factors |
| Doubly robust / double ML | Either the outcome or the propensity model is right | High-dimensional confounders, ML nuisance models |
| Difference-in-differences | Parallel trends without treatment | Policy launched in some regions or times, not others |
| Synthetic control | A weighted mix of untreated units mimics the treated one | One treated unit (a country, a city) |
| Regression discontinuity | Units just above and below a cutoff are comparable | Treatment assigned by a threshold (credit score, age) |
| Instrumental variables | The instrument affects the outcome only through the treatment | Unmeasured confounding with a valid instrument |
| Uplift modelling (S-, T-, X-learners) | Experimental or well-adjusted data | Target the users whom treatment changes most (CATE) |
Check yourself 2 questions
Difference-in-differences key assumption?
Show answer
Parallel trends.
When can you use a randomised experiment?
Show answer
When you control who gets the treatment.
Takeaway Randomised experiments, regression adjustment, matching, diff-in-diff, IV and RDD each rest on a key assumption.
03Formulas: metrics, losses, optimisers, model maths
Write these from memory. Most interview derivations start from one of them.
Classification metrics#
- ROC-AUC = P(random positive scores above random negative); threshold-free.
- PR-AUC baseline = positive rate; use it when positives are rare.
- Pick the threshold from business costs, not 0.5.
- Macro (average per class) vs micro (pool counts) vs weighted averaging.
Check yourself 2 questions
Precision formula?
Show answer
TP ÷ (TP + FP).
Which curve suits heavy class imbalance?
Show answer
Precision-recall (PR-AUC).
Takeaway Precision, recall, F1, specificity, ROC-AUC and PR-AUC each answer a different error-cost question.
Regression, ranking and generation metrics#
- MAPE explodes near zero; use sMAPE or MAE for such targets.
- BLEU (n-gram precision), ROUGE (recall, summaries), BERTScore (embedding match).
Check yourself 2 questions
MRR formula?
Show answer
Mean of 1 ÷ rank of the first relevant result.
RMSE versus MAE: which punishes large errors more?
Show answer
RMSE.
Takeaway MAE and RMSE for regression, NDCG, MRR and Recall@k for ranking, BLEU, ROUGE and judges for generation.
Loss functions#
| Loss | Formula / idea | Use |
|---|---|---|
| MSE / MAE / Huber | (y−ŷ)², |y−ŷ|, quadratic near 0 then linear | Regression; Huber resists outliers |
| Cross-entropy | −Σ y log softmax(z) | Classification, language modelling |
| Focal | −(1−p)^γ log p | Heavy class imbalance, detection |
| Hinge | max(0, 1 − y·f(x)) | SVM |
| Contrastive / InfoNCE | −log e^{s⁺/τ} / Σ e^{s/τ} | Embeddings, CLIP, retrieval |
| Triplet | max(0, d(a,p) − d(a,n) + m) | Metric learning, face ID |
| KL divergence | Σ p log(p/q) | VAE, distillation, RLHF penalty |
| Pairwise ranking | log(1 + e^{−(s_i − s_j)}) | Learning to rank, reward models |
Check yourself 2 questions
Which regression loss resists outliers?
Show answer
Huber (or MAE).
Loss for language modelling?
Show answer
Cross-entropy.
Takeaway MSE, MAE and Huber for regression, cross-entropy for classification, focal for imbalance, contrastive for embeddings.
Optimiser updates#
- Adam memory: 2 extra states per parameter → ~16 bytes/param with fp32 master weights in mixed precision.
Check yourself 2 questions
What does AdamW change from Adam?
Show answer
Weight decay is decoupled from the gradient update.
Why bias-correct Adam's moments?
Show answer
They start at zero and are biased early in training.
Takeaway SGD, momentum, Adam with bias correction, and AdamW with decoupled weight decay.
Neural-net building blocks#
Check yourself 2 questions
Attention formula?
Show answer
softmax(QKᵀ ÷ √d_k) V.
RMSNorm versus LayerNorm?
Show answer
RMSNorm skips mean-centring and normalises by root mean square.
Takeaway Sigmoid, softmax, scaled dot-product attention, LayerNorm, RMSNorm and SwiGLU are the building blocks.
LLM sizing maths#
- 7B in bf16 ≈ 14 GB weights; Llama-style 70B with GQA ≈ 0.3 MB KV per token in bf16.
Check yourself 2 questions
Training FLOPs formula?
Show answer
About 6 × parameters × tokens.
Memory for 7B parameters in bf16?
Show answer
About 14 GB.
Takeaway Params ≈ 12·L·d²; training FLOPs ≈ 6ND; inference ≈ 2N per token; weights memory = N × bytes per param.
04Data, classical ML, evaluation
Ml-overview/19-revision-guide/02-data, 03-classical-ml, 04-evaluation; practical ml/sklearn_cheatsheet.md
Data & validation#
- Missingness: MCAR / MAR / MNAR → impute + missing-indicator
- Outliers: IQR / z-score — error vs signal?
- Scaling: Standard / MinMax / Robust; log1p / Yeo-Johnson for skew
- Encoding: one-hot, ordinal, target (+smoothing, OOF), frequency
- Leakage: preprocessing before split, target, temporal, group, target-encoding
- CV: Stratified K-Fold, TimeSeriesSplit, GroupKFold, nested CV for HPO
- Drift: covariate / label / concept; PSI, KS test
Check yourself 2 questions
Good practice when imputing?
Show answer
Add a missing-indicator feature.
Transform for skewed features?
Show answer
log1p or Yeo-Johnson.
Takeaway Handle missingness types, judge outliers, scale and encode correctly, and validate on leakage-safe splits.
Classical ML#
| Topic | Key point |
|---|---|
| Regularisation | L1 sparse (diamond corners), L2 shrinks, ElasticNet both |
| SVM | max margin; kernel trick; C trades margin vs errors |
| Trees | split by Gini/entropy; high variance alone |
| Bagging / RF | reduce variance; OOB estimate |
| Boosting | reduce bias; sequential residuals; lr × n_estimators |
| KNN | scale features; curse of dimensionality |
| Naive Bayes | independence assumption; great for text |
| K-Means | K-Means++ init; spherical clusters; elbow / silhouette |
| DBSCAN | core / border / noise; arbitrary shapes |
| GMM | EM: E-step responsibilities, M-step params |
| PCA | SVD; variance explained; linear only |
| t-SNE / UMAP | viz; t-SNE local only, UMAP keeps more global |
| Stacking | out-of-fold predictions → meta learner |
Check yourself 2 questions
Which regulariser produces sparse weights?
Show answer
L1.
How do random forests reduce tree variance?
Show answer
Bagging and random feature subsets.
Takeaway L1 sparsifies, L2 shrinks; SVMs maximise margin; trees are high-variance, fixed by bagging or boosting.
Evaluation#
| Metric | Use when |
|---|---|
| Accuracy | use when class balance and error costs make it meaningful; add class-wise metrics |
| Precision | false positives costly (spam) |
| Recall | false negatives costly (fraud, cancer) |
| F1 | balance P/R on imbalance |
| ROC-AUC | ranking, balanced-ish |
| PR-AUC | heavy imbalance |
| Log-loss / Brier / ECE | probability quality, calibration |
| MAE / RMSE / MAPE | regression; RMSE punishes large errors |
| NDCG / MAP / MRR | ranking & retrieval |
| BLEU / ROUGE / BERTScore | generation (weak); LLM-as-judge |
Check yourself 2 questions
Fraud detection favours which metric?
Show answer
Recall (false negatives are costly).
Spam filtering favours?
Show answer
Precision (false positives are costly).
Takeaway Choose metrics by error costs: precision when false positives hurt, recall when misses hurt.
Time series & HPO#
- Stationarity (ADF), ACF/PACF → ARIMA orders; SARIMA, Holt-Winters, Prophet
- Walk-forward validation; lag/rolling features for trees
- DL: TCN, PatchTST, N-BEATS; foundation: Chronos, TimesFM
- HPO: grid → random (log-uniform) → Bayesian (TPE/Optuna) → Hyperband/ASHA, PBT
Check yourself 2 questions
Validation scheme for time series?
Show answer
Walk-forward (rolling or expanding).
How do tree models use time series?
Show answer
Lag and rolling-window features.
Takeaway Check stationarity, use walk-forward validation, lag features for trees, and search hyperparameters smartly.
sklearn workflow (your template)#
X_tr,X_te,y_tr,y_te = train_test_split(X,y,stratify=y,random_state=42) # split FIRST pre = ColumnTransformer([ ("num", Pipeline([("imp",SimpleImputer(strategy="median")),("sc",StandardScaler())]), num_cols), ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols)]) pipe = Pipeline([("pre",pre),("clf",HistGradientBoostingClassifier())]) cross_val_score(pipe,X_tr,y_tr,cv=StratifiedKFold(5,shuffle=True,random_state=42)) RandomizedSearchCV(pipe,{"clf__learning_rate":...},cv=cv) # step__param naming pipe.fit(X_tr,y_tr); evaluate ONCE on X_te; joblib.dump(pipe,"model.pkl")
Check yourself 2 questions
Why split before any fitting?
Show answer
To prevent leakage of test statistics.
What bundles preprocessing and the model?
Show answer
A Pipeline (with a ColumnTransformer).
Takeaway Split first, then a ColumnTransformer inside a Pipeline, fit on train only, tune with CV.
sklearn mistakes checklist#
- fit/fit_transform on full data before split → leakage
- fit_transform on test re-learns stats — only
.transform() - OneHotEncoder needs
handle_unknown="ignore" - SMOTE only inside CV folds (imblearn Pipeline)
- Accuracy misleads on imbalance → F1 / PR-AUC / class_weight
- Set random_state; same CV splitter across models
- Grid too slow → RandomizedSearchCV
Check yourself 2 questions
Why not fit_transform on the test set?
Show answer
It re-learns statistics from test data; use transform only.
Where must SMOTE run?
Show answer
Only inside training folds of cross-validation.
Takeaway Never fit on full data, only transform the test set, ignore unknown categories, and oversample only inside CV folds.
05Classical algorithms in depth
How each algorithm learns, what to tune, and the follow-up question interviewers usually ask about it.
Algorithm reference#
| Algorithm | How it learns | Key hyperparameters | Strengths | Watch out |
|---|---|---|---|---|
| Linear regression | Minimise squared error; closed form (XᵀX)⁻¹Xᵀy or gradient descent | Regularisation α (ridge, lasso) | Fast, interpretable coefficients | Assumes linearity; outliers and collinearity distort coefficients |
| Logistic regression | Sigmoid of a linear score; minimise log loss (convex) | C (inverse regularisation), penalty, class_weight | Calibrated probabilities, strong baseline | Needs scaling and feature engineering for non-linear boundaries |
| Decision tree | Greedy splits that maximise impurity reduction | max_depth, min_samples_leaf, ccp_alpha | Handles mixed types and interactions, readable | High variance; overfits without limits |
| Random forest | Bagging of deep trees on bootstrap samples with random feature subsets | n_estimators, max_features, max_depth | Robust, little tuning, OOB estimate | Large models; weak at extrapolation |
| Gradient boosting | Adds shallow trees that fit the negative gradient of the loss | learning_rate × n_estimators, depth or num_leaves, subsample, regularisation | Best accuracy on most tabular data | Overfits with high learning rate; needs early stopping |
| SVM | Maximise the margin; kernels map to higher dimensions implicitly | C, kernel, γ (RBF) | Strong on small, high-dimensional data | O(n²)–O(n³) training; no native probabilities |
| k-nearest neighbours | No training; vote or average over the k closest points | k, distance metric, weighting | Simple, non-parametric | Slow prediction; needs scaling; curse of dimensionality |
| Naive Bayes | Bayes rule assuming features independent given the class | Smoothing α, variant (multinomial, Gaussian, Bernoulli) | Very fast, good text baseline | Poorly calibrated when features correlate |
| k-means | Alternate: assign to nearest centroid, recompute centroids | k, init (k-means++), n_init | Fast, scalable | Spherical, similar-size clusters only; sensitive to scale and outliers |
| DBSCAN | Grow clusters from dense core points | eps, min_samples | Arbitrary shapes, labels noise | One density for all clusters; eps hard to pick |
| Gaussian mixture (EM) | E-step: soft assignments; M-step: update means, covariances, weights | Components, covariance type | Soft clustering, density estimate | Local optima; choose k with BIC |
| PCA | Eigenvectors of the covariance matrix (via SVD) | Components or variance to keep | Compression, decorrelation, denoising | Linear only; scale features first |
| t-SNE / UMAP | Preserve local neighbourhoods in 2–3 dimensions | Perplexity / n_neighbors, min_dist | Visualisation of clusters | Distances between clusters aren't meaningful; not for features |
| Isolation forest | Random splits isolate anomalies in fewer steps | n_estimators, contamination | Unsupervised anomaly scores at scale | Threshold needs labels or an alert budget |
Check yourself 2 questions
Linear regression closed form?
Show answer
(XᵀX)⁻¹Xᵀy.
Key hyperparameter of ridge or lasso?
Show answer
The regularisation strength α.
Takeaway Know how each algorithm learns, its key hyperparameters, strengths and pitfalls.
Boosting libraries compared#
| Library | Distinctive idea | Use when |
|---|---|---|
| XGBoost | Second-order (gradient + Hessian) objective with explicit regularisation; sparsity-aware splits; histogram mode | General default, mature tooling |
| LightGBM | Leaf-wise growth, histogram binning, GOSS sampling and exclusive feature bundling | Large datasets, speed; limit num_leaves and min_data_in_leaf to avoid overfitting |
| CatBoost | Ordered boosting and ordered target statistics for categoricals; symmetric trees | Many high-cardinality categorical features, little tuning time |
Check yourself 2 questions
Which library excels with categorical features?
Show answer
CatBoost.
LightGBM's distinctive growth strategy?
Show answer
Leaf-wise growth with histogram splits.
Takeaway XGBoost is the mature default, LightGBM is fastest on big data, CatBoost handles categoricals best.
Tree split maths#
- Gini and entropy usually pick similar splits; Gini is cheaper (no logarithm).
- Information gain favours many-valued features; gain ratio corrects for it.
- Feature importance from impurity is biased toward high-cardinality features; prefer permutation importance or SHAP.
Check yourself 2 questions
Gini impurity formula?
Show answer
1 − Σ pₖ².
Regression tree split criterion?
Show answer
Largest reduction in variance (MSE).
Takeaway Gini and entropy measure impurity; gain is the impurity drop; regression trees reduce variance.
06Feature engineering, explainability, fairness and privacy
What turns raw data into signal, and how to show a model is understandable, fair and safe with personal data.
Feature engineering playbook#
| Data type | Techniques | Pitfall |
|---|---|---|
| Numeric | Standardise for linear models and neural nets; log or Box-Cox for skew; clip outliers; bin for monotone effects | Fitting the scaler on all data leaks test statistics |
| Categorical (low cardinality) | One-hot; ordinal only if order is real | Unseen categories at serving: handle_unknown or an "other" bucket |
| Categorical (high cardinality) | Target encoding (out-of-fold, smoothed), frequency encoding, hashing trick, learned embeddings | In-fold target encoding leaks the label |
| Date and time | Hour, weekday, holidays; cyclical sin/cos; time since last event; lags and rolling windows | Rolling features must use only past data (point-in-time) |
| Text | TF-IDF, n-grams, pretrained embeddings, length and keyword flags | Vocabulary fitted on the full corpus leaks |
| Aggregates and interactions | Per-user and per-item counts, rates and recency; feature crosses | Aggregates computed after the prediction time |
| Missing values | Impute (median, mode, model) plus a missing-indicator column; trees can handle NaN natively | Missingness itself can be predictive; don't drop it blindly |
| Feature selection | Filter (mutual information, correlation), wrapper (recursive elimination), embedded (L1, tree importance), permutation importance on validation | Selecting features on the full dataset before CV inflates scores |
Check yourself 2 questions
Pitfall when scaling numeric features?
Show answer
Fitting the scaler on all data leaks test information.
Which models need standardised inputs?
Show answer
Linear models and neural nets.
Takeaway Each data type has standard techniques and a classic leakage pitfall.
Explainability#
| Method | Scope | Note |
|---|---|---|
| Coefficients | Global | Only comparable on scaled features; unstable with collinearity |
| Permutation importance | Global | Model-agnostic; correlated features share and hide importance |
| SHAP | Local and global | Additive attributions with game-theory guarantees; TreeSHAP is exact and fast for tree models |
| LIME | Local | Fits a simple surrogate around one prediction; results vary between runs |
| Partial dependence / ICE | Global / per-instance | Shows how predictions change with one feature; misleading when features correlate |
| Counterfactuals | Local | "What would need to change for approval?"; good for user-facing explanations |
Check yourself 2 questions
Weakness of permutation importance?
Show answer
Correlated features share and hide importance.
Local versus global: what does SHAP give?
Show answer
Both: per-prediction attributions that aggregate globally.
Takeaway Coefficients, permutation importance, SHAP and partial dependence each have scope and caveats.
Fairness#
- Demographic parity: equal positive rates across groups.
- Equal opportunity: equal true-positive rates. Equalised odds: equal TPR and FPR.
- Predictive parity / calibration within groups: a score means the same probability for every group.
- Impossibility: when base rates differ, calibration and equalised odds can't both hold; choose with stakeholders.
- Bias sources: sampling, historical labels, measurement, proxies for protected attributes.
- Mitigation: pre-processing (reweighing, resampling), in-processing (fairness constraints, adversarial debiasing), post-processing (group-specific thresholds).
- Process: slice metrics by group, model cards, human review of high-impact decisions.
Check yourself 2 questions
Equal opportunity means?
Show answer
Equal true-positive rates across groups.
Can all fairness criteria be satisfied together?
Show answer
Generally no; they conflict when base rates differ.
Takeaway Demographic parity, equal opportunity, equalised odds and calibration can't all hold at once.
Privacy in ML#
| Technique or risk | What it is | Trade-off |
|---|---|---|
| Differential privacy | Add calibrated noise so one person's data barely changes the output; DP-SGD clips per-example gradients and adds noise | Privacy budget ε vs accuracy |
| Federated learning | Train on devices, send only model updates (FedAvg), combine with secure aggregation | Non-IID data, communication cost, updates can still leak without DP |
| PII handling | Minimise, pseudonymise, redact from logs and prompts, encrypt at rest | Less data for debugging |
| Membership inference | Attacker tests whether a record was in the training set | Overfit models leak more; DP and regularisation help |
| Training-data extraction | LLMs can regurgitate memorised text | Deduplicate training data, filter outputs |
| Right to erasure | Remove a person's data on request | Retraining or machine unlearning is costly; keep data lineage |
Check yourself 2 questions
How does DP-SGD protect privacy?
Show answer
Clips per-example gradients and adds noise.
What's membership inference?
Show answer
Inferring whether a record was in the training data.
Takeaway Differential privacy, federated learning and attack risks such as membership inference trade privacy against accuracy.
07Data-centric ML: labels, augmentation, anomalies, time series
Most production gains come from better data rather than bigger models.
Labels with less effort#
| Approach | Idea |
|---|---|
| Labelling guidelines + agreement | Clear rules with examples; measure inter-annotator agreement (Cohen's κ) and resolve disagreements |
| Active learning | Label the examples the model is least sure about (uncertainty sampling, query by committee) |
| Weak supervision | Combine noisy labelling functions (rules, heuristics) into probabilistic labels |
| Semi-supervised | Pseudo-label confident unlabelled data; consistency regularisation (FixMatch) |
| Self-supervised pretraining | Learn representations from unlabelled data, then fine-tune on few labels |
| LLM-assisted labelling | Use an LLM as a first-pass labeller, audit samples with humans |
| Noisy labels | Find likely mislabels with confident learning or loss-based filtering |
Check yourself 2 questions
What does active learning label?
Show answer
The examples the model is most uncertain about.
How is annotator agreement measured?
Show answer
Cohen's κ.
Takeaway Guidelines with agreement checks, active learning, weak supervision and pseudo-labelling cut labelling cost.
Data augmentation#
| Modality | Augmentations |
|---|---|
| Images | Flips, crops, colour jitter, RandAugment, mixup, cutmix |
| Text | Back-translation, synonym swaps, paraphrasing with an LLM |
| Audio | SpecAugment masks, background noise, speed and pitch shifts |
| Tabular | SMOTE or noise for the minority class (inside CV folds only) |
| Time series | Window slicing, jitter, scaling, time warping |
Check yourself 2 questions
Text augmentation via translation?
Show answer
Back-translation.
Name an image augmentation that mixes examples.
Show answer
Mixup or CutMix.
Takeaway Flips and mixup for images, back-translation for text, SpecAugment for audio.
Anomaly detection#
- Statistical: z-score, IQR, seasonal decomposition residuals; good first line.
- Distance and density: k-NN distance, local outlier factor.
- Isolation forest: anomalies are isolated with fewer random splits.
- Reconstruction: autoencoders flag inputs they reconstruct badly.
- Forecast residuals: for metrics, alert when actuals leave the prediction interval.
- Evaluation: labels are rare; use precision@k and set the threshold from an alert budget analysts can handle.
Check yourself 2 questions
Why do isolation forests work?
Show answer
Anomalies are isolated with fewer random splits.
Good first line of anomaly detection?
Show answer
Statistical: z-score, IQR, seasonal residuals.
Takeaway Start statistical, then distance, density, isolation forest or autoencoders; labels are scarce, so evaluate carefully.
Time-series forecasting in depth#
| Topic | Key points |
|---|---|
| Baselines | Last value, seasonal naive; anything fancier must beat them |
| Statistical | ARIMA/SARIMA, exponential smoothing (ETS), Prophet for trend + seasonality + holidays |
| ML on features | Gradient boosting on lags, rolling stats, calendar features; one model across many series |
| Deep and foundation | DeepAR (probabilistic), N-BEATS, Temporal Fusion Transformer, pretrained models (Chronos, TimesFM) |
| Metrics | MAE, RMSE; scale-free MASE or WAPE across series; quantile loss for intervals |
| Validation | Rolling-origin backtests with a gap equal to the forecast horizon |
| Hierarchies | Forecast at several levels (store, region) and reconcile so they add up |
Check yourself 2 questions
Baselines every forecast must beat?
Show answer
Last value and seasonal naive.
What does Prophet model?
Show answer
Trend, seasonality and holidays.
Takeaway Beat naive baselines first; statistical models, tree models with lags, deep models and foundation models follow.
08Deep learning, architectures, generative models
Ml-overview/19-revision-guide/05,06,08; practical ml/pytorch_cheatsheet.md
Deep learning core#
| Topic | Remember |
|---|---|
| Backprop | dL/dW = xᵀδ; sigmoid′ ≤ 0.25 → vanishing |
| Residuals | H(x)=F(x)+x gives a +1 gradient path |
| Exploding | clip by norm (1.0) |
| Init | He 2/n_in (ReLU), Xavier (tanh), GPT std 0.02, residual 1/√(2L), LSTM forget bias 1 |
| Activations | ReLU (dying), GELU, SiLU, SwiGLU in LLM FFN |
| Loss | CE, focal (imbalance), label smoothing, InfoNCE, triplet, Huber |
| Optimisers | SGD+momentum, Adam, AdamW (decoupled WD), Lion |
| LR | warmup + cosine; OneCycle; grad accumulation |
| Norm | BatchNorm (CNN), LayerNorm / RMSNorm (Transformers), pre-norm stable |
| Mixed precision | bf16 no scaler; fp16 needs GradScaler |
| Memory | gradient checkpointing trades compute for memory |
Check yourself 2 questions
Why do residual connections help?
Show answer
They give a +1 gradient path through the identity.
Initialisation for ReLU networks?
Show answer
He initialisation (variance 2/n_in).
Takeaway Backprop, residuals, gradient clipping and proper initialisation keep deep nets trainable.
Architectures#
| Arch | Key idea |
|---|---|
| CNN | locality + weight sharing; ResNet skips; EfficientNet scaling |
| RNN / LSTM / GRU | gates; cell state = gradient highway |
| Attention | softmax(QKᵀ/√d_k)V; √d_k keeps softmax unsaturated |
| Transformer | attn + FFN + residual + norm; enc (BERT), dec (GPT), enc-dec (T5) |
| Positional | sinusoidal, learned, RoPE, ALiBi |
| MHA → GQA → MQA | fewer KV heads → smaller KV cache |
| FlashAttention | IO-aware tiling, online softmax; exact |
| MoE | router top-k experts; load-balancing loss |
| Mamba / SSM | linear-time selective state |
| GNN | message passing uses relational structure; check neighbor leakage and compare to simpler baselines |
| Self-supervised / contrastive | learn reusable representations from unlabeled data; measure transfer on held-out tasks |
| Multimodal | encoders + fusion/cross-attention; align modalities and score each modality slice |
| Scaling laws | Chinchilla is a classic compute-optimal heuristic (~20 training tokens/parameter in its setup), not a universal recipe; re-estimate for data quality, objective, and inference goals. Paper |
Check yourself 2 questions
Why divide attention scores by √d_k?
Show answer
To keep softmax from saturating.
What does an LSTM's cell state provide?
Show answer
A gradient highway across time.
Takeaway CNNs exploit locality, RNN gates carry state, attention mixes all positions, transformers scale.
PyTorch loop (your template)#
model.to(device) for epoch in range(E): model.train() for xb,yb in train_loader: xb,yb = xb.to(device), yb.to(device) optimizer.zero_grad() loss = criterion(model(xb), yb) loss.backward() clip_grad_norm_(model.parameters(), 1.0) optimizer.step(); scheduler.step() model.eval() with torch.no_grad(): ... # val loop
NaN / exploding debug
torch.autograd.set_detect_anomaly(True)(dev only)torch.isnan(loss).any(); print per-layerp.grad.norm()- Clip grads; lower LR; check inputs/labels; bf16 over fp16
- Transfer learning: freeze backbone → partial unfreeze → discriminative LRs
Check yourself 2 questions
Order of calls in a training step?
Show answer
zero_grad, forward, loss, backward, step.
What do you set for validation?
Show answer
model.eval() and torch.no_grad().
Takeaway train(), zero_grad, forward, loss, backward, step; eval() with no_grad for validation.
Generative models#
| Family | Key |
|---|---|
| Autoencoder | bottleneck; denoising / sparse variants |
| VAE | ELBO = recon − KL; reparam z = μ + εσ; posterior collapse; β-VAE |
| GAN | min_G max_D; mode collapse; WGAN-GP; 1-step sampling |
| Diffusion | predict noise (L_simple); stable regression training |
| DDPM / DDIM | stochastic T steps / deterministic fewer steps |
| CFG | guidance scale = fidelity ↔ diversity dial |
| Latent diffusion | diffuse in VAE latent (Stable Diffusion) |
| Flows | exact likelihood; coupling layers (RealNVP) |
| Flow matching | regress velocity; rectified flow (SD3, FLUX) |
| Consistency | 1–4 step sampling via distillation |
Check yourself 2 questions
VAE objective?
Show answer
ELBO = reconstruction − KL.
Classic GAN failure mode?
Show answer
Mode collapse.
Takeaway Autoencoders, VAEs, GANs, flows, diffusion and autoregressive models trade quality, speed and stability.
Training troubleshooting#
| Symptom | Likely causes | Fixes |
|---|---|---|
| Loss doesn't decrease | Learning rate too low or high, bug in labels or loss, frozen layers | Overfit one small batch first; LR range test; check label alignment |
| Loss becomes NaN | Exploding gradients, log(0), fp16 overflow, bad input values | Gradient clipping, lower LR, bf16, epsilon in logs, validate inputs |
| Train good, validation bad | Overfitting, leakage in train only, distribution shift | More data or augmentation, regularisation, early stopping; recheck the split |
| Both train and validation bad | Underfitting, weak features, too much regularisation | Bigger model, train longer, better features, less dropout |
| Validation better than train | Dropout and augmentation only active in training, easy validation set | Usually fine; confirm the validation set is representative |
| Sudden loss spikes | Bad batches, LR too high late in training, instability at scale | Warmup, lower peak LR, skip bad batches, check data |
| GPU out of memory | Batch or sequence too large, activations stored | Smaller micro-batch + gradient accumulation, checkpointing, mixed precision |
| GPU underutilised | Data loading bottleneck, small batches, CPU preprocessing | More loader workers, pinned memory, prefetching, larger batches |
| Great offline, poor online | Training–serving skew, stale features, feedback loops | Shared feature code, log served features, shadow tests |
Check yourself 2 questions
First debugging step when loss won't decrease?
Show answer
Overfit one small batch.
Loss suddenly becomes NaN: likely causes?
Show answer
Too high LR, exploding gradients, bad inputs or log(0).
Takeaway Overfit one batch first; check LR, labels, normalisation and leakage when training misbehaves.
09Applied ML domains
Domain-specific models and metrics that come up in ML engineer loops: recommendations, search, NLP, vision, speech, reinforcement learning.
Recommender systems#
| Stage / topic | Key ideas |
|---|---|
| Funnel | Candidate generation (1000s) → ranking (100s) → re-ranking (diversity, business rules) |
| Collaborative filtering | User–item matrix; item-item similarity; matrix factorisation (ALS, SGD) |
| Two-tower retrieval | User and item encoders; dot product; ANN index; in-batch negatives |
| Ranking models | GBDT, Wide & Deep, DLRM, DCN-v2, DIN (attention over history), multi-task (click + watch time) |
| Cold start | Content features, popularity priors, onboarding questions, exploration |
| Feedback loops | Position and popularity bias; log propensities; exploration traffic |
| Metrics | Offline: Recall@k, NDCG, AUC, calibration. Online: CTR, dwell, retention, diversity |
Check yourself 2 questions
Three stages of the recommendation funnel?
Show answer
Candidate generation, ranking, re-ranking.
Cold-start fix?
Show answer
Content features, popularity or exploration.
Takeaway Candidate generation, ranking, re-ranking; collaborative filtering, two-towers and sequence models.
Search and learning to rank#
| Topic | Key ideas |
|---|---|
| Lexical retrieval | TF-IDF, BM25 (term saturation k₁, length norm b) |
| Semantic retrieval | Bi-encoders + ANN; hybrid with BM25 via reciprocal rank fusion |
| Re-ranking | Cross-encoders, LLM rerankers on top-k |
| Learning to rank | Pointwise (regression), pairwise (RankNet), listwise (LambdaMART, ListNet) |
| Labels | Human graded relevance, clicks with position-bias correction |
| Query understanding | Spell correction, expansion, intent classification, entity linking |
Check yourself 2 questions
BM25's two key parameters?
Show answer
k₁ (term saturation) and b (length normalisation).
How are lexical and semantic results combined?
Show answer
Reciprocal rank fusion.
Takeaway BM25 plus dense retrieval, fused with RRF, then cross-encoder re-ranking and LTR.
NLP#
| Task | Approach |
|---|---|
| Text representation | Bag of words/TF-IDF → word2vec/GloVe → contextual (BERT) → LLM embeddings |
| Classification | TF-IDF + LR baseline; fine-tuned encoder; LLM zero/few-shot |
| NER / sequence labelling | BIO tags; BiLSTM-CRF → BERT token classification |
| Summarisation, translation | Encoder-decoder (T5, BART) or decoder LLMs; ROUGE/COMET + human eval |
| Question answering | Extractive (span prediction) vs generative + RAG |
| Tokenisation | BPE, WordPiece, Unigram/SentencePiece; byte-level avoids unknown tokens |
Check yourself 2 questions
Strong text classification baseline?
Show answer
TF-IDF + logistic regression.
What made embeddings contextual?
Show answer
Transformer encoders such as BERT.
Takeaway From bag of words to contextual embeddings and LLMs; TF-IDF plus LR remains a strong baseline.
Computer vision#
| Task | Models / metrics |
|---|---|
| Classification | ResNet, EfficientNet, ConvNeXt, ViT; top-1/top-5 accuracy |
| Detection | Faster R-CNN (two-stage), YOLO / SSD (one-stage), DETR; mAP@IoU, NMS |
| Segmentation | U-Net, Mask R-CNN, SAM (promptable); IoU, Dice |
| Vision-language | CLIP (contrastive image-text), VLMs (image encoder → projector → LLM) |
| Generation | Latent diffusion, DiT; FID, CLIP score |
| Practical | Augmentation (flip, crop, mixup, cutmix), transfer learning, class imbalance |
Check yourself 2 questions
One-stage versus two-stage detectors?
Show answer
YOLO/SSD (one-stage) versus Faster R-CNN (two-stage).
Detection metric?
Show answer
mAP at IoU thresholds.
Takeaway Classification, detection, segmentation and their models and metrics: top-k accuracy, mAP and IoU.
Speech and multimodal#
- ASR: CTC, RNN-T, attention encoder-decoder (Whisper); WER.
- TTS: text → mel spectrogram → vocoder; neural codec models; MOS.
- Voice agents: streaming ASR → LLM → streaming TTS, or native speech-to-speech; latency budget < ~800 ms; barge-in handling.
- Multimodal fusion: early (concat inputs), late (combine predictions), cross-attention.
Check yourself 2 questions
ASR metric?
Show answer
Word error rate (WER).
Cascaded voice agent pipeline?
Show answer
Streaming ASR → LLM → streaming TTS.
Takeaway ASR with CTC or encoder-decoder, TTS via spectrogram and vocoder, voice agents chaining or natively multimodal.
Reinforcement learning and bandits#
| Concept | Key idea |
|---|---|
| MDP | States, actions, transitions, rewards, discount γ |
| Bellman equation | V(s) = maxₐ [R + γ Σ P(s'|s,a) V(s')] |
| Q-learning / DQN | Off-policy TD; replay buffer + target network |
| Policy gradient | REINFORCE: ∇J = E[∇log π(a|s) · G]; high variance → baseline |
| Actor-critic, PPO | Advantage estimates; PPO clips the policy ratio for stable updates |
| Bandits | ε-greedy, UCB, Thompson sampling; contextual bandits for ads, recs |
| Offline RL / OPE | Learn from logs; importance sampling, doubly robust estimators |
Check yourself 2 questions
What do DQN's replay buffer and target network do?
Show answer
Stabilise off-policy TD learning.
Bandit algorithms balance what?
Show answer
Exploration and exploitation.
Takeaway MDPs, Bellman equations, Q-learning, policy gradients and bandits trade exploration and exploitation.
Recommendation funnel#
flowchart LR
A[("Millions of items")] --> CG["Candidate generation<br/>two-tower ANN · co-visitation · popular"]
CG -->|"~1,000"| RK["Ranking<br/>DNN or GBDT, multi-task"]
RK -->|"~100"| RR["Re-ranking<br/>diversity · freshness · rules"]
RR -->|"~20"| UI["Feed shown to user"]
UI -.->|"clicks, watch time"| LOG[("Logs to training data")]
LOG -.-> CG
LOG -.-> RKCheck yourself 2 questions
What does candidate generation use?
Show answer
Two-tower ANN, co-visitation or popularity.
What happens at re-ranking?
Show answer
Diversity and business rules applied to the final slate.
Takeaway Millions of items narrow to about 1,000 candidates, about 100 ranked, then a re-ranked slate.
10Transformer and LLM internals
Architecture choices inside modern LLMs, decoding, long context and reasoning models.
Decoder block, end to end#
- Tokenise (BPE) → token IDs → embedding lookup (d_model).
- Pre-norm (RMSNorm) → masked self-attention with RoPE on Q and K.
- Residual add → pre-norm → FFN (SwiGLU, ~2.7–4× d_model hidden) or MoE layer.
- Residual add; repeat L layers.
- Final norm → LM head (often tied to embeddings) → logits → softmax → sample.
Check yourself 2 questions
Where is RoPE applied?
Show answer
To Q and K inside attention.
FFN width relative to d_model?
Show answer
About 2.7–4×.
Takeaway Tokenise, embed, pre-norm, masked attention with RoPE, residual, pre-norm, SwiGLU FFN, residual; repeat; final norm and LM head.
Architecture choices#
| Choice | Options and why |
|---|---|
| Attention heads | MHA → GQA (shared K/V per group) → MQA (one K/V); MLA compresses KV into a latent (DeepSeek) |
| Positions | Absolute learned/sinusoidal → RoPE (relative, rotates Q/K) → ALiBi (linear bias) |
| Long context | RoPE scaling (position interpolation, NTK, YaRN), sliding-window attention, ring/sequence parallel attention |
| Norm | Post-LN (original) → pre-LN (stable deep training) → RMSNorm (cheaper) |
| FFN | ReLU/GELU → SwiGLU (better quality per FLOP) |
| MoE | Router picks top-k experts per token; more parameters at same compute; load-balancing loss, expert parallelism |
| Efficient attention | FlashAttention (exact, IO-aware), linear attention, state-space hybrids (Mamba, Jamba) |
| Encoder vs decoder | Encoder (BERT) for embeddings/classification; decoder (GPT) for generation; enc-dec (T5) for seq2seq |
Check yourself 2 questions
What does GQA do?
Show answer
Shares K/V heads across groups of query heads to shrink the KV cache.
Why mixture of experts?
Show answer
More parameters with only a few experts active per token.
Takeaway GQA or MQA shrink the KV cache, RoPE gives relative positions, MoE scales parameters without scaling compute.
Decoding strategies#
| Method | Behaviour |
|---|---|
| Greedy | Argmax each step; deterministic; can loop |
| Beam search | Keep top-B sequences; good for translation, bland for chat |
| Temperature | Divide logits by T; T<1 sharper, T>1 more random |
| Top-k | Sample among k most likely tokens |
| Top-p (nucleus) | Smallest set with cumulative prob ≥ p |
| Min-p | Keep tokens ≥ min_p × top prob; adapts to confidence |
| Repetition / frequency penalty | Down-weight already used tokens |
| Constrained / structured | Grammar or JSON-schema masks logits; guarantees valid output |
| Speculative decoding | Draft model proposes, target verifies in one pass; same output distribution |
Check yourself 2 questions
Temperature below 1 does what?
Show answer
Sharpens the distribution: more deterministic.
Top-p sampling?
Show answer
Sample from the smallest set of tokens whose probabilities sum to p.
Takeaway Greedy and beam are deterministic; temperature, top-k and top-p sample with controlled randomness.
Tokenisation details#
- BPE: start from bytes/chars, repeatedly merge the most frequent pair.
- WordPiece: merge by likelihood gain (BERT). Unigram: prune a large vocab by likelihood (SentencePiece).
- Vocab size trade-off: bigger vocab → shorter sequences, larger embedding table (32K–256K typical).
- Failure modes: digit splitting hurts arithmetic, non-English text costs more tokens, glitch tokens.
- Special tokens: BOS/EOS, chat-template role markers, tool-call delimiters.
Check yourself 2 questions
How does BPE build its vocabulary?
Show answer
By repeatedly merging the most frequent pair.
Which tokeniser does BERT use?
Show answer
WordPiece.
Takeaway BPE merges frequent pairs, WordPiece merges by likelihood, Unigram prunes a large vocab.
Reasoning models and test-time compute#
| Technique | Idea |
|---|---|
| Chain-of-thought | Generate intermediate steps before the answer; more tokens = more compute per problem |
| Self-consistency / best-of-N | Sample many solutions; majority vote or pick with a verifier |
| Process vs outcome reward models | Score each step vs only the final answer |
| RL with verifiable rewards (RLVR) | Reward from unit tests or exact-match maths answers; trains long reasoning |
| GRPO | PPO variant without a value network: advantages relative to a group of samples for the same prompt |
| Search at inference | Tree search / MCTS over reasoning steps with a verifier |
| Thinking budgets | Cap or scale reasoning tokens per request; trade latency and cost for accuracy |
| Distilling reasoning | Fine-tune small models on long reasoning traces from a strong model |
Check yourself 2 questions
Self-consistency?
Show answer
Sample many solutions and take the majority answer.
How does chain of thought add compute?
Show answer
It generates intermediate steps before answering.
Takeaway Chain of thought, self-consistency, search and RL-trained reasoning spend more compute at inference for better answers.
Decoder block diagram#
flowchart TD
T["Token IDs"] --> E["Embedding"]
E --> N1["RMSNorm"]
N1 --> AT["Masked self-attention<br/>RoPE · GQA · KV cache"]
AT --> R1(("+"))
E --> R1
R1 --> N2["RMSNorm"]
N2 --> FF["SwiGLU FFN or MoE"]
FF --> R2(("+"))
R1 --> R2
R2 -->|"repeat for L layers"| NF["Final norm"]
NF --> H["LM head, softmax, sample"]Check yourself 2 questions
What does the KV cache store?
Show answer
Keys and values of past tokens for fast decoding.
Pre-norm or post-norm in modern decoders?
Show answer
Pre-norm.
Takeaway Embedding, RMSNorm, masked attention with RoPE, GQA and KV cache, residual, RMSNorm, SwiGLU, residual.
11LLMs: training, prompting, agents, RAG
Ml-overview/19-revision-guide/10-llms, 11-llm-applications; LLM-System-Design/chapters-md/00-Reference-Guides/cheat-sheet.md
LLM lifecycle#
flowchart LR P[Pretrain: next-token on trillions of tokens] --> S[SFT: instruction pairs] S --> A[Align: RLHF / DPO] A --> E[Eval + red team] E --> Q[Quantise / distil] Q --> D[Serve: vLLM, TRT-LLM] D --> M[Monitor + feedback] M --> S
Check yourself 2 questions
What follows SFT?
Show answer
Alignment: RLHF or DPO.
Name a serving engine.
Show answer
vLLM (or TGI, TensorRT-LLM).
Takeaway Pretrain, SFT, align, evaluate and red-team, quantise or distil, then serve.
Training & alignment#
| Method | When / note |
|---|---|
| Pretraining | next-token objective; curate/deduplicate data, tokenize and pack sequences, track contamination |
| SFT | instruction/task behavior; quality and coverage matter more than a universal example count |
| LoRA / QLoRA | low-rank adapters; QLoRA = 4-bit base + LoRA |
| RLHF | reward model + PPO; frontier exploration; costly |
| DPO | preference pairs, no RM; cheaper & stable |
| RLAIF / Constitutional | AI feedback against principles |
| Distillation | big teacher → small student (Phi story) |
| Evaluation gates | held-out task suite, safety/red-team, human review; prevent train/test contamination |
| Synthetic data | Self-Instruct, rejection sampling, exec-verified code; audit quality and distribution shift |
Check yourself 2 questions
DPO versus RLHF?
Show answer
DPO optimises preferences directly without a reward model or RL loop.
What matters most in SFT data?
Show answer
Quality and coverage.
Takeaway Pretraining for knowledge, SFT for behaviour, preference optimisation for alignment.
Prompting & agents#
| Technique | Idea |
|---|---|
| CoT | think step by step; self-consistency = vote over samples |
| ReAct | Thought → Action → Observation loop |
| Reflection | self-critique and retry |
| Tree of Thought | search over reasoning branches |
| Tool use | JSON schema; validate args; timeouts |
| Memory | in-context, short-term store, long-term semantic, structured state |
| Multi-agent | orchestrator + workers, supervisor, debate, routing |
| Failure modes | hallucinated calls, wrong args, cascades, infinite loops → budgets, HITL |
| DSPy | optimise prompts (BootstrapFewShot, MIPRO) |
Check yourself 2 questions
ReAct loop?
Show answer
Thought → Action → Observation.
What does reflection add?
Show answer
Self-critique and retry.
Takeaway CoT, self-consistency, ReAct, reflection and tree of thought structure reasoning and tool use.
RAG#
| Stage | Choices |
|---|---|
| Chunking | 200–500 tokens, 15–25% overlap; semantic / structure-aware |
| Embedding | 768/1536 dims; 1536×4B ≈ 6 KB; 1M vectors ≈ 6 GB RAM |
| Retrieval | dense + BM25 hybrid, RRF k=60 |
| ANN index | HNSW (recall, RAM), IVF / IVF-PQ (compressed) |
| Query | multi-query, HyDE, step-back |
| Rerank | cross-encoder on top-k (precision) |
| Context | lost-in-the-middle → best chunks at edges |
| Advanced | Self-RAG, CRAG, GraphRAG |
| Eval | RAGAS: faithfulness, answer relevance, context precision/recall |
Check yourself 2 questions
Typical chunk size and overlap?
Show answer
200–500 tokens with 15–25% overlap.
Memory for 1M 1536-dim float32 vectors?
Show answer
About 6 GB.
Takeaway Chunking, embeddings, hybrid retrieval with RRF, re-ranking, context building and grounded generation.
RAG pipeline#
flowchart LR Q[Query] --> R[Rewrite / HyDE] R --> H[Hybrid: BM25 + vector] H --> F[RRF fusion] F --> X[Cross-encoder rerank] X --> C[Context build] C --> L[LLM] L --> G[Guardrails + citations]
Check yourself 2 questions
What is HyDE?
Show answer
Generating a hypothetical answer to embed for retrieval.
What re-ranks fused results?
Show answer
A cross-encoder.
Takeaway Query rewrite, hybrid retrieval, RRF fusion, cross-encoder re-rank, context, LLM, guardrails and citations.
Architecture decision#
flowchart TD
S[Problem] --> F{{Needs private data?}}
F -->|yes| RAG[RAG]
F -->|no| Fm{{Needs strict format?}}
Fm -->|yes| D{{1000+ examples?}}
Fm -->|no| P[Few-shot prompting]
D -->|yes| FT[LoRA fine-tune]
D -->|no| P
RAG --> A{{Needs tools / APIs?}}
FT --> A
P --> A
A -->|yes| AG[Agentic workflow]
A -->|no| SV[Direct serving]
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class F,Fm,D,A decCheck yourself 2 questions
Needs private data: first choice?
Show answer
RAG.
Strict format with fewer than 1000 examples?
Show answer
Few-shot prompting or structured output.
Takeaway Private data → RAG; strict format with 1000+ examples → fine-tune; otherwise few-shot prompting.
Hallucination stack#
- Causes: teacher forcing, rare facts, RLHF sycophancy
- Detect: self-consistency, SelfCheckGPT, NLI checks, FActScore
- Mitigate: RAG grounding, "say I don't know", constrained decoding, calibration, factuality FT
- Benchmarks: TruthfulQA, HaluEval, FELM
- LLM-as-judge biases: position, verbosity, self-preference
- Grounding checks: extract claims and test each against the retrieved passages (NLI); cite the supporting span.
- Abstain policy: gate on retrieval score or model confidence, then say "I don't know" or escalate.
- Decoding: lower temperature for factual tasks; schema-constrained output for tool calls.
- Monitoring: sample production answers for human factuality review and track the unsupported-claim rate.
- Product: show sources so users can verify, and say what the system cannot know (cut-off, private data).
A guarded answer pipeline
- Retrieve, and stop early if nothing relevant scores above the threshold.
- Generate with an instruction to cite a passage for every claim.
- Verify each cited claim against its passage; drop or flag unsupported ones.
- Answer with citations, or abstain and hand off.
Check yourself 2 questions
Name a detection method.
Show answer
Any of: self-consistency, SelfCheckGPT, NLI checks, FActScore.
Name a mitigation.
Show answer
Any of: RAG grounding, allowing 'I don't know', constrained decoding, citations.
Takeaway Hallucinations come from training and incentives; detect with consistency and NLI, mitigate with grounding and abstention.
Embeddings and vector search internals#
| Index | How it works | Tuning knobs | Trade-off |
|---|---|---|---|
| Flat (exact) | Compare against every vector | — | Perfect recall; fine up to ~100K vectors |
| IVF | Cluster vectors (k-means); search only the nearest clusters | nlist (clusters), nprobe (clusters searched) | Higher nprobe = better recall, slower |
| PQ / IVF-PQ | Split vectors into m sub-vectors and quantise each to a codebook | m, bits per code | 10–50× less memory, some recall loss; rerank with full vectors |
| HNSW | Layered proximity graph navigated greedily from the top layer | M (links), efConstruction, efSearch | Best recall/latency; high memory; deletes are awkward |
| DiskANN / ScaNN | SSD-resident graphs / anisotropic quantisation | Beam width, leaves searched | Billion-scale on modest hardware |
- Similarity: normalise vectors and cosine equals dot product; use the metric the embedding model was trained with.
- Memory: 1M × 768 dims × 4 bytes ≈ 3 GB before index overhead; float16 or int8 halves or quarters it.
- Filtering: pre-filter by metadata (tenant, permissions) inside the index; post-filtering can return too few results.
- Evaluate: recall@k against exact search on a sample, then tune for p95 latency.
- Model changes: a new embedding model means re-embedding everything; version your indexes.
Check yourself 2 questions
Up to roughly what size is flat search fine?
Show answer
About 100K vectors.
What does product quantisation trade?
Show answer
Memory for some recall.
Takeaway Flat search is exact, IVF clusters, HNSW graphs give fast approximate search, PQ compresses.
12LLM training at scale, fine-tuning and alignment
How models are trained across many GPUs, how to adapt them cheaply, and the preference-optimisation family.
Distributed training#
| Technique | Splits | Note |
|---|---|---|
| Data parallel (DDP) | Batch | Full model copy per GPU; all-reduce gradients |
| ZeRO-1 / 2 / 3, FSDP | Optimizer states / + gradients / + parameters | Memory scales down with GPU count; more communication |
| Tensor parallel | Each matrix across GPUs | Needs NVLink; within a node |
| Pipeline parallel | Layers across GPUs | Micro-batches to fill bubbles |
| Sequence / context parallel | Sequence length | Long-context training |
| Expert parallel | MoE experts | All-to-all token routing |
| Activation checkpointing | — | Recompute activations in backward; ~30% more compute |
| Mixed precision | — | bf16 compute, fp32 master weights; fp8 on Hopper+ |
Check yourself 2 questions
What does ZeRO-3 / FSDP shard?
Show answer
Optimiser states, gradients and parameters.
What does DDP all-reduce?
Show answer
Gradients.
Takeaway Data parallel copies the model, ZeRO/FSDP shard optimiser state, gradients and parameters, tensor and pipeline parallel split the model.
Parameter-efficient fine-tuning#
| Method | How | Note |
|---|---|---|
| LoRA | W' = W + (α/r)·BA, B∈ℝ^{d×r}, A∈ℝ^{r×k} | r 8–64; train ~0.1–1% params; merge for zero overhead |
| QLoRA | 4-bit NF4 frozen base + LoRA; double quantisation; paged optimisers | Fine-tune 70B on one 48–80 GB GPU |
| DoRA | Split weight into magnitude and direction; LoRA on direction | Closer to full fine-tune quality |
| Adapters | Small bottleneck layers inserted | Slight inference latency |
| Prefix / prompt tuning | Learned virtual tokens | Tiny; weaker on small models |
| Full fine-tune | All weights | Best ceiling; catastrophic forgetting risk; most memory |
Check yourself 2 questions
LoRA weight update?
Show answer
W' = W + (α/r)·BA with low-rank B and A.
What does QLoRA add?
Show answer
A 4-bit NF4 frozen base, double quantisation and paged optimisers.
Takeaway LoRA trains low-rank adapters (about 0.1–1% of params); QLoRA does it on a 4-bit frozen base.
Preference optimisation family#
| Method | Needs | Idea |
|---|---|---|
| RLHF (PPO) | Reward model + value model + reference | Maximise reward − β·KL(policy ∥ reference) |
| DPO | Chosen/rejected pairs | Closed-form: increase log-ratio of chosen over rejected vs reference |
| IPO / SimPO / ORPO | Pairs | Regularised or reference-free DPO variants; ORPO merges SFT + preference |
| KTO | Single thumbs up/down labels | Prospect-theory loss; no pairs needed |
| GRPO / RLVR | Verifiable reward function | Group-relative advantages; reasoning and code |
| RLAIF / Constitutional AI | Principles + AI judge | AI-generated preference labels |
Check yourself 2 questions
What does RLHF need beyond preference data?
Show answer
A reward model, a value model and a reference policy.
What does DPO need?
Show answer
Chosen and rejected pairs only.
Takeaway RLHF uses a reward model and PPO with a KL penalty; DPO and relatives optimise preference pairs directly.
Fine-tuning decision guide#
- Prompting first, then RAG for knowledge, then fine-tuning for behaviour, style, format, latency or cost.
- Fine-tuning does not reliably add new facts; it changes how the model responds.
- Data quality beats volume: a few thousand clean examples often suffice for SFT.
- Hold out an eval set before training; watch for regressions on general skills.
- Distil: use a large model to label data, fine-tune a small model to cut serving cost.
- Track: training loss, eval loss, task metric, and a safety/regression suite.
Check yourself 2 questions
Does fine-tuning reliably add new facts?
Show answer
No; it changes how the model responds.
What should you try before fine-tuning?
Show answer
Prompting, then RAG.
Takeaway Prompting first, RAG for knowledge, fine-tuning for behaviour, style, format, latency or cost.
How a chat model is built#
flowchart LR
D[("Web, code, books")] --> PT["Pretraining<br/>next-token prediction"]
PT --> B["Base model"]
B --> SFT["SFT<br/>instruction following"]
SFT --> PO["Preference tuning<br/>RLHF · DPO"]
PO --> RL["RL on verifiable tasks<br/>GRPO · RLVR"]
RL --> E["Evals and red-teaming"]
E --> R["Release"]Check yourself 2 questions
What does pretraining optimise?
Show answer
Next-token prediction on huge text corpora.
What turns a base model into an instruction follower?
Show answer
SFT.
Takeaway Pretraining makes a base model, SFT teaches instructions, preference tuning aligns it, then safety and evaluation.
Prompt, RAG or fine-tune?#
Check yourself 2 questions
Missing or changing knowledge?
Show answer
RAG with citations.
Wrong format, tone or behaviour that prompts can't fix?
Show answer
Fine-tune.
Takeaway Prompt problem → better prompts; missing knowledge → RAG; wrong behaviour or format → fine-tune; latency or cost → distil.
13AI agents and AI engineering
Building reliable LLM applications: workflow patterns, tools and MCP, memory, context engineering and frameworks.
Workflows vs agents#
| Pattern | How it works | Use when |
|---|---|---|
| Prompt chaining | Fixed sequence of LLM calls with checks between | Task splits into clear steps |
| Routing | Classify input, send to a specialised prompt/model | Distinct categories; cost tiers |
| Parallelisation | Sectioning (subtasks) or voting (same task N times) | Independent parts; need confidence |
| Orchestrator–workers | LLM plans subtasks dynamically and delegates | Unknown number of steps (multi-file code edits, research) |
| Evaluator–optimiser | Generate → critique → revise loop | Clear quality criteria (translation, code review) |
| Autonomous agent | LLM in a loop choosing tools until done | Open-ended tasks; needs sandboxing, budgets, checkpoints |
Check yourself 2 questions
When is routing appropriate?
Show answer
When inputs fall into distinct categories handled by specialised prompts or models.
When should you prefer a workflow over an agent?
Show answer
When steps are predictable; agents suit open-ended tasks.
Takeaway Chaining, routing, parallelisation and orchestrator-worker are workflows; agents choose their own steps.
Agent anatomy#
- Model: reasoning and tool choice.
- Tools: functions with JSON-schema args; clear names and descriptions; return concise, structured results.
- Memory: working (context window), episodic (past runs), semantic (vector store), procedural (instructions/skills).
- Planning: ReAct (think-act-observe), plan-and-execute, Reflexion (self-critique), tree search.
- Environment: sandboxed code execution, browser, file system, APIs.
- Control: step and token budgets, timeouts, human approval for irreversible actions, checkpoints for resume.
Check yourself 2 questions
What makes a tool easy for a model to use?
Show answer
A clear name and description, JSON-schema args and concise structured results.
Name two memory types.
Show answer
Any two of: working (context), episodic, semantic, procedural.
Takeaway A model, well-described tools, memory, planning and guardrails make an agent.
Model Context Protocol (MCP)#
| Piece | Meaning |
|---|---|
| Host | The AI app (chat client, IDE, agent) that the user runs |
| Client | Connection the host keeps to one server |
| Server | Exposes capabilities from a system (GitHub, DB, files) |
| Tools | Model-invoked actions with input schemas |
| Resources | Readable context (files, records) the app can attach |
| Prompts | Reusable templates the user can pick |
| Transports | stdio (local) and streamable HTTP (remote, OAuth) |
Check yourself 2 questions
What's an MCP server?
Show answer
A process exposing a system's capabilities (tools, resources, prompts).
What's the host?
Show answer
The AI app the user runs: chat client, IDE or agent.
Takeaway MCP connects hosts to servers exposing tools, resources and prompts through a standard client protocol.
Context engineering#
- Treat the context window as a budget: system instructions, tools, retrieved docs, history, scratchpad.
- Put stable content first for prefix caching; volatile content last.
- Retrieve just in time instead of pre-loading everything; return IDs and let the agent fetch details.
- Compact long histories: summarise old turns, drop stale tool outputs.
- Sub-agents with clean contexts for deep subtasks; return condensed results.
- Structured notes / memory files for long-running tasks.
Check yourself 2 questions
Why put stable content first?
Show answer
Prefix caching reuses it across calls.
What competes for the context budget?
Show answer
System instructions, tools, retrieved docs, history and scratchpad.
Takeaway Treat context as a budget: stable content first for caching, retrieve just enough, compact history.
Prompting checklist#
- Role and goal; who the output is for.
- Context and constraints; what "good" looks like.
- Examples (few-shot), varied and representative.
- Output format: schema, XML tags, or JSON mode.
- Let the model reason before answering for hard tasks.
- Tell it what to do when unsure ("say you don't know").
- Version prompts; test them against an eval set like code.
Check yourself 2 questions
How should few-shot examples be chosen?
Show answer
Varied and representative.
How do you pin the output format?
Show answer
A schema, XML tags or JSON mode.
Takeaway Role and goal, context and constraints, varied examples, an explicit output format, and tests.
Frameworks and tooling (know one well)#
| Tool | Strength |
|---|---|
| LangGraph | Stateful graph workflows, checkpoints, human-in-the-loop |
| LlamaIndex | Data connectors, indexing and RAG pipelines |
| DSPy | Programmatic prompts optimised against a metric |
| Provider agent SDKs | Tool loops, handoffs, tracing with less glue code |
| CrewAI / AutoGen | Multi-agent role-play and conversation patterns |
| Pydantic / Instructor | Typed structured outputs with validation and retries |
| Observability | Langfuse, LangSmith, Phoenix, OpenTelemetry GenAI traces |
| Serving | vLLM, SGLang, TensorRT-LLM, TGI, Ollama/llama.cpp (local) |
Check yourself 2 questions
Which framework optimises prompts against a metric?
Show answer
DSPy.
Which offers checkpoints and human-in-the-loop graphs?
Show answer
LangGraph.
Takeaway LangGraph for stateful graphs, LlamaIndex for data and RAG, DSPy for optimised prompts; know one well.
Agent loop#
flowchart TD
U["User goal"] --> M["LLM chooses next step"]
M -->|"tool call"| T["Tool, API or code sandbox"]
T -->|"observation"| M
M -->|"risky action"| H["Human approval"]
H --> M
M <-.->|"read / write"| MEM[("Memory and state")]
M -->|"done or budget hit"| A["Answer with sources"]Guardrails sit on every arrow: validate tool arguments, cap steps and tokens, and treat tool output as data.
Check yourself 2 questions
What should happen before a risky action?
Show answer
Human approval.
What does the agent get back from a tool call?
Show answer
An observation.
Takeaway The LLM picks a step, calls a tool, reads the observation, asks a human for risky actions, and repeats.
14LLM evaluation, safety and security
How to prove an LLM system works, and how it gets attacked.
Evaluation methods#
| Method | Use | Watch out |
|---|---|---|
| Golden test set | Regression gate on every prompt/model change | Keep it fresh; avoid leaking into prompts |
| Reference-based metrics | Exact match, F1, BLEU/ROUGE, unit tests for code | Miss valid paraphrases |
| LLM-as-judge | Scale qualitative grading with a rubric | Position, verbosity, self-preference bias; calibrate with humans |
| Pairwise preference | A vs B comparisons; Elo-style rankings | Needs many comparisons |
| RAG metrics | Context precision/recall, faithfulness, answer relevance | Evaluate retrieval and generation separately |
| Agent metrics | Task success, tool-call accuracy, steps, cost, trajectory review | Non-determinism: run several trials (pass@k, pass^k) |
| Online | Thumbs, edits, escalation rate, A/B tests | Feedback is sparse and biased |
Check yourself 2 questions
What's a golden test set used for?
Show answer
A regression gate on every prompt or model change.
Main risk of LLM-as-judge?
Show answer
Bias, such as favouring length or its own style; calibrate against humans.
Takeaway Golden sets, reference metrics, LLM judges, human review and online signals each catch different failures.
Benchmarks to recognise#
| Area | Benchmarks |
|---|---|
| Knowledge / reasoning | MMLU, MMLU-Pro, GPQA, ARC, HellaSwag, BIG-Bench Hard |
| Maths | GSM8K, MATH, AIME |
| Code | HumanEval, MBPP, LiveCodeBench, SWE-bench (Verified) |
| Agents / tools | τ-bench, GAIA, WebArena, OSWorld, BFCL (function calling) |
| Instruction following / chat | IFEval, MT-Bench, Chatbot Arena, AlpacaEval |
| Long context | Needle-in-a-haystack, RULER, LongBench |
| Truthfulness / safety | TruthfulQA, HaluEval, HarmBench |
Check yourself 2 questions
Name a coding benchmark.
Show answer
Any of: HumanEval, MBPP, LiveCodeBench, SWE-bench.
Name a maths benchmark.
Show answer
Any of: GSM8K, MATH, AIME.
Takeaway MMLU and GPQA for knowledge, GSM8K and MATH for maths, HumanEval and SWE-bench for code.
OWASP Top 10 for LLM applications (2025)#
| # | Risk |
|---|---|
| LLM01 | Prompt injection (direct and indirect via documents, web pages, tool results) |
| LLM02 | Sensitive information disclosure |
| LLM03 | Supply chain (models, datasets, plugins) |
| LLM04 | Data and model poisoning |
| LLM05 | Improper output handling (unsanitised output into SQL, shell, HTML) |
| LLM06 | Excessive agency (too many tools or permissions) |
| LLM07 | System prompt leakage |
| LLM08 | Vector and embedding weaknesses |
| LLM09 | Misinformation (hallucination, overreliance) |
| LLM10 | Unbounded consumption (cost and denial of service) |
Check yourself 2 questions
LLM01?
Show answer
Prompt injection (direct and indirect).
What is indirect prompt injection?
Show answer
Instructions hidden in documents, web pages or tool results the model reads.
Takeaway Prompt injection tops the list, followed by sensitive data disclosure, supply chain and more.
Defence in depth#
- Treat all retrieved and tool content as untrusted data, never instructions.
- Least-privilege tools; read-only by default; human approval for irreversible actions.
- Input and output classifiers (jailbreak, PII, toxicity); allow-lists for URLs and actions.
- Validate and escape model output before it reaches SQL, shells or browsers.
- Sandbox code execution; network egress controls.
- Per-user rate and token limits; spend alerts.
- Red-team before launch; log prompts and tool calls for audit (with PII redaction).
Check yourself 2 questions
How should tool and retrieved content be treated?
Show answer
As untrusted data, never instructions.
Default permission for tools?
Show answer
Read-only, least privilege.
Takeaway Treat retrieved content as data, least-privilege tools, human approval for irreversible actions, and input and output checks.
15LLM inference & serving
digitalocean_inference_prep/01_inference_internals/*, LLM-System-Design anki-numbers.md
Prefill vs decode#
| Phase | Bound | Metric |
|---|---|---|
| Prefill (whole prompt, parallel) | compute-bound | TTFT |
| Decode (one token / step) | memory-bandwidth-bound | TPOT / ITL |
- KV cache = 2 × layers × kv_heads × head_dim × seq × batch × bytes
- Concurrency limit is usually KV-cache memory, not compute
- 70B (GQA, bf16): ~0.3 MB KV per token per request
Check yourself 2 questions
Which phase sets time to first token?
Show answer
Prefill.
Why is decode memory-bound?
Show answer
Each token reads all weights and the KV cache for little compute.
Takeaway Prefill is compute-bound (TTFT); decode is memory-bandwidth-bound (TPOT); the KV cache grows with sequence and batch.
KV-cache techniques#
| Technique | Idea |
|---|---|
| PagedAttention (vLLM) | fixed blocks + block table, like OS virtual memory; near-zero fragmentation; CoW sharing |
| Prefix caching / RadixAttention (SGLang) | reuse KV for shared system prompt / RAG context |
| Tiered offload | HBM → CPU DRAM → SSD → object store (LMCache, Dynamo KVBM) |
| KV quantisation | fp8/int8 KV → more concurrent sequences |
| Response cache ≠ KV cache | app-level exact prompt → answer vs engine-level attention state |
Check yourself 2 questions
What does PagedAttention borrow from operating systems?
Show answer
Virtual-memory-style fixed blocks with a block table.
What does prefix caching reuse?
Show answer
KV for shared prompt prefixes.
Takeaway PagedAttention removes fragmentation, prefix caching reuses shared prompts, quantised and compressed caches save memory.
Symptom → lever#
| Symptom | Lever |
|---|---|
| GPU idle between requests | continuous batching |
| long prompts spike everyone | chunked prefill |
| prefill bursts starve decode | disaggregated serving (prefill / decode pools, NIXL KV transfer) |
| same system prompt reprocessed | prefix caching |
| identical full requests | response cache |
| OOM under concurrency | paged KV + tiered offload |
| peer already has prefix | KV-aware routing |
| model too big for 1 GPU | tensor / pipeline parallelism |
Check yourself 2 questions
GPU idle between requests?
Show answer
Continuous batching.
Long prompts spiking everyone's latency?
Show answer
Chunked prefill.
Takeaway Idle GPUs → continuous batching; long prompts → chunked prefill; prefill starving decode → disaggregated serving.
Parallelism & quantisation#
- TP within a node over NVLink (fine-grained, latency) · PP across nodes (bubbles) · EP for MoE · DP replicas — e.g. TP=8 in node, PP across
- Interconnects: NVLink (in-node), InfiniBand/RoCE (cross-node), XGMI (AMD)
- Precision ladder: fp32 → bf16 → fp8 → int8 → int4
- GPTQ / AWQ weight-only INT4/INT8; FP8 native on Hopper/Blackwell; SmoothQuant W8A8
- INT8 ≈ −50% VRAM, <1% quality; INT4 ≈ −75%, 1–3%
- QLoRA = training-time quant; AWQ/GPTQ = serving quant
- Speculative decoding: draft proposes, target verifies; 2–4× TPOT if acceptance >70%
Check yourself 2 questions
Where should tensor parallelism run?
Show answer
Within a node over NVLink.
What's the cost of pipeline parallelism?
Show answer
Bubbles (idle stages).
Takeaway Tensor parallel within a node, pipeline across nodes, expert parallel for MoE; quantise weights and KV to fit and speed up.
Numbers to know#
| Item | Value |
|---|---|
| 1 token | ≈ 0.75 words ≈ 4 chars |
| VRAM / 1B params (bf16) | ~2 GB |
| 7–8B bf16 | 14–16 GB → 1× A10G / L4 (24 GB) |
| 70B bf16 | ~140 GB → 2× A100-80GB |
| TTFT target | < 1 s p95 (chat) |
| TPOT target | 20–50 ms (reading ≈ 200 ms/token) |
| Guardrail classifier | < 20 ms; intent classifier < 10 ms |
| IDE completion | < 100 ms |
| Semantic cache | cos ≥ 0.92, ~40% hit (FAQ) |
| GPU scale trigger | 60–70% utilisation |
| Peak multiplier | ~12× avg (consumer) |
Check yourself 2 questions
VRAM for a 7–8B model in bf16?
Show answer
About 14–16 GB.
Words per token roughly?
Show answer
About 0.75.
Takeaway 1 token ≈ 0.75 words; ~2 GB VRAM per billion params in bf16; 70B needs about 140 GB; TTFT under 1 s p95.
Cost cascade#
- 1. Semantic cache (~40% free)
- 2. Router: small 8B for easy queries (≈20× cheaper), frontier for hard
- 3. Prompt compression (LLMLingua, 30–50% fewer tokens)
- 4. Continuous batching + speculative decoding (self-hosted)
- 5. Quantise (INT8 / FP8); multiplex LoRA adapters on one base
- Eval gates: block cost increase >10% (low risk) / >2% (high risk)
Check yourself 2 questions
First rung of the cost cascade?
Show answer
A semantic cache.
How much cheaper is routing easy queries to an 8B model?
Show answer
About 20×.
Takeaway Semantic cache, model routing, prompt compression, batching, quantisation and distillation stack up savings.
16LLM system design & production ML
LLM-System-Design/chapters-md (cheat-sheet, anki-numbers, chapter list), Ml-overview/19-revision-guide/13-production-ml
LLM system design framework#
| Step | Do |
|---|---|
| 1 · Scope (5–10m) | interactive vs batch, QPS, TTFT/TPOT, cost per query; BotE tokens & GPUs |
| 2 · HLD (10m) | Client → Gateway → Orchestrator → Retriever → LLM; check in |
| 3 · Deep dives (15–20m) | 2–3 components; 2–3 options each + recommendation |
| 4 · Wrap (5m) | observability, cost tracking, PII redaction |
| 5 · Curveballs | hallucination, 10× traffic, vector DB OOM |
| Failure mode | Mitigation |
|---|---|
| Hallucination | RAG grounding, low temp, abstain, self-check |
| Prompt injection | input classifier, role isolation, sandboxed tools (MCP) |
| High TTFT | semantic cache, smaller model, spec decoding, batching |
| GPU OOM | quantise, cap context, PagedAttention |
| Stale RAG | event-driven reindex, soft deletes |
"Why?" rule: never name a tech without the reason + number.
Check yourself 2 questions
What belongs in scoping?
Show answer
Interactive versus batch, QPS, TTFT/TPOT, cost per query, back-of-envelope tokens and GPUs.
Typical high-level path?
Show answer
Client → gateway → orchestrator → retriever → LLM.
Takeaway Scope with estimates, a high-level design, deep dives on retrieval, serving and evaluation, then cost, safety and trade-offs.
Production ML / MLOps#
| Area | Key |
|---|---|
| Deployment | shadow → canary → A/B; blue-green; rollback |
| Serving | REST vs gRPC; dynamic batching; ONNX / TensorRT |
| Features | online (Redis) / offline store; point-in-time correctness; train-serve parity |
| Streaming | Kafka semantics; Flink windows + watermarks; Little's law |
| Data | Lambda vs Kappa; Parquet; Delta/Iceberg; medallion; data contracts |
| Registry | MLflow stages; champion/challenger; lineage; auto rollback |
| Monitoring | data drift (PSI) vs concept drift; latency P99; fallbacks |
| Diagnosis | sudden drop → pipeline bug; gradual → drift → retrain |
| Governance | model cards, audit trails, GDPR erasure |
Check yourself 2 questions
Safe rollout order?
Show answer
Shadow → canary → A/B, with rollback.
Why point-in-time correctness in feature stores?
Show answer
To avoid training on future information (leakage).
Takeaway Shadow, canary and A/B deployment; batched serving; online and offline feature stores with point-in-time correctness; monitoring and retraining.
Case studies#
| Group | Chapters |
|---|---|
| RAG & search | support chatbot, enterprise semantic search, financial doc extraction, shopping assistant, multimodal asset search, legal contract review, advanced RAG platform |
| Agents & MCP | research agent, text-to-SQL analyst, game NPC engine, multi-agent orchestrator, MCP tool platform |
| Fine-tune & prompt | coding assistant, content pipeline, prompt engineering, fine-tuning |
| Real-time & edge | meeting summariser, voice agent, on-device LLMs |
| Regulated | AI tutor, healthcare triage, privacy & governance |
| LLMOps | lifecycle, eval at scale, cost optimisation, observability & incidents |
Check yourself 2 questions
Name two RAG and search case studies.
Show answer
Any two of: support chatbot, enterprise semantic search, financial document extraction, shopping assistant, legal contract review.
What do the case studies practise?
Show answer
Applying the LLM system design framework end to end.
Takeaway RAG, search, extraction, assistants and review systems are the classic LLM system design cases.
MLOps lifecycle#
flowchart LR
D[("Data and labels")] --> V["Validate<br/>schema · drift"]
V --> T["Train and tune"]
T --> E{{"Offline eval gate"}}
E -->|"fail"| T
E -->|"pass"| REG[("Model registry")]
REG --> S["Shadow → canary → full rollout"]
S --> MON["Monitor<br/>drift · quality · latency · cost"]
MON -->|"retrain trigger"| D
MON -->|"regression"| RB["Automatic rollback"]
RB --> REG
classDef dec fill:__DF__,stroke:__DS__,color:__FG__
class E decCheck yourself 2 questions
What happens if the offline eval gate fails?
Show answer
Back to training.
Where do passing models go?
Show answer
The model registry.
Takeaway Validate data, train, gate on offline evaluation, register, deploy safely, monitor and retrain.
17MLOps and production ML platformNew
Google Cloud "MLOps: continuous delivery and automation pipelines in machine learning"; Chip Huyen, Designing Machine Learning Systems; Feast, MLflow, Kubeflow and KServe documentation; Sculley et al., "Hidden Technical Debt in Machine Learning Systems".
MLOps maturity: levels 0, 1 and 2#
| Level | What it looks like | Typical pain | Next step |
|---|---|---|---|
| 0 · manual | Notebook to pickle to a hand-deployed service; retrained "when someone remembers" | No reproducibility, silent decay, deploy by one person | Script the pipeline, track experiments, add a registry |
| 1 · pipeline automation | Orchestrated train → validate → register; continuous training on a schedule or trigger; feature store | Pipeline code itself is deployed by hand; tests thin | CI/CD for the pipeline, not just the model |
| 2 · CI/CD for pipelines | Pipeline changes are tested, built and released like services; models promoted by gates; monitoring triggers retraining | Platform cost and complexity | Self-service templates, cost and SLO dashboards |
Interview framing: name your current level, the one bottleneck that keeps you there, and the smallest change that moves you up. The model is usually 5% of the system; the rest is data, glue, serving and monitoring.
Check yourself 2 questions
What distinguishes MLOps level 2 from level 1?
Show answer
The pipeline code itself is tested, built and released through CI/CD, not just the model.
How should you answer 'how mature is your MLOps?'
Show answer
Name your level, the bottleneck keeping you there, and the smallest change that moves you up.
Takeaway Level 0 is manual, level 1 automates the training pipeline, level 2 adds CI/CD for the pipelines themselves.
Feature store internals#
- Two stores, one definition: an offline store (warehouse or lake: BigQuery, Delta, Parquet) for training, and an online store (Redis, DynamoDB, Cassandra) for low-latency lookups. Both are filled from the same feature definition, which is the whole point: it removes training–serving skew.
- Materialisation: batch jobs (and streaming jobs for fresh features, via Kafka or Flink) compute features and write to both stores; the online store keeps only the latest value per entity, with a TTL.
- Point-in-time joins: to build training data, each label row joins the feature values as they were at the label's timestamp (an "as of" join), never later values. Getting this wrong is silent leakage.
- Entities and keys: features hang off entity keys (user_id, merchant_id); a feature view groups features with the same key, source and freshness.
- Watch-outs: stale online values when a stream lags, hot keys, backfills that rewrite history, and features computed in the request path that never made it into the store.
- Tools: Feast (open source), Tecton, Feathr, Databricks and Vertex AI feature stores.
Check yourself 2 questions
Why does a feature store reduce training–serving skew?
Show answer
Both the offline and online stores are filled from the same feature definition.
What is a point-in-time join?
Show answer
Joining each label row to feature values as they were at the label's timestamp, never later.
Takeaway One feature definition fills an offline store for training and an online store for serving; point-in-time joins prevent leakage.
Pipeline orchestration#
- A pipeline is a DAG of steps: ingest → validate → featurise → train → evaluate → register. Orchestrators: Airflow (schedules and data jobs), Kubeflow Pipelines and Argo (container steps on Kubernetes), Dagster and Prefect (asset- and Python-first), Vertex and SageMaker Pipelines (managed).
- Make every task idempotent: rerunning a step for a date partition overwrites, never duplicates. That makes retries and backfills safe.
- Partition by time and pass the logical date into each task, not "now", so a backfill for last March computes last March.
- Data validation as a gate: schema, null rates, ranges and distribution checks (Great Expectations, TFX Data Validation, Pandera) stop bad data before training; a failed check fails the run loudly.
- Cache and lineage: store each step's inputs, code version and outputs so unchanged steps are skipped and any model can be traced to its data.
- Trigger retraining on a schedule, on new labelled data volume, or on a drift alert, and always through the same pipeline.
Check yourself 2 questions
Why make pipeline tasks idempotent?
Show answer
So retries and backfills overwrite instead of duplicating.
Why pass the logical date instead of 'now'?
Show answer
So a backfill computes the historical partition correctly.
Takeaway Pipelines are DAGs of idempotent, date-partitioned tasks with data validation as a gate.
CI/CD for models#
| Stage | What runs | Gate |
|---|---|---|
| CI on every commit | Unit tests for feature code and transforms, data-contract tests on a sample, a tiny training smoke run | All tests pass; lint and type checks |
| Continuous training | The full pipeline on fresh data | Validation checks pass |
| Offline evaluation | Metrics on a frozen holdout and per-slice metrics against the current champion | Beats champion by a set margin, no slice regresses beyond tolerance |
| Registry | Model, signature, metrics, data and code versions stored (MLflow, SageMaker, Vertex) | Stage moves: candidate → staging → production |
| Deploy | Container build, load test, shadow, then canary | Latency, error and business metrics hold during canary |
| Rollback | Previous registry version re-served | One command, rehearsed |
Treat the model as an artefact with a version, like a binary. Promote by evidence, roll back by pointer, and never retrain by hand in production.
Check yourself 2 questions
What must a candidate model show at the offline gate?
Show answer
Beat the champion by a set margin with no important slice regressing.
How should rollback work?
Show answer
Re-serve the previous registry version with one rehearsed command.
Takeaway Commit tests, continuous training, an offline gate against the champion, a registry, shadow and canary, and one-command rollback.
Serving patterns#
| Pattern | When | Watch-out |
|---|---|---|
| Batch scoring | Scores needed hours ahead (churn lists, nightly recommendations) | Stale scores for new users; storage for every entity |
| Online, synchronous | Decision inside a request (fraud, ranking), tens of ms | Tail latency, feature-fetch latency, fallbacks when the model is down |
| Streaming | Score events as they arrive (Kafka consumer) | Ordering, exactly-once effects, back-pressure |
| On-device or edge | Privacy, offline use, zero network latency | Model size, update rollout, device variety |
- Serving stacks: KServe, Seldon, BentoML, Ray Serve, Triton (multi-framework GPU), TorchServe; vLLM, TGI or TensorRT-LLM for LLMs.
- Always have a fallback: a cached score, a rule, or the previous model, so a model outage degrades rather than breaks the product.
Check yourself 2 questions
When is batch scoring the right pattern?
Show answer
When predictions are needed hours ahead, like churn lists or nightly recommendations.
Give three fallbacks for a model outage.
Show answer
A cached score, a simple rule, or the previous model.
Takeaway Batch, online, streaming and edge serving each fit a latency need; always keep a fallback.
GPU serving and autoscaling#
- Scale on the right signal: CPU percentage is meaningless for GPU models. Scale on queue depth, in-flight requests per replica or tokens per second, using KEDA or a custom-metric HPA on Kubernetes (AKS, EKS, GKE).
- Cold starts are slow: pulling a multi-gigabyte image and loading weights can take minutes. Keep a warm minimum, pre-pull images onto nodes, cache weights on local NVMe, and scale out before the queue explodes.
- Pack the GPU: dynamic or continuous batching raises throughput; small models can share a GPU via MIG partitions or multiple model servers; big models need tensor parallelism across GPUs.
- Node pools: separate GPU pools by GPU type, with taints so CPU pods don't land there, and spot or preemptible pools for batch and fault-tolerant work.
- Scale to zero only for rare, latency-tolerant traffic; otherwise the first user waits for the cold start.
- Track GPU utilisation, memory, queue time, time to first token and cost per thousand requests side by side.
Check yourself 2 questions
Why is CPU utilisation a bad autoscaling signal for GPU models?
Show answer
The work happens on the GPU; queue depth or in-flight requests reflect load.
How do you soften GPU cold starts?
Show answer
Warm minimum replicas, pre-pulled images and cached weights on local disk.
Takeaway Scale GPU models on queue depth or in-flight requests, keep warm replicas, pre-pull images and batch.
My model got worse: what now?#
Check yourself 2 questions
A metric drops right after a deploy. First move?
Show answer
Roll back first, then diff the change.
Inputs look stable but fresh labels show worse accuracy. What is it?
Show answer
Concept drift: the input–outcome relationship changed.
Takeaway Check recent changes, then broken features, then data drift, then concept drift, then the metric itself.
Monitoring and drift playbook#
| Layer | Watch | Typical alert |
|---|---|---|
| Service | Latency p50/p99, errors, throughput, saturation | p99 over SLO for 5 minutes |
| Data quality | Schema, null and default rates, ranges, freshness | Null rate of a key feature doubles |
| Data drift | PSI or KS on inputs, embedding drift | PSI above 0.2 on a top feature |
| Prediction drift | Score distribution, positive rate | Positive rate leaves its weekly band |
| Model quality | Accuracy, calibration, per-slice metrics once labels arrive | AUC down by a set margin vs last month |
| Business | Conversion, fraud loss, complaints | Guardrail metric breached |
- Labels arrive late (chargebacks in weeks, churn in months), so proxy signals carry the early warning and quality metrics confirm later.
- PSI rule of thumb: below 0.1 stable, 0.1–0.2 watch, above 0.2 investigate.
- Every alert needs an owner and a runbook entry; an alert nobody acts on trains people to ignore alerts.
Check yourself 2 questions
PSI rule of thumb?
Show answer
Below 0.1 stable, 0.1–0.2 watch, above 0.2 investigate.
Why can't you rely on accuracy alone for monitoring?
Show answer
Labels often arrive weeks or months late.
Takeaway Monitor service, data quality, data drift, prediction drift, model quality and business metrics; delayed labels make early layers essential.
Reproducibility and experiment tracking#
- A model is reproducible only if you can recover four things: code (git commit), data (a snapshot or version, via DVC, lakeFS, Delta time travel or warehouse snapshots), configuration (hyperparameters, feature list) and environment (container image digest, library versions).
- Track every run in MLflow, Weights & Biases or a managed equivalent: parameters, metrics, artefacts and the data version.
- Fix random seeds, but expect GPU nondeterminism; compare runs by metric distributions over several seeds, not one lucky run.
- Model cards record intended use, training data, metrics by slice, known limits and owners.
Check yourself 2 questions
Name the four things needed to reproduce a model.
Show answer
Code commit, data version, configuration and environment (image digest).
Why compare runs across several seeds?
Show answer
GPU nondeterminism and variance make one run unreliable.
Takeaway Reproducing a model needs code, data version, configuration and environment.
Cost control for ML platforms#
| Lever | Typical saving | Trade-off |
|---|---|---|
| Right-size instances, raise GPU utilisation with batching | Often 30–60% | Some added latency |
| Spot or preemptible for training and batch | 60–90% off on-demand | Checkpoint and retry logic |
| Quantise or distil the model | 2–4× cheaper serving | Small quality loss to measure |
| Cache repeated predictions or prompts | Large for skewed traffic | Staleness and invalidation |
| Autoscale by queue depth, scale down at night | Proportional to idle time | Cold starts |
| Retrain on a trigger, not a fixed daily cron | Fewer runs | Needs good drift signals |
Report cost per thousand predictions (or per million tokens) next to quality, so trade-offs are visible to the team that pays.
Check yourself 2 questions
What does spot capacity require to be safe for training?
Show answer
Checkpointing and retry logic.
Which cost metric should sit next to quality?
Show answer
Cost per thousand predictions (or per million tokens).
Takeaway Batching, spot capacity, quantisation, caching, queue-based autoscaling and triggered retraining cut ML cost.
Incident stories to tell#
- Training–serving skew: a "days since signup" feature used UTC in training and local time online; scores shifted for one region. Fix: one feature definition in the feature store, plus a parity test comparing online and offline values for sampled entities.
- Silent null: an upstream team renamed a column; the pipeline filled the missing feature with zero and accuracy fell for a week before anyone noticed. Fix: data contracts and a null-rate alert that fails the pipeline.
- Feedback loop: a recommender trained on its own clicks narrowed what users saw and engagement slowly fell. Fix: exploration traffic, logging propensities and position-debiased training.
- GPU cold start: autoscaling on CPU never added replicas; the queue grew until timeouts. Fix: scale on queue depth, keep a warm minimum and pre-pull images.
Tell each as STAR: the symptom, how you detected it, the root cause, the fix and the guard rail that stops it recurring.
Check yourself 2 questions
What fixed the UTC versus local-time skew?
Show answer
One feature definition plus an online–offline parity test.
What should every incident story end with?
Show answer
The guard rail that stops it recurring.
Takeaway Have skew, silent-null, feedback-loop and cold-start incidents ready as STAR stories.
MLOps interview questions#
| Question | Strong answer, in one line |
|---|---|
| How do you prevent training–serving skew? | One feature definition feeding both stores, point-in-time joins for training, and a parity test online vs offline. |
| When should a model retrain? | On a trigger (enough new labels, drift beyond a threshold, or a schedule matched to how fast the world changes), always through the same validated pipeline. |
| How do you roll out a new model safely? | Offline gate vs champion, shadow traffic, canary with guardrail metrics, then ramp; keep the previous version one pointer away. |
| How do you monitor without labels? | Input and prediction drift, data quality and proxy business signals now; quality metrics when delayed labels arrive. |
| How do you autoscale a GPU model? | On queue depth or in-flight requests, with a warm minimum, pre-pulled images and batching to keep utilisation high. |
| What goes in a model registry entry? | The artefact, its signature, metrics by slice, data and code versions, owner and stage. |
Check yourself 2 questions
When should a model retrain?
Show answer
On a trigger: enough new labels, drift past a threshold, or a schedule matched to change, through the same pipeline.
How do you roll out a model safely?
Show answer
Offline gate, shadow, canary with guardrails, then ramp, with rollback one pointer away.
Takeaway Skew, retraining triggers, safe rollout, label-free monitoring and GPU autoscaling are the core MLOps questions.
18Classic ML system design
The non-LLM design questions in ML engineer loops: a framework plus the key decisions for ten common prompts.
Framework (45 min)#
- Clarify the product goal, users, scale, latency budget, constraints.
- Frame as an ML task: input, output, label; is ML even needed?
- Metrics: offline (AUC, NDCG) tied to online (CTR, revenue, retention) + guardrails.
- Data: sources, labels (explicit, implicit, human), sampling, leakage, privacy.
- Features: user, item, context, cross features; freshness; feature store.
- Model: baseline → stronger model; justify by data size and latency.
- Serving: batch vs online; candidate retrieval → ranking; caching; fallbacks.
- Evaluate: offline replay, A/B test, interleaving.
- Monitor and iterate: drift, feedback loops, retraining cadence.
Check yourself 2 questions
What should offline metrics be tied to?
Show answer
Online business metrics such as CTR or retention.
What question comes right after framing the ML task?
Show answer
Is ML even needed?
Takeaway Clarify, frame as ML, choose metrics, data and features, model, serving, evaluation and monitoring.
Common traps#
- Jumping to a deep model before a baseline and a metric.
- Training–serving skew: features computed differently online.
- Label leakage from post-event signals (refund flag in fraud features).
- Ignoring position bias and feedback loops in implicit labels.
- Random splits on time-dependent data; use time-based splits.
- No plan for cold start, delayed labels, or class imbalance.
- Forgetting latency and cost: 100 ms budget shapes model size.
Check yourself 2 questions
What's training–serving skew?
Show answer
Features computed differently online than in training.
Give an example of label leakage.
Show answer
Using a refund flag (a post-event signal) as a fraud feature.
Takeaway Skipping baselines, training–serving skew, label leakage, ignoring feedback loops and offline-only evaluation.
Ten prompts, key decisions#
| Prompt | Label / objective | Key features | Model and serving | Gotcha |
|---|---|---|---|---|
| Feed ranking | Multi-task: click, like, dwell, hide | Author affinity, recency, content embeddings | Retrieval + DNN ranker, weighted score | Engagement bait; diversity re-rank |
| Ads CTR prediction | Click (calibrated probability) | Sparse IDs, user history, context | Logistic regression → DCN/DLRM; online learning | Calibration matters for auction bids |
| Video recommendations | Watch time, satisfaction surveys | Watch history sequence, co-watch | Two-tower retrieval + ranker | Clickbait; freshness for new uploads |
| Search ranking | Graded relevance, clicks | Query-doc text match, BM25, popularity | Hybrid retrieval + LambdaMART / cross-encoder | Position bias in click labels |
| Fraud detection | Chargebacks (delayed) | Velocity, device, graph links, amounts | GBDT + rules; real-time scoring < 100 ms | Extreme imbalance; adversarial drift |
| ETA prediction | Actual arrival time | Route segments, traffic, time, weather | GBDT / GNN on road graph | Asymmetric cost of under-estimates |
| Spam / abuse classification | Reports, reviewer labels | Text, sender reputation, behaviour | Fine-tuned encoder + rules; human review queue | Adversaries adapt; precision at high recall |
| People you may know | Connection accepted | Mutual friends, graph proximity | Graph candidate gen + ranker | Privacy and sensitive connections |
| Dynamic pricing | Conversion and revenue | Demand, supply, competitor price | Demand model + optimiser; bandits | Fairness, regulation, feedback loops |
| Visual / product search | Same or similar item | Image + text embeddings | CLIP-style encoder + ANN index | Index freshness; near-duplicates |
Check yourself 2 questions
Feed ranking objective?
Show answer
Multi-task: click, like, dwell, hide, combined with weights.
What's a common gotcha in feed ranking?
Show answer
Position bias and feedback loops.
Takeaway Feed ranking, ads, search, fraud and other prompts each have a label, key features, model and a gotcha.
19ML system design: three full walkthroughs
Model answers that follow the framework above: framing and metrics, data and labels, features, model, serving, monitoring and trade-offs.
Video recommendations (home feed)#
Multi-stage funnel: cheap retrieval over millions of videos, an expensive ranker over hundreds, then policy and diversity re-ranking.
flowchart LR
EV[["Events<br/>views, likes, skips"]] --> FS[("Feature store<br/>online + offline")]
EV --> TR["Training pipelines"]
TR --> TT["Two-tower model"]
TR --> RKM["Ranking model"]
TT --> ANN[("ANN index<br/>video embeddings")]
U["User opens app"] --> CG["Candidate generation<br/>ANN · co-watch · fresh"]
CG --> ANN
CG --> R["Ranker"]
RKM --> R
R --> FS
R --> RR["Re-rank<br/>diversity · policy"]
RR --> U
Framing and metrics
- Goal: long-term satisfaction, not clicks. Proxy: expected watch time plus survey-based satisfaction.
- Offline: Recall@k for retrieval; NDCG and AUC for ranking; calibration per head.
- Online: watch time per user, 7-day retention, diversity. Guardrails: latency, creator fairness, policy violations.
Data and labels
- Positives: watched ≥ 30 s or ≥ 50%; negatives: impressed and skipped.
- Log the position shown; train with it as a feature and fix it at serving to remove position bias.
- Time-based splits; dedupe bots and autoplay.
Features and models
- User: last N watched IDs (sequence encoder), search history, locale, device, time of day.
- Video: content embedding, age, creator, quality and engagement rates.
- Cross: user-creator affinity, topic match.
- Retrieval: two-tower with in-batch negatives and log-Q correction; HNSW or ScaNN index refreshed hourly.
- Ranking: multi-task DNN (click, watch time, like, dislike) combined by tuned weights.
Serving and monitoring
- ~200 ms budget: retrieval 1,000s → ranking 100s → show ~20.
- Cache user embeddings; precompute for inactive users.
- Monitor feature drift, index freshness, model calibration; long-term holdout groups.
Trade-offs
- Exploration slots for new videos vs short-term watch time.
- Cold start: content embeddings and a freshness boost.
- Feedback loops narrow tastes; diversity constraints in re-ranking.
Check yourself 2 questions
Why a multi-stage funnel?
Show answer
Expensive models can only score hundreds of candidates in time.
What does re-ranking add?
Show answer
Policy, diversity and business rules.
Takeaway Cheap retrieval over millions, an expensive ranker over hundreds, then policy and diversity re-ranking.
Payment fraud detection#
A synchronous decision under 100 ms with heavily imbalanced, delayed labels and an adversary who adapts.
flowchart LR
TX["Payment request"] --> GW["Payment gateway"]
GW --> RS["Risk service<br/>p99 under 100 ms"]
RS --> OF[("Online features<br/>velocity counters")]
RS --> RU["Rules engine"]
RS --> M["GBDT model"]
RS -->|"approve, review or decline"| GW
RS -.->|"review"| HR["Analyst queue"]
GW -.-> ST[["Event stream"]]
ST -.-> OF
CB[["Chargebacks and analyst labels"]] -.-> TRN["Weekly retraining"]
TRN -.-> M
Framing and metrics
- Predict P(fraud); map to approve / step-up auth / review / decline with thresholds set from costs: fraud loss vs lost revenue from false declines.
- Offline: PR-AUC, recall at a fixed false-positive rate, dollar-weighted recall.
- Online: chargeback rate, approval rate, review queue size.
Labels
- Chargebacks arrive 30–90 days later: train on matured windows; use analyst labels for recent data.
- Fraud is ~0.1%: class weights, careful negative sampling, calibrate afterwards.
- Declined transactions never get labels: keep a tiny randomised holdout or use counterfactual evaluation.
Features and model
- Velocity: transactions per card, device, IP and email over 1 minute, 1 hour, 24 hours.
- Behaviour: amount vs the user's history, new device, distance from last location, time since account creation.
- Graph: devices or cards shared with known fraud.
- Model: gradient-boosted trees plus hard rules; explain with SHAP for analysts.
Serving and monitoring
- Online feature store with point-in-time correct training data, so training and serving match.
- New models run in shadow mode before taking decisions.
- Fallback to rules if the model times out.
- Alert on approval-rate shifts and feature drift (PSI); fraudsters adapt within days.
Trade-offs
- Decline vs step-up authentication vs manual review.
- Recall vs customer friction; segment thresholds by merchant risk.
Check yourself 2 questions
Latency budget for fraud scoring?
Show answer
Under about 100 ms, synchronous.
Two label problems in fraud?
Show answer
Heavy imbalance and delayed labels (chargebacks arrive late).
Takeaway Synchronous decisions under 100 ms with imbalanced, delayed labels and an adaptive adversary.
Enterprise knowledge assistant (RAG)#
Grounded answers with citations over internal documents, where permissions and prompt injection matter as much as answer quality.
flowchart TD
SRC[("Wiki, drive, tickets")] --> ING["Ingest<br/>parse · chunk · ACL tags"]
ING --> EMB["Embed"]
EMB --> IDX[("Vector + BM25 index")]
Q["Employee question"] --> GW["Gateway<br/>auth · rate limit"]
GW --> QR["Query rewrite"]
QR --> RET["Hybrid retrieval<br/>filtered by user ACL"]
RET --> IDX
RET --> RR["Cross-encoder rerank"]
RR --> LLM["LLM answer with citations"]
LLM --> OC["Output checks<br/>PII · grounding"]
OC --> Q
LLM -.-> OBS[("Traces, evals, feedback")]
Requirements and metrics
- 10K employees, 50K questions/day, first token < 2 s, sources updated within an hour, answers cite sources, never leak documents a user can't open.
- Retrieval recall@k on a labelled set; faithfulness and correctness (LLM judge calibrated with humans); citation accuracy; deflection rate; thumbs up/down.
Pipeline
- Chunk 300–500 tokens along headings; keep title, source, owner, ACL groups, updated_at.
- Change events trigger incremental re-indexing and deletes.
- Hybrid retrieval (BM25 + dense, reciprocal rank fusion) top-50 → rerank → best 5–8 chunks.
- Permission filter applied inside retrieval, never after generation.
- Prompt: answer only from sources, cite [n], say when the answer isn't there; stream over SSE.
Safety, cost and evaluation
- Documents can contain prompt injection: treat retrieved text as data and give the model no write tools.
- Redact PII in logs; retain traces for debugging under a retention policy.
- Small model for query rewriting, larger model for answers; semantic cache scoped by permission set.
- Golden set of 200–500 questions gates every prompt, model or chunking change.
Trade-offs
- Long-context stuffing is simpler but costlier and weaker on precision than retrieval.
- Fine-tuning is for tone and format, not for keeping knowledge current.
Check yourself 2 questions
How are permissions enforced?
Show answer
Filter retrieval by the user's access rights.
Why is prompt injection a risk here?
Show answer
Documents themselves can carry malicious instructions.
Takeaway Grounded, cited answers over internal docs, where permissions and prompt injection matter as much as quality.
20Classical AI foundations
The pre-deep-learning AI toolkit (search, games, constraints, probabilistic reasoning). It still powers planners, game engines and agent tool use.
Search#
| Algorithm | Property |
|---|---|
| BFS / DFS | Uninformed; BFS optimal for unit costs |
| Uniform-cost (Dijkstra) | Optimal for non-negative costs |
| Iterative deepening | BFS optimality with DFS memory |
| Greedy best-first | Follows h(n); fast, not optimal |
| A* | f = g + h; optimal if h is admissible (never overestimates) |
| Local search | Hill climbing, simulated annealing, genetic algorithms |
Check yourself 2 questions
When is A* optimal?
Show answer
With an admissible (never overestimating) heuristic.
What does iterative deepening combine?
Show answer
BFS optimality with DFS memory.
Takeaway BFS and DFS are uninformed, uniform-cost is optimal for non-negative costs, A* is optimal with an admissible heuristic.
Games and constraints#
- Minimax: maximise your minimum outcome in zero-sum games.
- Alpha-beta pruning: skip branches that can't change the decision; best case O(b^{d/2}).
- MCTS: selection (UCT) → expansion → simulation → backpropagation; AlphaGo pairs it with policy/value nets.
- CSP: variables, domains, constraints. Backtracking + MRV heuristic + forward checking + arc consistency (AC-3).
Check yourself 2 questions
Best-case complexity of alpha-beta?
Show answer
O(b^(d/2)).
MCTS steps?
Show answer
Selection, expansion, simulation, backpropagation.
Takeaway Minimax with alpha-beta pruning, MCTS for huge trees, and CSPs with backtracking and propagation.
Reasoning under uncertainty#
- Bayesian networks: DAG of conditional probabilities; exact or sampling inference.
- Hidden Markov models: forward algorithm (likelihood), Viterbi (best path), Baum-Welch (learning).
- Kalman / particle filters: state tracking from noisy sensors.
- MDP solving: value iteration, policy iteration.
- Logic: propositional and first-order logic, resolution; planning with STRIPS/PDDL.
Check yourself 2 questions
What does the Viterbi algorithm find?
Show answer
The most likely hidden state path.
What does the forward algorithm compute?
Show answer
The likelihood of the observations.
Takeaway Bayesian networks, HMMs with forward and Viterbi, and Kalman filters handle uncertain state.
21Rapid-fire interview questions
Short questions that show up in almost every ML/LLM screen, with the answer to give in one or two sentences.
Question → crisp answer#
| Question | Answer |
|---|---|
| Why divide attention scores by √d_k? | Dot products grow with dimension; scaling keeps softmax out of saturated regions where gradients vanish. |
| L1 vs L2 regularisation? | L1 drives weights to exactly zero (feature selection, Laplace prior); L2 shrinks smoothly (Gaussian prior), handles correlated features better. |
| Bagging vs boosting? | Bagging trains independent models on bootstraps to cut variance (RF); boosting trains sequentially on residuals to cut bias (XGBoost). |
| How do you handle class imbalance? | Right metric (PR-AUC, recall at precision), class weights or focal loss, resampling inside CV only, threshold tuning, more minority data. |
| Why LayerNorm instead of BatchNorm in transformers? | Normalises per token, independent of batch size and sequence padding; works at inference with batch size 1. |
| What does BatchNorm do at inference? | Uses running mean and variance collected in training, not batch statistics. |
| Fix vanishing gradients? | ReLU-family activations, residual connections, normalisation, good initialisation (He/Xavier), LSTM/GRU gates for RNNs. |
| Why AdamW over Adam? | Adam's L2 penalty gets scaled by the adaptive learning rate; AdamW decouples weight decay so regularisation behaves as intended. |
| What is the KV cache? | Stored keys and values of past tokens so each decode step only computes attention for the new token; trades memory for compute. |
| Why GQA? | Shares K/V heads across query groups; shrinks KV cache and memory bandwidth with little quality loss. |
| How does LoRA work? | Freezes W and learns a low-rank update BA (rank r); far fewer trainable parameters; can be merged into W after training. |
| DPO vs PPO-based RLHF? | DPO optimises preferences directly from pairs without a reward model or RL loop: simpler and stabler; PPO can explore beyond the dataset. |
| RAG or fine-tuning? | RAG for changing or private knowledge with citations; fine-tuning for consistent behaviour, format, tone, or a smaller cheaper model. |
| Why is speculative decoding lossless? | The target model verifies draft tokens with rejection sampling, so outputs follow the target's distribution exactly. |
| Temperature 0 still gives different outputs. Why? | Floating-point non-determinism in batched GPU kernels and ties; batch composition changes numerics. |
| How do you evaluate a RAG system? | Retrieval recall/precision on labelled queries, then faithfulness and answer relevance, plus end-to-end human or judge review on a golden set. |
| Data drift vs concept drift? | Data drift: input distribution changes (PSI, KS). Concept drift: the input → label relationship changes; detected by falling performance on fresh labels. |
| Cross-validation for time series? | Forward-chaining (expanding or rolling window) splits; never shuffle future into training. |
| Curse of dimensionality? | Distances concentrate and data becomes sparse as dimensions grow; KNN and density estimates degrade; reduce dimensions or regularise. |
| Explain ROC-AUC to a PM | The chance the model ranks a random positive above a random negative; 0.5 is coin flip, 1.0 is perfect ranking. |
| What is calibration and how to fix it? | Predicted probabilities match observed frequencies; fix with Platt scaling, isotonic regression or temperature scaling on a held-out set. |
| Why does dropout help? | Prevents co-adaptation; approximates an ensemble of thinned networks; turned off at inference. |
| Prefill vs decode bottlenecks? | Prefill is compute-bound (big matrix multiplies over the prompt); decode is memory-bandwidth-bound (reading weights and KV per token). |
| How would you reduce LLM serving cost? | Cache, route easy queries to small models, shorten prompts, quantise, batch continuously, use prefix caching, distil. |
| What is hallucination and how to reduce it? | Fluent but unsupported output. Ground with retrieval, ask for citations, allow abstention, lower temperature, verify with checks or a second model. |
Check yourself 2 questions
Why scale attention by √d_k?
Show answer
Dot products grow with dimension; scaling keeps softmax out of saturated regions.
L1 versus L2 in one line?
Show answer
L1 drives weights to zero (sparse); L2 shrinks them smoothly.
Takeaway Rapid-fire questions with crisp answers: attention scaling, L1 versus L2, bias–variance and more.
22Implement from scratch: ML coding round
ML engineer loops often ask you to code a core algorithm in plain NumPy. These are compact, correct versions to practise from.
Stable softmax and cross-entropy#
import numpy as np def softmax(z): # z: (n, k) z = z - z.max(axis=1, keepdims=True) # subtract max for stability e = np.exp(z) return e / e.sum(axis=1, keepdims=True) def cross_entropy(logits, y): # y: integer labels (n,) z = logits - logits.max(axis=1, keepdims=True) log_probs = z - np.log(np.exp(z).sum(axis=1, keepdims=True)) return -log_probs[np.arange(len(y)), y].mean() # gradient w.r.t. logits: (softmax(logits) - one_hot(y)) / n
Check yourself 2 questions
Why subtract the max before exp?
Show answer
To avoid overflow without changing the result.
Stable cross-entropy uses what?
Show answer
Log-softmax (log-sum-exp).
Takeaway Subtract the row max before exponentiating, and use log-softmax for cross-entropy.
Logistic regression with gradient descent#
def fit_logreg(X, y, lr=0.1, epochs=500, l2=0.0): n, d = X.shape w, b = np.zeros(d), 0.0 for _ in range(epochs): p = 1 / (1 + np.exp(-(X @ w + b))) # predicted probabilities grad_w = X.T @ (p - y) / n + l2 * w grad_b = (p - y).mean() w -= lr * grad_w b -= lr * grad_b return w, b # predict: (1 / (1 + exp(-(X @ w + b)))) >= 0.5
Check yourself 2 questions
Gradient of logistic loss with respect to w?
Show answer
Xᵀ(p − y) ÷ n (plus the L2 term).
Prediction formula?
Show answer
sigmoid(Xw + b).
Takeaway Sigmoid probabilities, gradient Xᵀ(p − y)/n, optional L2, and a learning rate.
k-means#
def kmeans(X, k, iters=100, seed=0): rng = np.random.default_rng(seed) C = X[rng.choice(len(X), k, replace=False)] # (k-means++ is better) for _ in range(iters): d = ((X[:, None, :] - C[None, :, :]) ** 2).sum(-1) # (n, k) labels = d.argmin(1) newC = np.array([X[labels == j].mean(0) if (labels == j).any() else C[j] for j in range(k)]) if np.allclose(newC, C): break C = newC return C, labels
Check yourself 2 questions
Two alternating steps of k-means?
Show answer
Assign to nearest centroid; recompute centroids as means.
Better initialisation?
Show answer
k-means++.
Takeaway Assign points to the nearest centroid, recompute centroids, repeat; k-means++ initialises better.
Scaled dot-product attention with a causal mask#
def attention(Q, K, V, causal=True): # (T, d) each, single head d = Q.shape[-1] scores = Q @ K.T / np.sqrt(d) # (T, T) if causal: T = scores.shape[0] scores = np.where(np.tril(np.ones((T, T))) == 1, scores, -1e9) w = softmax(scores) # rows sum to 1 return w @ V # (T, d) # multi-head: split d into h heads, run per head, concatenate, project
Check yourself 2 questions
How is the causal mask applied?
Show answer
Set scores above the diagonal to −∞ before softmax.
Shape of the score matrix for T tokens?
Show answer
T × T.
Takeaway Scores = QKᵀ/√d, mask future positions to −∞, softmax, then multiply by V.
ROC-AUC from scratch#
def roc_auc(y, scores): # probability a random positive outranks a random negative (ties count ½) order = np.argsort(scores) ranks = np.empty(len(scores)); ranks[order] = np.arange(1, len(scores) + 1) for s in np.unique(scores): # average ranks for ties m = scores == s; ranks[m] = ranks[m].mean() pos = y == 1; n_pos, n_neg = pos.sum(), (~pos).sum() return (ranks[pos].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)
Check yourself 2 questions
What does ROC-AUC mean probabilistically?
Show answer
P(random positive scores above random negative), ties counting half.
How do ranks give AUC?
Show answer
Sum the positive ranks, subtract n₊(n₊+1)/2, divide by n₊·n₋.
Takeaway AUC is the probability a random positive outranks a random negative, computed from ranks.
Top-p (nucleus) sampling#
def sample_top_p(logits, p=0.9, temperature=1.0, rng=np.random.default_rng()): probs = softmax((logits / temperature)[None, :])[0] order = np.argsort(-probs) cum = np.cumsum(probs[order]) keep = order[: np.searchsorted(cum, p) + 1] # smallest set with mass ≥ p kept = probs[keep] / probs[keep].sum() return rng.choice(keep, p=kept)
Check yourself 2 questions
Which tokens survive top-p?
Show answer
The smallest set whose cumulative probability reaches p.
Where is temperature applied?
Show answer
To the logits, before softmax.
Takeaway Sort probabilities, keep the smallest set reaching p, renormalise and sample.
23Last-minute checklist
Last-minute revision#
- Baseline first; GBDT for tabular; split before any fit
- Imbalance → PR-AUC/F1, class weights, resample inside CV
- Attention: softmax(QKᵀ/√d)V; GQA shrinks KV; RoPE positions; pre-norm + RMSNorm + SwiGLU
- AdamW + warmup + cosine; clip at 1.0; bf16
- SFT for format, DPO for preferences, LoRA/QLoRA for cheap adaptation
- RAG = hybrid retrieval + rerank + faithfulness eval; chunks 200–500 tokens
- Prefill compute-bound (TTFT); decode memory-bound (TPOT); KV cache is the concurrency limit
- vLLM PagedAttention, continuous batching, prefix caching, disaggregation, spec decoding
- Quantise: FP8 on Hopper, AWQ/GPTQ INT4 to fit; validate with evals
Check yourself 2 questions
Metric for imbalanced classification?
Show answer
PR-AUC or F1.
Where should resampling happen?
Show answer
Inside CV folds only.
Takeaway Baselines first, GBDT for tabular, split before fitting, PR-AUC for imbalance, attention and serving essentials.