CSCheatsheets
ML engineering

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.

24sections
120cards
17diagrams
0%known

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 dec

Choose the task before choosing the model. Check label availability, data volume, leakage risk, latency, interpretability, and cost.

Check yourself 2 questions
  1. The output is an ordered list of items. Which family?

    Show answer

    Ranking or recommendation.

  2. 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 dec

Split before fitting any learned transform. Match the split to the deployment unit: time, person, site, or group.

Check yourself 2 questions
  1. Why build a simple baseline early?

    Show answer

    Every fancier model must beat it to justify its cost.

  2. 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 dec

Use 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
  1. What's missing if you need fresh, private or cited knowledge?

    Show answer

    Retrieval: add RAG.

  2. 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#

LayerQuestionsExamples
Data & splitIs the test set representative and uncontaminated?Time/group split, dedup, label audit
Task qualityDoes the model solve the actual task?PR-AUC, calibration, NDCG/MRR, exact match
Robustness & slicesWhere does it fail, and for whom?Subgroup slices, stress tests, shift tests
LLM / RAGAre answers grounded, useful, safe, and complete?Retrieval recall, faithfulness, citation checks, human review
ProductionCan it meet service constraints?p95 latency, availability, tokens/request, cost, fallback rate
Online evidenceDid 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
  1. First layer of the evaluation stack?

    Show answer

    Data and split: representative and uncontaminated.

  2. 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 familyPatterns and decisionsJump
Problem framing & model choiceLearning objective, modality, baseline, algorithm selection§01 · §0 objective flow
Data & classical MLPreprocessing, leakage-safe validation, model families, metrics, time series, HPO§04
Deep learning & generationTraining loop, architectures, optimization, VAE/GAN/diffusion/flows§08
LLM training & applicationsPretraining, SFT/alignment, prompting, RAG, agents, hallucination§11
Inference & servingPrefill/decode, KV cache, parallelism, quantization, latency/cost levers§15
System design & MLOpsDeployment, feature/data systems, monitoring, incidents, governance§16
Check yourself 2 questions
  1. What does the coverage map help with?

    Show answer

    Jumping to the section that covers a topic family.

  2. 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#

SignalRouteKey check
Personalized ranking at scaleCandidate retrieval → feature-rich ranker → re-rank / constraintsOffline NDCG/Recall plus online experiment; watch popularity and position bias.
Estimate treatment impactRandomized experiment → causal effect; observational data → matching / weighting / doubly robustState identification assumptions, interference, and uncertainty.
Choose actions from feedbackContextual bandit → constrained RL only when delayed state mattersSafe exploration, off-policy evaluation, reward hacking checks.
Relational inputsGraph features / message-passing GNNCompare against tabular and embedding baselines; guard against neighbor leakage.
Text, image, audio, video togetherPretrained modality encoders → fusion / cross-attention → task head or generative modelAlign timestamps, modality failures, and evaluation by modality.
Small labeled datasetTransfer learning, frozen embeddings, PEFT, augmentation, active labelingKeep validation independent; avoid synthetic-data leakage.
Model quality regresses after launchTrace data → features/retrieval → model → serving → user outcomeSeparate input drift, label/concept drift, retrieval failure, and service failure.
Check yourself 2 questions
  1. Personalised ranking at scale: the route?

    Show answer

    Candidate retrieval, a feature-rich ranker, then re-ranking with constraints.

  2. 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)#

ProblemFirst choiceWhy
Tabular, mixed typesXGBoost / LightGBMhandles missing, non-linearity natively
Tabular, needs interpretabilityLogistic regression + FEcoefficients meaningful, calibrated
Imagespretrained CNN / ViT fine-tunedrepresentation learning
Text classificationfine-tuned LMpretrained context
Anomaly, no labelsIsolation Forest, DBSCAN, autoencoderunsupervised
Small data, odd structureKNN / SVM-RBFnon-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
  1. First choice for tabular mixed-type data?

    Show answer

    XGBoost or LightGBM.

  2. 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
  1. Cost of multiplying (m×n) by (n×p)?

    Show answer

    m·n·p.

  2. 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
  1. What is backprop, mathematically?

    Show answer

    Repeated application of the chain rule.

  2. 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#

Bayes: P(A|B) = P(B|A)·P(A) / P(B)E[X+Y] = E[X]+E[Y]; Var(aX) = a²Var(X)Var(X) = E[X²] − E[X]²
  • 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
  1. Bayes' rule?

    Show answer

    P(A|B) = P(B|A)·P(A) ÷ P(B).

  2. 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#

DistributionModelsMean / var
Bernoulli(p)One yes/no trialp / p(1−p)
Binomial(n,p)Successes in n trialsnp / np(1−p)
Poisson(λ)Event counts per intervalλ / λ
Geometric(p)Trials to first success1/p
Exponential(λ)Time between events; memoryless1/λ / 1/λ²
Normal(μ,σ²)Sums of many effects; 68-95-99.7μ / σ²
Beta(α,β)Prior over a probability (Thompson sampling)α/(α+β)
Categorical / DirichletMulti-class outcome / prior over it—
Check yourself 2 questions
  1. Poisson mean and variance?

    Show answer

    Both λ.

  2. 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
  1. Which prior corresponds to L2 regularisation?

    Show answer

    A Gaussian prior.

  2. 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
  1. What does a p-value measure?

    Show answer

    P(data this extreme | H₀), not P(H₀ true).

  2. 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#

MethodKey assumptionUse when
Randomised experiment (A/B)Random assignment; no interference between unitsYou can control who gets the treatment
Regression adjustmentAll confounders are measured and modelled correctlyObservational data with rich covariates
Propensity matching / weighting (IPW)No unmeasured confounding; overlap between groupsTreatment chosen by observed factors
Doubly robust / double MLEither the outcome or the propensity model is rightHigh-dimensional confounders, ML nuisance models
Difference-in-differencesParallel trends without treatmentPolicy launched in some regions or times, not others
Synthetic controlA weighted mix of untreated units mimics the treated oneOne treated unit (a country, a city)
Regression discontinuityUnits just above and below a cutoff are comparableTreatment assigned by a threshold (credit score, age)
Instrumental variablesThe instrument affects the outcome only through the treatmentUnmeasured confounding with a valid instrument
Uplift modelling (S-, T-, X-learners)Experimental or well-adjusted dataTarget the users whom treatment changes most (CATE)
Vocabulary: ATE (average effect for everyone), ATT (for the treated), CATE (conditional on features). Draw the causal graph: adjust for confounders, never for colliders or mediators of the effect you want.
Check yourself 2 questions
  1. Difference-in-differences key assumption?

    Show answer

    Parallel trends.

  2. 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#

Precision = TP / (TP + FP)Recall (TPR) = TP / (TP + FN)F1 = 2PR / (P + R) (Fβ weights recall β times more)Specificity = TN / (TN + FP)FPR = FP / (FP + TN) = 1 − specificityAccuracy = (TP + TN) / totalLog loss = −(1/N) Σ [y log p + (1−y) log(1−p)]
  • 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
  1. Precision formula?

    Show answer

    TP ÷ (TP + FP).

  2. 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#

MAE = mean|y − ŷ|RMSE = √mean(y − ŷ)²R² = 1 − SS_res / SS_totDCG@k = Σ (2^rel_i − 1) / log₂(i + 1)NDCG = DCG / IDCGMRR = mean(1 / rank of first relevant)Recall@k = relevant in top k / all relevantPerplexity = exp(cross-entropy per token)
  • 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
  1. MRR formula?

    Show answer

    Mean of 1 ÷ rank of the first relevant result.

  2. 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#

LossFormula / ideaUse
MSE / MAE / Huber(y−ŷ)², |y−ŷ|, quadratic near 0 then linearRegression; Huber resists outliers
Cross-entropy−Σ y log softmax(z)Classification, language modelling
Focal−(1−p)^γ log pHeavy class imbalance, detection
Hingemax(0, 1 − y·f(x))SVM
Contrastive / InfoNCE−log e^{s⁺/τ} / Σ e^{s/τ}Embeddings, CLIP, retrieval
Tripletmax(0, d(a,p) − d(a,n) + m)Metric learning, face ID
KL divergenceΣ p log(p/q)VAE, distillation, RLHF penalty
Pairwise rankinglog(1 + e^{−(s_i − s_j)})Learning to rank, reward models
Check yourself 2 questions
  1. Which regression loss resists outliers?

    Show answer

    Huber (or MAE).

  2. 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#

SGD: θ ← θ − η gMomentum: v ← βv + g θ ← θ − η vAdam: m ← β₁m + (1−β₁)g; v ← β₂v + (1−β₂)g² m̂ = m/(1−β₁ᵗ); v̂ = v/(1−β₂ᵗ) θ ← θ − η m̂ / (√v̂ + ε)AdamW: same + θ ← θ − ηλθ (decoupled weight decay)
  • Adam memory: 2 extra states per parameter → ~16 bytes/param with fp32 master weights in mixed precision.
Check yourself 2 questions
  1. What does AdamW change from Adam?

    Show answer

    Weight decay is decoupled from the gradient update.

  2. 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#

sigmoid(x) = 1/(1+e^−x)softmax(z)_i = e^{z_i}/Σ e^{z_j}Attention(Q,K,V) = softmax(QKᵀ/√d_k) VLayerNorm(x) = γ (x − μ)/√(σ² + ε) + βRMSNorm(x) = γ x / √(mean(x²) + ε)SwiGLU(x) = (Swish(xW₁) ⊙ xW₃) W₂Dropout: zero with prob p, scale kept units by 1/(1−p)
Check yourself 2 questions
  1. Attention formula?

    Show answer

    softmax(QKᵀ ÷ √d_k) V.

  2. 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#

Params (dense decoder) ≈ 12 · L · d² (+ vocab · d embeddings)Training FLOPs ≈ 6 · N · D (N params, D tokens)Inference FLOPs ≈ 2 · N per tokenWeights memory = N × bytes/param (bf16 = 2, int8 = 1, int4 = 0.5)Full fine-tune with Adam ≈ 16–20 bytes/param (+ activations)KV cache/token = 2 · L · n_kv_heads · d_head · bytesAttention cost ∝ n² · d per layer
  • 7B in bf16 ≈ 14 GB weights; Llama-style 70B with GQA ≈ 0.3 MB KV per token in bf16.
Check yourself 2 questions
  1. Training FLOPs formula?

    Show answer

    About 6 × parameters × tokens.

  2. 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
  1. Good practice when imputing?

    Show answer

    Add a missing-indicator feature.

  2. 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#

TopicKey point
RegularisationL1 sparse (diamond corners), L2 shrinks, ElasticNet both
SVMmax margin; kernel trick; C trades margin vs errors
Treessplit by Gini/entropy; high variance alone
Bagging / RFreduce variance; OOB estimate
Boostingreduce bias; sequential residuals; lr × n_estimators
KNNscale features; curse of dimensionality
Naive Bayesindependence assumption; great for text
K-MeansK-Means++ init; spherical clusters; elbow / silhouette
DBSCANcore / border / noise; arbitrary shapes
GMMEM: E-step responsibilities, M-step params
PCASVD; variance explained; linear only
t-SNE / UMAPviz; t-SNE local only, UMAP keeps more global
Stackingout-of-fold predictions → meta learner
Check yourself 2 questions
  1. Which regulariser produces sparse weights?

    Show answer

    L1.

  2. 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#

MetricUse when
Accuracyuse when class balance and error costs make it meaningful; add class-wise metrics
Precisionfalse positives costly (spam)
Recallfalse negatives costly (fraud, cancer)
F1balance P/R on imbalance
ROC-AUCranking, balanced-ish
PR-AUCheavy imbalance
Log-loss / Brier / ECEprobability quality, calibration
MAE / RMSE / MAPEregression; RMSE punishes large errors
NDCG / MAP / MRRranking & retrieval
BLEU / ROUGE / BERTScoregeneration (weak); LLM-as-judge
Check yourself 2 questions
  1. Fraud detection favours which metric?

    Show answer

    Recall (false negatives are costly).

  2. 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
  1. Validation scheme for time series?

    Show answer

    Walk-forward (rolling or expanding).

  2. 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
  1. Why split before any fitting?

    Show answer

    To prevent leakage of test statistics.

  2. 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
  1. Why not fit_transform on the test set?

    Show answer

    It re-learns statistics from test data; use transform only.

  2. 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#

AlgorithmHow it learnsKey hyperparametersStrengthsWatch out
Linear regressionMinimise squared error; closed form (XᵀX)⁻¹Xᵀy or gradient descentRegularisation α (ridge, lasso)Fast, interpretable coefficientsAssumes linearity; outliers and collinearity distort coefficients
Logistic regressionSigmoid of a linear score; minimise log loss (convex)C (inverse regularisation), penalty, class_weightCalibrated probabilities, strong baselineNeeds scaling and feature engineering for non-linear boundaries
Decision treeGreedy splits that maximise impurity reductionmax_depth, min_samples_leaf, ccp_alphaHandles mixed types and interactions, readableHigh variance; overfits without limits
Random forestBagging of deep trees on bootstrap samples with random feature subsetsn_estimators, max_features, max_depthRobust, little tuning, OOB estimateLarge models; weak at extrapolation
Gradient boostingAdds shallow trees that fit the negative gradient of the losslearning_rate × n_estimators, depth or num_leaves, subsample, regularisationBest accuracy on most tabular dataOverfits with high learning rate; needs early stopping
SVMMaximise the margin; kernels map to higher dimensions implicitlyC, kernel, γ (RBF)Strong on small, high-dimensional dataO(n²)–O(n³) training; no native probabilities
k-nearest neighboursNo training; vote or average over the k closest pointsk, distance metric, weightingSimple, non-parametricSlow prediction; needs scaling; curse of dimensionality
Naive BayesBayes rule assuming features independent given the classSmoothing α, variant (multinomial, Gaussian, Bernoulli)Very fast, good text baselinePoorly calibrated when features correlate
k-meansAlternate: assign to nearest centroid, recompute centroidsk, init (k-means++), n_initFast, scalableSpherical, similar-size clusters only; sensitive to scale and outliers
DBSCANGrow clusters from dense core pointseps, min_samplesArbitrary shapes, labels noiseOne density for all clusters; eps hard to pick
Gaussian mixture (EM)E-step: soft assignments; M-step: update means, covariances, weightsComponents, covariance typeSoft clustering, density estimateLocal optima; choose k with BIC
PCAEigenvectors of the covariance matrix (via SVD)Components or variance to keepCompression, decorrelation, denoisingLinear only; scale features first
t-SNE / UMAPPreserve local neighbourhoods in 2–3 dimensionsPerplexity / n_neighbors, min_distVisualisation of clustersDistances between clusters aren't meaningful; not for features
Isolation forestRandom splits isolate anomalies in fewer stepsn_estimators, contaminationUnsupervised anomaly scores at scaleThreshold needs labels or an alert budget
Check yourself 2 questions
  1. Linear regression closed form?

    Show answer

    (XᵀX)⁻¹Xᵀy.

  2. 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#

LibraryDistinctive ideaUse when
XGBoostSecond-order (gradient + Hessian) objective with explicit regularisation; sparsity-aware splits; histogram modeGeneral default, mature tooling
LightGBMLeaf-wise growth, histogram binning, GOSS sampling and exclusive feature bundlingLarge datasets, speed; limit num_leaves and min_data_in_leaf to avoid overfitting
CatBoostOrdered boosting and ordered target statistics for categoricals; symmetric treesMany high-cardinality categorical features, little tuning time
Bagging vs boosting: bagging averages independent high-variance models (lower variance); boosting chains weak learners that correct each other (lower bias).
Check yourself 2 questions
  1. Which library excels with categorical features?

    Show answer

    CatBoost.

  2. 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(S) = 1 − Σ pₖ²Entropy(S) = − Σ pₖ log₂ pₖGain = Impurity(parent) − Σ (|child| / |parent|) · Impurity(child)Regression: choose the split that most reduces variance (MSE)
  • 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
  1. Gini impurity formula?

    Show answer

    1 − Σ pₖ².

  2. 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 typeTechniquesPitfall
NumericStandardise for linear models and neural nets; log or Box-Cox for skew; clip outliers; bin for monotone effectsFitting the scaler on all data leaks test statistics
Categorical (low cardinality)One-hot; ordinal only if order is realUnseen categories at serving: handle_unknown or an "other" bucket
Categorical (high cardinality)Target encoding (out-of-fold, smoothed), frequency encoding, hashing trick, learned embeddingsIn-fold target encoding leaks the label
Date and timeHour, weekday, holidays; cyclical sin/cos; time since last event; lags and rolling windowsRolling features must use only past data (point-in-time)
TextTF-IDF, n-grams, pretrained embeddings, length and keyword flagsVocabulary fitted on the full corpus leaks
Aggregates and interactionsPer-user and per-item counts, rates and recency; feature crossesAggregates computed after the prediction time
Missing valuesImpute (median, mode, model) plus a missing-indicator column; trees can handle NaN nativelyMissingness itself can be predictive; don't drop it blindly
Feature selectionFilter (mutual information, correlation), wrapper (recursive elimination), embedded (L1, tree importance), permutation importance on validationSelecting features on the full dataset before CV inflates scores
Check yourself 2 questions
  1. Pitfall when scaling numeric features?

    Show answer

    Fitting the scaler on all data leaks test information.

  2. 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#

MethodScopeNote
CoefficientsGlobalOnly comparable on scaled features; unstable with collinearity
Permutation importanceGlobalModel-agnostic; correlated features share and hide importance
SHAPLocal and globalAdditive attributions with game-theory guarantees; TreeSHAP is exact and fast for tree models
LIMELocalFits a simple surrogate around one prediction; results vary between runs
Partial dependence / ICEGlobal / per-instanceShows how predictions change with one feature; misleading when features correlate
CounterfactualsLocal"What would need to change for approval?"; good for user-facing explanations
Regulated domains: prefer inherently interpretable models or monotonic constraints, and log the explanation shown with each decision.
Check yourself 2 questions
  1. Weakness of permutation importance?

    Show answer

    Correlated features share and hide importance.

  2. 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
  1. Equal opportunity means?

    Show answer

    Equal true-positive rates across groups.

  2. 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 riskWhat it isTrade-off
Differential privacyAdd calibrated noise so one person's data barely changes the output; DP-SGD clips per-example gradients and adds noisePrivacy budget ε vs accuracy
Federated learningTrain on devices, send only model updates (FedAvg), combine with secure aggregationNon-IID data, communication cost, updates can still leak without DP
PII handlingMinimise, pseudonymise, redact from logs and prompts, encrypt at restLess data for debugging
Membership inferenceAttacker tests whether a record was in the training setOverfit models leak more; DP and regularisation help
Training-data extractionLLMs can regurgitate memorised textDeduplicate training data, filter outputs
Right to erasureRemove a person's data on requestRetraining or machine unlearning is costly; keep data lineage
Check yourself 2 questions
  1. How does DP-SGD protect privacy?

    Show answer

    Clips per-example gradients and adds noise.

  2. 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#

ApproachIdea
Labelling guidelines + agreementClear rules with examples; measure inter-annotator agreement (Cohen's κ) and resolve disagreements
Active learningLabel the examples the model is least sure about (uncertainty sampling, query by committee)
Weak supervisionCombine noisy labelling functions (rules, heuristics) into probabilistic labels
Semi-supervisedPseudo-label confident unlabelled data; consistency regularisation (FixMatch)
Self-supervised pretrainingLearn representations from unlabelled data, then fine-tune on few labels
LLM-assisted labellingUse an LLM as a first-pass labeller, audit samples with humans
Noisy labelsFind likely mislabels with confident learning or loss-based filtering
Check yourself 2 questions
  1. What does active learning label?

    Show answer

    The examples the model is most uncertain about.

  2. 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#

ModalityAugmentations
ImagesFlips, crops, colour jitter, RandAugment, mixup, cutmix
TextBack-translation, synonym swaps, paraphrasing with an LLM
AudioSpecAugment masks, background noise, speed and pitch shifts
TabularSMOTE or noise for the minority class (inside CV folds only)
Time seriesWindow slicing, jitter, scaling, time warping
Rule: augment only training data, and only with transformations that keep the label true.
Check yourself 2 questions
  1. Text augmentation via translation?

    Show answer

    Back-translation.

  2. 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
  1. Why do isolation forests work?

    Show answer

    Anomalies are isolated with fewer random splits.

  2. 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#

TopicKey points
BaselinesLast value, seasonal naive; anything fancier must beat them
StatisticalARIMA/SARIMA, exponential smoothing (ETS), Prophet for trend + seasonality + holidays
ML on featuresGradient boosting on lags, rolling stats, calendar features; one model across many series
Deep and foundationDeepAR (probabilistic), N-BEATS, Temporal Fusion Transformer, pretrained models (Chronos, TimesFM)
MetricsMAE, RMSE; scale-free MASE or WAPE across series; quantile loss for intervals
ValidationRolling-origin backtests with a gap equal to the forecast horizon
HierarchiesForecast at several levels (store, region) and reconcile so they add up
Check yourself 2 questions
  1. Baselines every forecast must beat?

    Show answer

    Last value and seasonal naive.

  2. 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#

TopicRemember
BackpropdL/dW = xᵀδ; sigmoid′ ≤ 0.25 → vanishing
ResidualsH(x)=F(x)+x gives a +1 gradient path
Explodingclip by norm (1.0)
InitHe 2/n_in (ReLU), Xavier (tanh), GPT std 0.02, residual 1/√(2L), LSTM forget bias 1
ActivationsReLU (dying), GELU, SiLU, SwiGLU in LLM FFN
LossCE, focal (imbalance), label smoothing, InfoNCE, triplet, Huber
OptimisersSGD+momentum, Adam, AdamW (decoupled WD), Lion
LRwarmup + cosine; OneCycle; grad accumulation
NormBatchNorm (CNN), LayerNorm / RMSNorm (Transformers), pre-norm stable
Mixed precisionbf16 no scaler; fp16 needs GradScaler
Memorygradient checkpointing trades compute for memory
Check yourself 2 questions
  1. Why do residual connections help?

    Show answer

    They give a +1 gradient path through the identity.

  2. 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#

ArchKey idea
CNNlocality + weight sharing; ResNet skips; EfficientNet scaling
RNN / LSTM / GRUgates; cell state = gradient highway
Attentionsoftmax(QKᵀ/√d_k)V; √d_k keeps softmax unsaturated
Transformerattn + FFN + residual + norm; enc (BERT), dec (GPT), enc-dec (T5)
Positionalsinusoidal, learned, RoPE, ALiBi
MHA → GQA → MQAfewer KV heads → smaller KV cache
FlashAttentionIO-aware tiling, online softmax; exact
MoErouter top-k experts; load-balancing loss
Mamba / SSMlinear-time selective state
GNNmessage passing uses relational structure; check neighbor leakage and compare to simpler baselines
Self-supervised / contrastivelearn reusable representations from unlabeled data; measure transfer on held-out tasks
Multimodalencoders + fusion/cross-attention; align modalities and score each modality slice
Scaling lawsChinchilla 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
  1. Why divide attention scores by √d_k?

    Show answer

    To keep softmax from saturating.

  2. 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-layer p.grad.norm()
  • Clip grads; lower LR; check inputs/labels; bf16 over fp16
  • Transfer learning: freeze backbone → partial unfreeze → discriminative LRs
Check yourself 2 questions
  1. Order of calls in a training step?

    Show answer

    zero_grad, forward, loss, backward, step.

  2. 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#

FamilyKey
Autoencoderbottleneck; denoising / sparse variants
VAEELBO = recon − KL; reparam z = μ + εσ; posterior collapse; β-VAE
GANmin_G max_D; mode collapse; WGAN-GP; 1-step sampling
Diffusionpredict noise (L_simple); stable regression training
DDPM / DDIMstochastic T steps / deterministic fewer steps
CFGguidance scale = fidelity ↔ diversity dial
Latent diffusiondiffuse in VAE latent (Stable Diffusion)
Flowsexact likelihood; coupling layers (RealNVP)
Flow matchingregress velocity; rectified flow (SD3, FLUX)
Consistency1–4 step sampling via distillation
Check yourself 2 questions
  1. VAE objective?

    Show answer

    ELBO = reconstruction − KL.

  2. Classic GAN failure mode?

    Show answer

    Mode collapse.

Takeaway Autoencoders, VAEs, GANs, flows, diffusion and autoregressive models trade quality, speed and stability.

Training troubleshooting#

SymptomLikely causesFixes
Loss doesn't decreaseLearning rate too low or high, bug in labels or loss, frozen layersOverfit one small batch first; LR range test; check label alignment
Loss becomes NaNExploding gradients, log(0), fp16 overflow, bad input valuesGradient clipping, lower LR, bf16, epsilon in logs, validate inputs
Train good, validation badOverfitting, leakage in train only, distribution shiftMore data or augmentation, regularisation, early stopping; recheck the split
Both train and validation badUnderfitting, weak features, too much regularisationBigger model, train longer, better features, less dropout
Validation better than trainDropout and augmentation only active in training, easy validation setUsually fine; confirm the validation set is representative
Sudden loss spikesBad batches, LR too high late in training, instability at scaleWarmup, lower peak LR, skip bad batches, check data
GPU out of memoryBatch or sequence too large, activations storedSmaller micro-batch + gradient accumulation, checkpointing, mixed precision
GPU underutilisedData loading bottleneck, small batches, CPU preprocessingMore loader workers, pinned memory, prefetching, larger batches
Great offline, poor onlineTraining–serving skew, stale features, feedback loopsShared feature code, log served features, shadow tests
Check yourself 2 questions
  1. First debugging step when loss won't decrease?

    Show answer

    Overfit one small batch.

  2. 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 / topicKey ideas
FunnelCandidate generation (1000s) → ranking (100s) → re-ranking (diversity, business rules)
Collaborative filteringUser–item matrix; item-item similarity; matrix factorisation (ALS, SGD)
Two-tower retrievalUser and item encoders; dot product; ANN index; in-batch negatives
Ranking modelsGBDT, Wide & Deep, DLRM, DCN-v2, DIN (attention over history), multi-task (click + watch time)
Cold startContent features, popularity priors, onboarding questions, exploration
Feedback loopsPosition and popularity bias; log propensities; exploration traffic
MetricsOffline: Recall@k, NDCG, AUC, calibration. Online: CTR, dwell, retention, diversity
Check yourself 2 questions
  1. Three stages of the recommendation funnel?

    Show answer

    Candidate generation, ranking, re-ranking.

  2. 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#

TopicKey ideas
Lexical retrievalTF-IDF, BM25 (term saturation k₁, length norm b)
Semantic retrievalBi-encoders + ANN; hybrid with BM25 via reciprocal rank fusion
Re-rankingCross-encoders, LLM rerankers on top-k
Learning to rankPointwise (regression), pairwise (RankNet), listwise (LambdaMART, ListNet)
LabelsHuman graded relevance, clicks with position-bias correction
Query understandingSpell correction, expansion, intent classification, entity linking
Check yourself 2 questions
  1. BM25's two key parameters?

    Show answer

    k₁ (term saturation) and b (length normalisation).

  2. 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#

TaskApproach
Text representationBag of words/TF-IDF → word2vec/GloVe → contextual (BERT) → LLM embeddings
ClassificationTF-IDF + LR baseline; fine-tuned encoder; LLM zero/few-shot
NER / sequence labellingBIO tags; BiLSTM-CRF → BERT token classification
Summarisation, translationEncoder-decoder (T5, BART) or decoder LLMs; ROUGE/COMET + human eval
Question answeringExtractive (span prediction) vs generative + RAG
TokenisationBPE, WordPiece, Unigram/SentencePiece; byte-level avoids unknown tokens
Check yourself 2 questions
  1. Strong text classification baseline?

    Show answer

    TF-IDF + logistic regression.

  2. 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#

TaskModels / metrics
ClassificationResNet, EfficientNet, ConvNeXt, ViT; top-1/top-5 accuracy
DetectionFaster R-CNN (two-stage), YOLO / SSD (one-stage), DETR; mAP@IoU, NMS
SegmentationU-Net, Mask R-CNN, SAM (promptable); IoU, Dice
Vision-languageCLIP (contrastive image-text), VLMs (image encoder → projector → LLM)
GenerationLatent diffusion, DiT; FID, CLIP score
PracticalAugmentation (flip, crop, mixup, cutmix), transfer learning, class imbalance
Check yourself 2 questions
  1. One-stage versus two-stage detectors?

    Show answer

    YOLO/SSD (one-stage) versus Faster R-CNN (two-stage).

  2. 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
  1. ASR metric?

    Show answer

    Word error rate (WER).

  2. 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#

ConceptKey idea
MDPStates, actions, transitions, rewards, discount γ
Bellman equationV(s) = maxₐ [R + γ Σ P(s'|s,a) V(s')]
Q-learning / DQNOff-policy TD; replay buffer + target network
Policy gradientREINFORCE: ∇J = E[∇log π(a|s) · G]; high variance → baseline
Actor-critic, PPOAdvantage estimates; PPO clips the policy ratio for stable updates
Banditsε-greedy, UCB, Thompson sampling; contextual bandits for ads, recs
Offline RL / OPELearn from logs; importance sampling, doubly robust estimators
Check yourself 2 questions
  1. What do DQN's replay buffer and target network do?

    Show answer

    Stabilise off-policy TD learning.

  2. 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 -.-> RK
Check yourself 2 questions
  1. What does candidate generation use?

    Show answer

    Two-tower ANN, co-visitation or popularity.

  2. 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#

  1. Tokenise (BPE) → token IDs → embedding lookup (d_model).
  2. Pre-norm (RMSNorm) → masked self-attention with RoPE on Q and K.
  3. Residual add → pre-norm → FFN (SwiGLU, ~2.7–4× d_model hidden) or MoE layer.
  4. Residual add; repeat L layers.
  5. Final norm → LM head (often tied to embeddings) → logits → softmax → sample.
Causal mask lets token i attend only to ≤ i. Training is parallel over positions (teacher forcing); generation is sequential.
Check yourself 2 questions
  1. Where is RoPE applied?

    Show answer

    To Q and K inside attention.

  2. 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#

ChoiceOptions and why
Attention headsMHA → GQA (shared K/V per group) → MQA (one K/V); MLA compresses KV into a latent (DeepSeek)
PositionsAbsolute learned/sinusoidal → RoPE (relative, rotates Q/K) → ALiBi (linear bias)
Long contextRoPE scaling (position interpolation, NTK, YaRN), sliding-window attention, ring/sequence parallel attention
NormPost-LN (original) → pre-LN (stable deep training) → RMSNorm (cheaper)
FFNReLU/GELU → SwiGLU (better quality per FLOP)
MoERouter picks top-k experts per token; more parameters at same compute; load-balancing loss, expert parallelism
Efficient attentionFlashAttention (exact, IO-aware), linear attention, state-space hybrids (Mamba, Jamba)
Encoder vs decoderEncoder (BERT) for embeddings/classification; decoder (GPT) for generation; enc-dec (T5) for seq2seq
Check yourself 2 questions
  1. What does GQA do?

    Show answer

    Shares K/V heads across groups of query heads to shrink the KV cache.

  2. 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#

MethodBehaviour
GreedyArgmax each step; deterministic; can loop
Beam searchKeep top-B sequences; good for translation, bland for chat
TemperatureDivide logits by T; T<1 sharper, T>1 more random
Top-kSample among k most likely tokens
Top-p (nucleus)Smallest set with cumulative prob ≥ p
Min-pKeep tokens ≥ min_p × top prob; adapts to confidence
Repetition / frequency penaltyDown-weight already used tokens
Constrained / structuredGrammar or JSON-schema masks logits; guarantees valid output
Speculative decodingDraft model proposes, target verifies in one pass; same output distribution
Check yourself 2 questions
  1. Temperature below 1 does what?

    Show answer

    Sharpens the distribution: more deterministic.

  2. 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
  1. How does BPE build its vocabulary?

    Show answer

    By repeatedly merging the most frequent pair.

  2. 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#

TechniqueIdea
Chain-of-thoughtGenerate intermediate steps before the answer; more tokens = more compute per problem
Self-consistency / best-of-NSample many solutions; majority vote or pick with a verifier
Process vs outcome reward modelsScore each step vs only the final answer
RL with verifiable rewards (RLVR)Reward from unit tests or exact-match maths answers; trains long reasoning
GRPOPPO variant without a value network: advantages relative to a group of samples for the same prompt
Search at inferenceTree search / MCTS over reasoning steps with a verifier
Thinking budgetsCap or scale reasoning tokens per request; trade latency and cost for accuracy
Distilling reasoningFine-tune small models on long reasoning traces from a strong model
Check yourself 2 questions
  1. Self-consistency?

    Show answer

    Sample many solutions and take the majority answer.

  2. 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
  1. What does the KV cache store?

    Show answer

    Keys and values of past tokens for fast decoding.

  2. 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
  1. What follows SFT?

    Show answer

    Alignment: RLHF or DPO.

  2. 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#

MethodWhen / note
Pretrainingnext-token objective; curate/deduplicate data, tokenize and pack sequences, track contamination
SFTinstruction/task behavior; quality and coverage matter more than a universal example count
LoRA / QLoRAlow-rank adapters; QLoRA = 4-bit base + LoRA
RLHFreward model + PPO; frontier exploration; costly
DPOpreference pairs, no RM; cheaper & stable
RLAIF / ConstitutionalAI feedback against principles
Distillationbig teacher → small student (Phi story)
Evaluation gatesheld-out task suite, safety/red-team, human review; prevent train/test contamination
Synthetic dataSelf-Instruct, rejection sampling, exec-verified code; audit quality and distribution shift
Check yourself 2 questions
  1. DPO versus RLHF?

    Show answer

    DPO optimises preferences directly without a reward model or RL loop.

  2. What matters most in SFT data?

    Show answer

    Quality and coverage.

Takeaway Pretraining for knowledge, SFT for behaviour, preference optimisation for alignment.

Prompting & agents#

TechniqueIdea
CoTthink step by step; self-consistency = vote over samples
ReActThought → Action → Observation loop
Reflectionself-critique and retry
Tree of Thoughtsearch over reasoning branches
Tool useJSON schema; validate args; timeouts
Memoryin-context, short-term store, long-term semantic, structured state
Multi-agentorchestrator + workers, supervisor, debate, routing
Failure modeshallucinated calls, wrong args, cascades, infinite loops → budgets, HITL
DSPyoptimise prompts (BootstrapFewShot, MIPRO)
Check yourself 2 questions
  1. ReAct loop?

    Show answer

    Thought → Action → Observation.

  2. 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#

StageChoices
Chunking200–500 tokens, 15–25% overlap; semantic / structure-aware
Embedding768/1536 dims; 1536×4B ≈ 6 KB; 1M vectors ≈ 6 GB RAM
Retrievaldense + BM25 hybrid, RRF k=60
ANN indexHNSW (recall, RAM), IVF / IVF-PQ (compressed)
Querymulti-query, HyDE, step-back
Rerankcross-encoder on top-k (precision)
Contextlost-in-the-middle → best chunks at edges
AdvancedSelf-RAG, CRAG, GraphRAG
EvalRAGAS: faithfulness, answer relevance, context precision/recall
Check yourself 2 questions
  1. Typical chunk size and overlap?

    Show answer

    200–500 tokens with 15–25% overlap.

  2. 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
  1. What is HyDE?

    Show answer

    Generating a hypothetical answer to embed for retrieval.

  2. 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 dec
Check yourself 2 questions
  1. Needs private data: first choice?

    Show answer

    RAG.

  2. 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

  1. Retrieve, and stop early if nothing relevant scores above the threshold.
  2. Generate with an instruction to cite a passage for every claim.
  3. Verify each cited claim against its passage; drop or flag unsupported ones.
  4. Answer with citations, or abstain and hand off.
Check yourself 2 questions
  1. Name a detection method.

    Show answer

    Any of: self-consistency, SelfCheckGPT, NLI checks, FActScore.

  2. 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#

IndexHow it worksTuning knobsTrade-off
Flat (exact)Compare against every vector—Perfect recall; fine up to ~100K vectors
IVFCluster vectors (k-means); search only the nearest clustersnlist (clusters), nprobe (clusters searched)Higher nprobe = better recall, slower
PQ / IVF-PQSplit vectors into m sub-vectors and quantise each to a codebookm, bits per code10–50× less memory, some recall loss; rerank with full vectors
HNSWLayered proximity graph navigated greedily from the top layerM (links), efConstruction, efSearchBest recall/latency; high memory; deletes are awkward
DiskANN / ScaNNSSD-resident graphs / anisotropic quantisationBeam width, leaves searchedBillion-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
  1. Up to roughly what size is flat search fine?

    Show answer

    About 100K vectors.

  2. 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#

TechniqueSplitsNote
Data parallel (DDP)BatchFull model copy per GPU; all-reduce gradients
ZeRO-1 / 2 / 3, FSDPOptimizer states / + gradients / + parametersMemory scales down with GPU count; more communication
Tensor parallelEach matrix across GPUsNeeds NVLink; within a node
Pipeline parallelLayers across GPUsMicro-batches to fill bubbles
Sequence / context parallelSequence lengthLong-context training
Expert parallelMoE expertsAll-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
  1. What does ZeRO-3 / FSDP shard?

    Show answer

    Optimiser states, gradients and parameters.

  2. 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#

MethodHowNote
LoRAW' = W + (α/r)·BA, B∈ℝ^{d×r}, A∈ℝ^{r×k}r 8–64; train ~0.1–1% params; merge for zero overhead
QLoRA4-bit NF4 frozen base + LoRA; double quantisation; paged optimisersFine-tune 70B on one 48–80 GB GPU
DoRASplit weight into magnitude and direction; LoRA on directionCloser to full fine-tune quality
AdaptersSmall bottleneck layers insertedSlight inference latency
Prefix / prompt tuningLearned virtual tokensTiny; weaker on small models
Full fine-tuneAll weightsBest ceiling; catastrophic forgetting risk; most memory
Which target modules? Apply LoRA to all linear layers (q, k, v, o, gate, up, down) for best quality; attention-only is cheaper.
Check yourself 2 questions
  1. LoRA weight update?

    Show answer

    W' = W + (α/r)·BA with low-rank B and A.

  2. 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#

MethodNeedsIdea
RLHF (PPO)Reward model + value model + referenceMaximise reward − β·KL(policy ∥ reference)
DPOChosen/rejected pairsClosed-form: increase log-ratio of chosen over rejected vs reference
IPO / SimPO / ORPOPairsRegularised or reference-free DPO variants; ORPO merges SFT + preference
KTOSingle thumbs up/down labelsProspect-theory loss; no pairs needed
GRPO / RLVRVerifiable reward functionGroup-relative advantages; reasoning and code
RLAIF / Constitutional AIPrinciples + AI judgeAI-generated preference labels
Check yourself 2 questions
  1. What does RLHF need beyond preference data?

    Show answer

    A reward model, a value model and a reference policy.

  2. 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
  1. Does fine-tuning reliably add new facts?

    Show answer

    No; it changes how the model responds.

  2. 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
  1. What does pretraining optimise?

    Show answer

    Next-token prediction on huge text corpora.

  2. 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?#

Output not good enough
1Fixed by a better prompt or examples?
yes
Prompt engineering
no
2Missing or changing knowledge?
yes
RAG with citations
no
3Wrong format, tone or behaviour?
yes
SFT or LoRA on examples
no
4Need preferred answers, not just acceptable?
yes
DPO or preference tuning
no
5Too slow or expensive?
yes
Distil or quantise
no
Improve the evals first
Check yourself 2 questions
  1. Missing or changing knowledge?

    Show answer

    RAG with citations.

  2. 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#

PatternHow it worksUse when
Prompt chainingFixed sequence of LLM calls with checks betweenTask splits into clear steps
RoutingClassify input, send to a specialised prompt/modelDistinct categories; cost tiers
ParallelisationSectioning (subtasks) or voting (same task N times)Independent parts; need confidence
Orchestrator–workersLLM plans subtasks dynamically and delegatesUnknown number of steps (multi-file code edits, research)
Evaluator–optimiserGenerate → critique → revise loopClear quality criteria (translation, code review)
Autonomous agentLLM in a loop choosing tools until doneOpen-ended tasks; needs sandboxing, budgets, checkpoints
Rule: start with the simplest workflow that works; add autonomy only when it measurably helps.
Check yourself 2 questions
  1. When is routing appropriate?

    Show answer

    When inputs fall into distinct categories handled by specialised prompts or models.

  2. 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
  1. What makes a tool easy for a model to use?

    Show answer

    A clear name and description, JSON-schema args and concise structured results.

  2. 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)#

PieceMeaning
HostThe AI app (chat client, IDE, agent) that the user runs
ClientConnection the host keeps to one server
ServerExposes capabilities from a system (GitHub, DB, files)
ToolsModel-invoked actions with input schemas
ResourcesReadable context (files, records) the app can attach
PromptsReusable templates the user can pick
Transportsstdio (local) and streamable HTTP (remote, OAuth)
Why it matters: one integration works across many hosts (N+M instead of N×M connectors). Agent-to-agent protocols (A2A) cover agents calling other agents.
Check yourself 2 questions
  1. What's an MCP server?

    Show answer

    A process exposing a system's capabilities (tools, resources, prompts).

  2. 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
  1. Why put stable content first?

    Show answer

    Prefix caching reuses it across calls.

  2. 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#

  1. Role and goal; who the output is for.
  2. Context and constraints; what "good" looks like.
  3. Examples (few-shot), varied and representative.
  4. Output format: schema, XML tags, or JSON mode.
  5. Let the model reason before answering for hard tasks.
  6. Tell it what to do when unsure ("say you don't know").
  7. Version prompts; test them against an eval set like code.
Check yourself 2 questions
  1. How should few-shot examples be chosen?

    Show answer

    Varied and representative.

  2. 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)#

ToolStrength
LangGraphStateful graph workflows, checkpoints, human-in-the-loop
LlamaIndexData connectors, indexing and RAG pipelines
DSPyProgrammatic prompts optimised against a metric
Provider agent SDKsTool loops, handoffs, tracing with less glue code
CrewAI / AutoGenMulti-agent role-play and conversation patterns
Pydantic / InstructorTyped structured outputs with validation and retries
ObservabilityLangfuse, LangSmith, Phoenix, OpenTelemetry GenAI traces
ServingvLLM, SGLang, TensorRT-LLM, TGI, Ollama/llama.cpp (local)
Check yourself 2 questions
  1. Which framework optimises prompts against a metric?

    Show answer

    DSPy.

  2. 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
  1. What should happen before a risky action?

    Show answer

    Human approval.

  2. 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#

MethodUseWatch out
Golden test setRegression gate on every prompt/model changeKeep it fresh; avoid leaking into prompts
Reference-based metricsExact match, F1, BLEU/ROUGE, unit tests for codeMiss valid paraphrases
LLM-as-judgeScale qualitative grading with a rubricPosition, verbosity, self-preference bias; calibrate with humans
Pairwise preferenceA vs B comparisons; Elo-style rankingsNeeds many comparisons
RAG metricsContext precision/recall, faithfulness, answer relevanceEvaluate retrieval and generation separately
Agent metricsTask success, tool-call accuracy, steps, cost, trajectory reviewNon-determinism: run several trials (pass@k, pass^k)
OnlineThumbs, edits, escalation rate, A/B testsFeedback is sparse and biased
Check yourself 2 questions
  1. What's a golden test set used for?

    Show answer

    A regression gate on every prompt or model change.

  2. 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#

AreaBenchmarks
Knowledge / reasoningMMLU, MMLU-Pro, GPQA, ARC, HellaSwag, BIG-Bench Hard
MathsGSM8K, MATH, AIME
CodeHumanEval, MBPP, LiveCodeBench, SWE-bench (Verified)
Agents / toolsτ-bench, GAIA, WebArena, OSWorld, BFCL (function calling)
Instruction following / chatIFEval, MT-Bench, Chatbot Arena, AlpacaEval
Long contextNeedle-in-a-haystack, RULER, LongBench
Truthfulness / safetyTruthfulQA, HaluEval, HarmBench
Caveat: public benchmarks saturate and leak into training data. Your own task-specific eval matters most.
Check yourself 2 questions
  1. Name a coding benchmark.

    Show answer

    Any of: HumanEval, MBPP, LiveCodeBench, SWE-bench.

  2. 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
LLM01Prompt injection (direct and indirect via documents, web pages, tool results)
LLM02Sensitive information disclosure
LLM03Supply chain (models, datasets, plugins)
LLM04Data and model poisoning
LLM05Improper output handling (unsanitised output into SQL, shell, HTML)
LLM06Excessive agency (too many tools or permissions)
LLM07System prompt leakage
LLM08Vector and embedding weaknesses
LLM09Misinformation (hallucination, overreliance)
LLM10Unbounded consumption (cost and denial of service)
Check yourself 2 questions
  1. LLM01?

    Show answer

    Prompt injection (direct and indirect).

  2. 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
  1. How should tool and retrieved content be treated?

    Show answer

    As untrusted data, never instructions.

  2. 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#

PhaseBoundMetric
Prefill (whole prompt, parallel)compute-boundTTFT
Decode (one token / step)memory-bandwidth-boundTPOT / 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
  1. Which phase sets time to first token?

    Show answer

    Prefill.

  2. 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#

TechniqueIdea
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 offloadHBM → CPU DRAM → SSD → object store (LMCache, Dynamo KVBM)
KV quantisationfp8/int8 KV → more concurrent sequences
Response cache ≠ KV cacheapp-level exact prompt → answer vs engine-level attention state
Check yourself 2 questions
  1. What does PagedAttention borrow from operating systems?

    Show answer

    Virtual-memory-style fixed blocks with a block table.

  2. 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#

SymptomLever
GPU idle between requestscontinuous batching
long prompts spike everyonechunked prefill
prefill bursts starve decodedisaggregated serving (prefill / decode pools, NIXL KV transfer)
same system prompt reprocessedprefix caching
identical full requestsresponse cache
OOM under concurrencypaged KV + tiered offload
peer already has prefixKV-aware routing
model too big for 1 GPUtensor / pipeline parallelism
Check yourself 2 questions
  1. GPU idle between requests?

    Show answer

    Continuous batching.

  2. 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
  1. Where should tensor parallelism run?

    Show answer

    Within a node over NVLink.

  2. 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#

ItemValue
1 token≈ 0.75 words ≈ 4 chars
VRAM / 1B params (bf16)~2 GB
7–8B bf1614–16 GB → 1× A10G / L4 (24 GB)
70B bf16~140 GB → 2× A100-80GB
TTFT target< 1 s p95 (chat)
TPOT target20–50 ms (reading ≈ 200 ms/token)
Guardrail classifier< 20 ms; intent classifier < 10 ms
IDE completion< 100 ms
Semantic cachecos ≥ 0.92, ~40% hit (FAQ)
GPU scale trigger60–70% utilisation
Peak multiplier~12× avg (consumer)
Check yourself 2 questions
  1. VRAM for a 7–8B model in bf16?

    Show answer

    About 14–16 GB.

  2. 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
  1. First rung of the cost cascade?

    Show answer

    A semantic cache.

  2. 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#

StepDo
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 · Curveballshallucination, 10× traffic, vector DB OOM
Failure modeMitigation
HallucinationRAG grounding, low temp, abstain, self-check
Prompt injectioninput classifier, role isolation, sandboxed tools (MCP)
High TTFTsemantic cache, smaller model, spec decoding, batching
GPU OOMquantise, cap context, PagedAttention
Stale RAGevent-driven reindex, soft deletes

"Why?" rule: never name a tech without the reason + number.

Check yourself 2 questions
  1. What belongs in scoping?

    Show answer

    Interactive versus batch, QPS, TTFT/TPOT, cost per query, back-of-envelope tokens and GPUs.

  2. 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#

AreaKey
Deploymentshadow → canary → A/B; blue-green; rollback
ServingREST vs gRPC; dynamic batching; ONNX / TensorRT
Featuresonline (Redis) / offline store; point-in-time correctness; train-serve parity
StreamingKafka semantics; Flink windows + watermarks; Little's law
DataLambda vs Kappa; Parquet; Delta/Iceberg; medallion; data contracts
RegistryMLflow stages; champion/challenger; lineage; auto rollback
Monitoringdata drift (PSI) vs concept drift; latency P99; fallbacks
Diagnosissudden drop → pipeline bug; gradual → drift → retrain
Governancemodel cards, audit trails, GDPR erasure
Check yourself 2 questions
  1. Safe rollout order?

    Show answer

    Shadow → canary → A/B, with rollback.

  2. 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#

GroupChapters
RAG & searchsupport chatbot, enterprise semantic search, financial doc extraction, shopping assistant, multimodal asset search, legal contract review, advanced RAG platform
Agents & MCPresearch agent, text-to-SQL analyst, game NPC engine, multi-agent orchestrator, MCP tool platform
Fine-tune & promptcoding assistant, content pipeline, prompt engineering, fine-tuning
Real-time & edgemeeting summariser, voice agent, on-device LLMs
RegulatedAI tutor, healthcare triage, privacy & governance
LLMOpslifecycle, eval at scale, cost optimisation, observability & incidents
Check yourself 2 questions
  1. 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.

  2. 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 dec
Check yourself 2 questions
  1. What happens if the offline eval gate fails?

    Show answer

    Back to training.

  2. 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#

LevelWhat it looks likeTypical painNext step
0 · manualNotebook to pickle to a hand-deployed service; retrained "when someone remembers"No reproducibility, silent decay, deploy by one personScript the pipeline, track experiments, add a registry
1 · pipeline automationOrchestrated train → validate → register; continuous training on a schedule or trigger; feature storePipeline code itself is deployed by hand; tests thinCI/CD for the pipeline, not just the model
2 · CI/CD for pipelinesPipeline changes are tested, built and released like services; models promoted by gates; monitoring triggers retrainingPlatform cost and complexitySelf-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
  1. 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.

  2. 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
  1. Why does a feature store reduce training–serving skew?

    Show answer

    Both the offline and online stores are filled from the same feature definition.

  2. 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
  1. Why make pipeline tasks idempotent?

    Show answer

    So retries and backfills overwrite instead of duplicating.

  2. 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#

StageWhat runsGate
CI on every commitUnit tests for feature code and transforms, data-contract tests on a sample, a tiny training smoke runAll tests pass; lint and type checks
Continuous trainingThe full pipeline on fresh dataValidation checks pass
Offline evaluationMetrics on a frozen holdout and per-slice metrics against the current championBeats champion by a set margin, no slice regresses beyond tolerance
RegistryModel, signature, metrics, data and code versions stored (MLflow, SageMaker, Vertex)Stage moves: candidate → staging → production
DeployContainer build, load test, shadow, then canaryLatency, error and business metrics hold during canary
RollbackPrevious registry version re-servedOne 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
  1. What must a candidate model show at the offline gate?

    Show answer

    Beat the champion by a set margin with no important slice regressing.

  2. 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#

PatternWhenWatch-out
Batch scoringScores needed hours ahead (churn lists, nightly recommendations)Stale scores for new users; storage for every entity
Online, synchronousDecision inside a request (fraud, ranking), tens of msTail latency, feature-fetch latency, fallbacks when the model is down
StreamingScore events as they arrive (Kafka consumer)Ordering, exactly-once effects, back-pressure
On-device or edgePrivacy, offline use, zero network latencyModel 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
  1. When is batch scoring the right pattern?

    Show answer

    When predictions are needed hours ahead, like churn lists or nightly recommendations.

  2. 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
  1. 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.

  2. 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?#

A production metric dropped
1Did the pipeline, code or a dependency change recently?
yes
Roll back firstthen diff the change
no
2Are input features broken: nulls, schema, units, stale values?
yes
Data incidentfix the source, backfill, alert upstream
no
3Has the input distribution shifted (PSI or KS on key features)?
yes
Data driftretrain on recent data, check slices
no
4Do fresh labels show the input-output relationship changed?
yes
Concept driftretrain, revisit features or labels
no
Check the metric itselfseasonality, traffic mix, logging bugs
Check yourself 2 questions
  1. A metric drops right after a deploy. First move?

    Show answer

    Roll back first, then diff the change.

  2. 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#

LayerWatchTypical alert
ServiceLatency p50/p99, errors, throughput, saturationp99 over SLO for 5 minutes
Data qualitySchema, null and default rates, ranges, freshnessNull rate of a key feature doubles
Data driftPSI or KS on inputs, embedding driftPSI above 0.2 on a top feature
Prediction driftScore distribution, positive ratePositive rate leaves its weekly band
Model qualityAccuracy, calibration, per-slice metrics once labels arriveAUC down by a set margin vs last month
BusinessConversion, fraud loss, complaintsGuardrail 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
  1. PSI rule of thumb?

    Show answer

    Below 0.1 stable, 0.1–0.2 watch, above 0.2 investigate.

  2. 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
  1. Name the four things needed to reproduce a model.

    Show answer

    Code commit, data version, configuration and environment (image digest).

  2. 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#

LeverTypical savingTrade-off
Right-size instances, raise GPU utilisation with batchingOften 30–60%Some added latency
Spot or preemptible for training and batch60–90% off on-demandCheckpoint and retry logic
Quantise or distil the model2–4× cheaper servingSmall quality loss to measure
Cache repeated predictions or promptsLarge for skewed trafficStaleness and invalidation
Autoscale by queue depth, scale down at nightProportional to idle timeCold starts
Retrain on a trigger, not a fixed daily cronFewer runsNeeds 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
  1. What does spot capacity require to be safe for training?

    Show answer

    Checkpointing and retry logic.

  2. 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#

  1. 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.
  2. 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.
  3. 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.
  4. 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
  1. What fixed the UTC versus local-time skew?

    Show answer

    One feature definition plus an online–offline parity test.

  2. 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#

QuestionStrong 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
  1. 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.

  2. 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)#

  1. Clarify the product goal, users, scale, latency budget, constraints.
  2. Frame as an ML task: input, output, label; is ML even needed?
  3. Metrics: offline (AUC, NDCG) tied to online (CTR, revenue, retention) + guardrails.
  4. Data: sources, labels (explicit, implicit, human), sampling, leakage, privacy.
  5. Features: user, item, context, cross features; freshness; feature store.
  6. Model: baseline → stronger model; justify by data size and latency.
  7. Serving: batch vs online; candidate retrieval → ranking; caching; fallbacks.
  8. Evaluate: offline replay, A/B test, interleaving.
  9. Monitor and iterate: drift, feedback loops, retraining cadence.
Check yourself 2 questions
  1. What should offline metrics be tied to?

    Show answer

    Online business metrics such as CTR or retention.

  2. 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
  1. What's training–serving skew?

    Show answer

    Features computed differently online than in training.

  2. 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#

PromptLabel / objectiveKey featuresModel and servingGotcha
Feed rankingMulti-task: click, like, dwell, hideAuthor affinity, recency, content embeddingsRetrieval + DNN ranker, weighted scoreEngagement bait; diversity re-rank
Ads CTR predictionClick (calibrated probability)Sparse IDs, user history, contextLogistic regression → DCN/DLRM; online learningCalibration matters for auction bids
Video recommendationsWatch time, satisfaction surveysWatch history sequence, co-watchTwo-tower retrieval + rankerClickbait; freshness for new uploads
Search rankingGraded relevance, clicksQuery-doc text match, BM25, popularityHybrid retrieval + LambdaMART / cross-encoderPosition bias in click labels
Fraud detectionChargebacks (delayed)Velocity, device, graph links, amountsGBDT + rules; real-time scoring < 100 msExtreme imbalance; adversarial drift
ETA predictionActual arrival timeRoute segments, traffic, time, weatherGBDT / GNN on road graphAsymmetric cost of under-estimates
Spam / abuse classificationReports, reviewer labelsText, sender reputation, behaviourFine-tuned encoder + rules; human review queueAdversaries adapt; precision at high recall
People you may knowConnection acceptedMutual friends, graph proximityGraph candidate gen + rankerPrivacy and sensitive connections
Dynamic pricingConversion and revenueDemand, supply, competitor priceDemand model + optimiser; banditsFairness, regulation, feedback loops
Visual / product searchSame or similar itemImage + text embeddingsCLIP-style encoder + ANN indexIndex freshness; near-duplicates
Check yourself 2 questions
  1. Feed ranking objective?

    Show answer

    Multi-task: click, like, dwell, hide, combined with weights.

  2. 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
  1. Why a multi-stage funnel?

    Show answer

    Expensive models can only score hundreds of candidates in time.

  2. 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
  1. Latency budget for fraud scoring?

    Show answer

    Under about 100 ms, synchronous.

  2. 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
  1. How are permissions enforced?

    Show answer

    Filter retrieval by the user's access rights.

  2. 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.

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
  1. Best-case complexity of alpha-beta?

    Show answer

    O(b^(d/2)).

  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
  1. What does the Viterbi algorithm find?

    Show answer

    The most likely hidden state path.

  2. 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#

QuestionAnswer
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 PMThe 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
  1. Why scale attention by √d_k?

    Show answer

    Dot products grow with dimension; scaling keeps softmax out of saturated regions.

  2. 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
  1. Why subtract the max before exp?

    Show answer

    To avoid overflow without changing the result.

  2. 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
  1. Gradient of logistic loss with respect to w?

    Show answer

    Xᵀ(p − y) ÷ n (plus the L2 term).

  2. 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
  1. Two alternating steps of k-means?

    Show answer

    Assign to nearest centroid; recompute centroids as means.

  2. 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
  1. How is the causal mask applied?

    Show answer

    Set scores above the diagonal to −∞ before softmax.

  2. 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
  1. What does ROC-AUC mean probabilistically?

    Show answer

    P(random positive scores above random negative), ties counting half.

  2. 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
  1. Which tokens survive top-p?

    Show answer

    The smallest set whose cumulative probability reaches p.

  2. 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
  1. Metric for imbalanced classification?

    Show answer

    PR-AUC or F1.

  2. 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.

No cards match. Try fewer or different words, or press Esc to clear.