Learn Machine Learning Engineering

How data becomes a model that keeps working after it ships. Thirty-nine modules, from what one training example represents to diagnosing a production incident without blindly retraining.

ProblemTargetDataRepresentationSplitModelTrainingEvaluationValidationDeploymentInferenceMonitoringDriftRetraining

ML Fundamentals

6 lessons

What a machine learning system actually is — a pipeline from raw data to feedback — and the sixteen things that go wrong in it, most of which are invisible offline.

What ML Engineering Is

Not "which algorithm". Turning data into a system that learns useful patterns, generalises, serves predictions and stays measurable after it ships — and knowing which neighbouring domain owns each thing it depends on.

Q · A team has a notebook with a good model in it. What is the distance between that notebook and a system the business can rely on, and which of it is ML engineering's job?
The ML Pipeline
▶ lab

Raw data → dataset → features → split → model → training → evaluation → artifact → deployment → inference → feedback. Eleven stages, each a place an assumption enters, and the loop back is what makes it a system rather than a script.

Q · What are the stages between an event happening in the world and a model influencing the next such event, and what does each stage decide that the model can no longer change?
What Can Go Wrong
▶ lab

Sixteen failure classes, each entering at a specific pipeline stage, most invisible to the offline metric. Learning to name them by stage is the difference between debugging a model and retraining it in the dark.

Q · The model was fine at approval and is wrong in production. Which of the sixteen ways this happens entered at which stage, and which signal would have shown it?
Learning vs Programming

A program encodes rules someone wrote. A model encodes patterns from data it was shown — and therefore inherits the data's biases, gaps and timing. The model is a set of assumptions with weights attached.

Q · What is actually different about a component whose behaviour was learned from data rather than written as rules, and what does that difference do to testing, review and change?
The ML Reasoning Loop
▶ lab

Problem → Target → Data → Representation → Split → Model → Training → Evaluation → Validation → Deployment → Inference → Monitoring → Drift → Retraining. Fourteen questions in order, and the order is the method.

Q · Given any ML problem, incident or number, what is the sequence of questions that locates it, and why does skipping an early one invalidate every later answer?
Don't Delegate Understanding

Libraries hide optimisation, AutoML hides search, feature stores hide synchronisation, model servers hide inference, cloud platforms hide infrastructure, foundation models hide training. Use all of them — and know what each one is hiding when it breaks.

Q · Every layer of ML tooling hides something on purpose. Which things must the engineer still understand about a model they did not write, and what does "Model Accuracy = 94%" need before it means anything?

Problem Formulation

7 lessons

Start from the decision, not the model. What event to predict, when the prediction must exist, what action follows, what each mistake costs, and whether labels can be observed at all.

Problem Formulation
▶ lab

"Users are cancelling subscriptions" is a situation, not a task. Six questions turn it into Input X → Model → Prediction ŷ → Decision, and each one skipped is a model that answers something nobody asked.

Q · Someone says "users are cancelling subscriptions, can we predict it?" What has to be decided before that sentence becomes a modelling task, and in what order?
Decision Before Model
▶ lab

The model exists to change a decision. Name the decision, its owner, its capacity and its moment first, and most model choices — target, features, metric, threshold, inference mode — are made for you.

Q · Why does naming the decision before the model fix so many later choices, and what happens to a model built for a decision nobody named?
Prediction vs Decision

`P(churn) = 0.78` is a prediction. "Offer a retention discount?" is a decision. The model produces the first; a threshold, a cost and a policy turn it into the second, and none of those three lives in the model.

Q · The model outputs a probability. What has to happen between that number and the action the business takes, and why must those steps be designed and owned separately from the model?
Target Definition

The target must encode the outcome you actually care about, at a horizon, from a moment. `churned = cancelled within 30 days of the snapshot` is a target; `churned` is not.

Q · What makes a target definition precise enough to build a dataset from, and how does an imprecise one produce a model that is correct about the wrong thing?
Label Construction

Labels are built, not found. A versioned, tested query over raw events, parameterised by the snapshot moment and the horizon, is the difference between a label and a column that happened to be there.

Q · How do you turn a target definition into a label table that is correct for every (entity, snapshot) pair, reproducible later, and provably free of information from after the snapshot?
Label Leakage

A feature that carries the answer — `cancelled_at` used to predict `will_cancel` — gives excellent offline metrics and an invalid model. Leakage is about when information exists, not which columns are forbidden.

Q · How does information from the label reach the features, why does the offline evaluation reward it, and how do you tell a leaked feature from a legitimately predictive one?
When Not to Use ML
▶ lab

A rule works; labels cannot be observed; the decision cannot use a probability; a wrong prediction has unbounded cost; the data does not exist at prediction time. Any one of these is a reason to stop, and the formulation is where you find out.

Q · Which properties of a problem make a learned model the wrong tool even when a good model could be trained, and how do you recognise each one before building it?

Learning Paradigms

6 lessons

Supervised, unsupervised, semi-supervised and self-supervised — distinguished by where the learning signal comes from, and by what each can and cannot promise.

Supervised Learning

A labelled target turns learning into function fitting. The model is only as right as the label, and the label was made by a process nobody wrote down.

Q · When someone hands you a table with a target column, what exactly has the model been told to learn — and who decided it?
Unsupervised Learning

No labels, so no loss against the truth. The model finds structure in whatever the features and the distance say — and nobody checked that those mean anything to the business.

Q · The data has no target column, so you want the model to "find the structure". Structure according to what, and how would you know it found the wrong one?
Semi-Supervised Learning

A few thousand labels and a few million unlabelled rows. The unlabelled data helps exactly when it comes from the same distribution as the labels — and that is the thing you cannot check with labels.

Q · Labels are scarce and unlabelled data is abundant. Under what conditions does the unlabelled data make the model better rather than more confidently wrong?
Self-Supervised Learning

The data labels itself: hide part of it and predict it back. The signal is free and abundant, which is why it works — and why the model learns whatever the corpus contains, including what you did not want.

Q · If the model is trained to reconstruct its own input, what has it learned, and why would that help with a task the pretext never mentioned?
The Learning Signal

Every paradigm is defined by where the gradient's target comes from. That source decides what the model can be wrong about without anyone noticing.

Q · If you strip away the algorithms, what actually distinguishes supervised, unsupervised, semi-supervised and self-supervised — and what does that tell you to monitor?
Choosing a Paradigm
▶ lab

Have labels? Can you get them? What do they cost, and how long until they arrive? What does "structure" mean to the business? The paradigm is the answer to those questions, not a preference.

Q · A team wants to "use ML" on a new problem. Which questions about labels, cost and business meaning decide whether it is supervised, unsupervised, semi-supervised or self-supervised — and when is the answer none of them?

Task Types

6 lessons

Regression, classification, ranking, clustering, dimensionality reduction and anomaly detection — what each one outputs, and why a visually separated cluster is not a business segment.

Regression

The output is a number. The loss decides which errors that number is allowed to make, and the business rarely agrees with squared error about which errors are expensive.

Q · The model outputs a continuous value. Which errors is it trained to avoid, and are those the errors that cost the business money?
Classification
▶ lab

The model outputs a probability; the product needs a decision. The threshold between them is where the business cost lives, and it is the part that gets defaulted to 0.5.

Q · The model outputs a category or a probability. How does that become an action, and which metric describes the action rather than the probability?
Ranking

The output is an order, judged by what sits at the top. The label is usually a click, which was produced by the previous ranking — so the model learns the old order as much as relevance.

Q · The product shows a list and the model decides the order. What is the label, where did it come from, and what does the model learn about positions that were never shown?
Clustering

k-means and hierarchical clustering find groups under a distance you chose. A visually separated cluster is a fact about the geometry, not about the business — until something external says otherwise.

Q · The algorithm returned clean groups. Under what distance, how stable are they, and what outside the algorithm says they mean anything?
Dimensionality Reduction
▶ lab

PCA keeps variance; UMAP and t-SNE keep neighbourhoods, approximately. Neither keeps meaning, and a 2D picture of a 300-dimensional space is a drawing, not a map.

Q · You projected a high-dimensional space to two dimensions and it looks structured. What did the projection keep, what did it throw away, and which of the things you see are artefacts?
Anomaly Detection

The model ranks how unusual each point is. Unusual is not the same as bad, positives are rare, and someone has to read the top of the list — so precision there is the whole product.

Q · Positives are rare and mostly unlabelled, and the model flags what is unusual. Anomalous relative to what, and who checks whether the top of the list is worth reading?

Dataset Construction

7 lessons

Filtering, joining, labelling and feature creation each introduce bias or leakage. What one training example represents, and how sampling decides what the model can learn.

Dataset Construction
▶ lab

Raw data becomes a dataset through filtering, joining, labelling and feature creation. Each stage is a decision, and each decision can introduce bias or leakage that no model can undo.

Q · The model is trained on "the data". Which pipeline produced that data, what did each stage decide, and where could the answer or a bias have entered?
What Is One Example?

One row is one user, or one transaction, or one user-day, or one query-document pair. Choosing the grain decides the snapshot date, the label window, and what counts as a duplicate.

Q · A row in the training set represents what, as of when, with a label observed over which window — and does the same entity appear more than once?
Sampling Strategies

Random, stratified, temporal and group-based sampling each preserve a different property of the population. Which property matters depends on what the model will meet in production.

Q · The full dataset is too large or too skewed to use as is. Which subset can be trained on without teaching the model a population that does not exist?
Selection Bias

The dataset only contains the cases that reached the step where the label was recorded. Approved loans have repayment labels; declined ones do not. The model learns about the selected, and is deployed on everyone.

Q · Which process decided that these rows have labels and those do not, and is the model going to be used on the rows that were never labelled?
Survivorship Bias

The table contains the customers, companies or machines that are still here. The ones that failed were deleted, archived or never joined, and the model learns what survivors look like.

Q · Who is missing from the table because they did not make it, and is the model being asked to predict the very thing that removed them?
Class Imbalance
▶ lab

When positives are one in a thousand, always predicting negative is almost perfectly accurate and completely useless. Imbalance decides the metric, the split, the threshold, and whether the probabilities can be trusted.

Q · Positives are rare. Which metric, split and threshold still say something about the decision, and what does rebalancing the training data do to the model's probabilities?
Label Quality

The label is the thing the model is trained to reproduce. Noisy, delayed, drifting, disputed or machine-generated labels put a ceiling on everything downstream, and the ceiling is invisible in the metric.

Q · Where did the labels come from, how wrong are they, when did they arrive, and has what they mean changed since the first row was labelled?

Data Splitting

6 lessons

Train, validation and test as three different jobs, and the split strategy — random, temporal, grouped, stratified — as the decision that decides whether the metric means anything.

Train / Validation / Test

Three sets with three jobs: learn parameters, choose between models, and estimate final performance once. The percentages are a consequence of the jobs, not a rule.

Q · Which decisions is each set allowed to inform, and how big does each need to be for the number it produces to mean anything?
Random Split

Shuffle the rows and cut. Correct when rows are independent and production looks like the training period. Wrong, and optimistic, whenever time or repeated entities are in the data.

Q · Are the rows independent of each other and of time, so that a shuffled cut resembles the data production will send?
Time-Based Split
▶ lab

Train on the past, validate on the future. The only split that measures the thing production actually asks for — how well the model generalises to a period it did not see.

Q · Production will score data from a period after training. Does the validation set come from after the training set, with a gap that matches the label delay?
Group Split
▶ lab

When the same entity appears in many rows, all of its rows go to one side of the split. Otherwise the model is evaluated on recognising entities it already saw, and production is full of entities it has not.

Q · Does the same user, patient, device or document appear in more than one row, and will production ask about entities the model has never seen?
Stratified Split

When positives are rare, a plain random cut can leave validation with too few of them to say anything. Stratifying fixes the class ratio per set so every fold holds a known number of positives.

Q · Are positives rare enough that a random cut could leave the validation set with too few to measure the metric, and which variable should the split hold fixed?
Choosing a Split Strategy

Four questions decide the split: is there time in the data, do entities recur, are positives rare, and will production see new entities or a new period? The answers compose into one strategy.

Q · Given what production will look like relative to the training data, which combination of time, group and stratified splitting makes the validation number mean what it claims?

Data Leakage

7 lessons

The deepest module. Target, temporal, entity, preprocessing, feature and evaluation leakage: every way information from the answer reaches the model, and why each makes offline metrics lie.

Data Leakage
▶ lab

Leakage is information from the answer reaching the model during training through a route that will not exist at prediction time. The offline metric improves; the product does not.

Q · Validation is excellent and production is mediocre, with no skew, no drift and no bug in the serving path. How does information from the label get into the features, and why does the evaluation not notice?
Target Leakage
▶ lab

A feature that is derived from, caused by, or written by the same process as the label. It looks like a column; it is the answer.

Q · A feature predicts the label almost perfectly on the training table. How do you tell whether you have found a strong signal or a copy of the answer?
Temporal Leakage
▶ lab

Information from after the prediction time reaches the features: a future timestamp, a window that crosses the snapshot, a random split of time-ordered data.

Q · The features are honest columns and none of them is the label. How can they still know the future, and why does a random split hide it?
Entity Leakage
▶ lab

The same user, patient or device appears on both sides of the split. The model memorises the entity, the evaluation rewards it, and production is full of strangers.

Q · Every feature is honest and every window is correct. Why does a random row split still overstate how the model will do on people it has never seen?
Preprocessing Leakage
▶ lab

A scaler, imputer, encoder or feature selector fitted on the full dataset before the split has seen the validation rows. The order of operations is the leak.

Q · No feature knows the future and no entity straddles the split. How can a normaliser leak, and why is the fix a matter of ordering rather than of columns?
Evaluation Leakage

The data is clean and the pipeline is ordered correctly. The leak is the engineer: tuning on the test set, peeking repeatedly, picking the best of many runs on one holdout.

Q · Every feature, split and preprocessing step is correct. How does the test number still become an overestimate, and why is the cause a process rather than a column?
The Leakage Audit

A checklist run on every feature before the offline number is believed: when is it computed, from what, is it available at prediction time, does it correlate suspiciously, is it near-perfect on a subgroup.

Q · The validation number is too good. What do you check, in what order, to find the leak before anyone commits to the number?

Feature Engineering

7 lessons

Aggregation, bucketing, normalisation, encoding, temporal and interaction features — each a transformation that must be reproduced identically at serving time.

Feature Engineering
▶ lab

A feature is a transformation from raw records to a number the model can use. It is learned from training data, and it has to be reproduced identically at serving time — which is where it usually breaks.

Q · The model is a function of its features, not of the raw data. What is a feature, who computes it, when, and what must be true for the same feature to exist in production?
Aggregation Features

Per-entity counts, sums, rates and recency over windows. They dominate tabular models, and they are the main source of train/serve skew because they depend on a clock, a source and a null policy at once.

Q · Why do a handful of windowed counts per entity outperform every other feature, and why are those same features the ones that break between training and serving?
Bucketing & Normalisation

Bucket edges, means and standard deviations are fitted on the training fold and shipped with the model. Refit them anywhere else and the model receives inputs from a transformation it never learned.

Q · Scaling and bucketing look like cleaning. Why are they part of the model, and what goes wrong when serving recomputes them?
Categorical Encoding

One-hot, ordinal and embedding encodings turn categories into numbers. Each has a vocabulary that was fitted on training data, an unseen-category policy, and a serving path that must apply both identically.

Q · A model consumes numbers. How does a category become one, what fitted state does that create, and what happens when production sends a category training never saw?
Target Encoding
▶ lab

Replace a category with the mean label for that category. Powerful on high-cardinality features, and a leak unless the rate for each row is computed without that row, out of fold, with a smoothed prior.

Q · Encoding a category as its label rate is the most effective trick for high-cardinality features. Why does the obvious version leak, and what does the out-of-fold version cost?
Temporal Features

Windows, lags, recency, calendar features and "as of" timestamps. Every one is anchored to a clock, and the rule is that the anchor is the prediction time and no window ends after it.

Q · Time is the axis along which features leak, skew and go stale. How do you build features from it that mean the same thing in training and serving?
Missing Data

Why a value is missing is information. Imputation is fitted on the training fold and shipped, the missingness indicator is often the better feature, and the null policy must be identical at serving.

Q · A null is not a value. What does its absence mean, how should the model see it, and what has to match between training and serving for the answer to hold?

Representation & Importance

5 lessons

Hand-engineered features against learned representations, feature selection, and importance methods — with the warning every one of them needs: importance is not causality.

Raw Features vs Learned Representations
▶ lab

Either a person decides what the model sees, or the model decides. Each choice hides something, and the learned one ships inside the artifact and must be versioned like weights.

Q · Should we hand-engineer the features or let the model learn its own representation from raw input — and what does each choice commit us to at serving time?
Feature Selection

Fewer features means fewer serving dependencies, less leakage surface, and a smaller lie when the selection is done outside the training fold — which is where it is usually done.

Q · We have four hundred candidate features. How do we decide which ones the model should use, without the selection itself contaminating the evaluation or leaving us with columns production cannot supply?
Feature Importance

Split gain, coefficients and every other model-specific importance answer one question: what does this model use? They do not answer what matters in the world, and unscaled coefficients do not even answer the first one.

Q · The model reports an importance for every feature. What does that number actually measure, why do two models on the same data disagree about it, and what is it safe to conclude from it?
Permutation Importance

Shuffle one column, re-score the model on held-out data, and the drop is what the deployed model depends on. Done on training data it measures memorisation; done one correlated feature at a time it splits the credit and hides the group.

Q · How do we measure what the deployed model actually depends on, in a way that does not reward leaked or high-cardinality features, and what does the method get wrong on correlated columns?
Attribution Is Not Causality

Every importance and attribution method describes how a model's output depends on its inputs. None describes what would happen if you changed the world. "X predicts Y" and "X causes Y" are different claims, and the business hears the second.

Q · The model says support tickets are the strongest predictor of churn and that discounts predict retention. Can we act on those as causes — and if not, what would it take to know?

Baselines

5 lessons

Rule, mean predictor, majority class, linear model, simple tree. Mandatory before anything complex, because a model that does not beat a useful baseline has not earned its cost.

Baselines Are Mandatory

A metric with nothing to compare it to is a number, not a result. Before anything complex: a rule, a constant predictor, a linear model, a shallow tree — and the question of whether the proposed model beats a useful one by enough to pay for itself.

Q · The model reports a strong validation metric. Compared to what — and what is the simplest thing that would have scored nearly as well?
The Rule Baseline

The heuristic the business already uses is the strongest baseline most models face, and the honest reason a model has to win by a margin: the rule is free to run, already trusted, and already in production.

Q · What does the rule the business runs today score on our holdout — and if we cannot say, what is the model being compared to?
Majority Class and Mean Predictor
▶ lab

The constant predictor is the floor of every metric. Under imbalance it wins accuracy without looking at a single feature, and for regression it defines R² = 0 — which is why scoring it first is how you find out whether the metric means anything.

Q · What does a predictor that ignores every feature score on our metric — and if that number looks good, what does it say about the metric?
The Linear Baseline

Logistic or linear regression as the first real model: cheap to fit, cheap to serve, readable, and the reference for everything after it. If the complex model cannot beat it clearly, the complexity is not earning anything.

Q · What does a regularised linear model on the same features score, and what does its distance from the complex model tell us about where the signal is?
Beating the Baseline
▶ lab

A comparison is only a comparison on the same split, the same metric, the same threshold policy, with an interval — and the margin has to be read against what the winner costs to serve. A small gain that costs a GPU and eighty milliseconds is a loss.

Q · The candidate beats the baseline. On what split, by which metric, at which threshold, with what uncertainty — and after the serving cost, is it still a win?

Linear Models

6 lessons

Linear and logistic regression as the models everything else is compared to: coefficients, residuals, the sigmoid, and the threshold that turns a probability into a decision.

Linear Regression

ŷ = w·x + b. A weight per feature, a bias, a loss that says which mistakes hurt — and a set of assumptions the weights only make sense under.

Q · A linear model gave a coefficient of 40 minutes per kilometre and an RMSE the team liked. What did the model actually assume, and what happens when the assumptions stop being true?
Residuals & Assumptions

The residual plot is the diagnostic; the single metric is the summary. Heteroscedasticity, extrapolation and unscaled coefficients are all visible there and invisible in the RMSE.

Q · The regression metric is acceptable and the coefficients look sensible. What does a residual plot show that the metric cannot, and which of the model's assumptions does it check?
Logistic Regression
▶ lab

Linear score → sigmoid → probability, trained by gradient descent on the log loss. The threshold that turns the probability into a decision is a different step, owned by someone else.

Q · What does a logistic regression actually compute, how is it trained, and why is "the model said yes" always two decisions dressed as one?
Sigmoid & Probability

The sigmoid turns a score into a number between 0 and 1. Whether that number is a probability is a fact about calibration on the deployment distribution, not about the function.

Q · The model output is 0.8. Under what conditions does that mean 80%, and what do class weights, resampling and a changed base rate do to it?
Thresholding
▶ lab

The threshold is not part of the model. It is the point where a business decision about costs and capacity is written down, and it deserves an owner, a config and a review.

Q · Who chose 0.5, against what cost, and what happens to the business when the score distribution moves and the constant does not?
Regularized Linear Models

L1 makes weights zero, L2 makes them small, elastic net does both — and all of them penalise a feature in proportion to its scale, so the scaler is part of the model.

Q · The linear model has hundreds of features and unstable coefficients between retrains. What does a penalty on the weights do, which penalty, and why does it only mean something after scaling?

Classification Metrics

7 lessons

The confusion matrix and everything derived from it — precision, recall, F1, ROC AUC, PR AUC, calibration — each with its business reading and the case where it misleads.

The Confusion Matrix
▶ lab

Four counts — TP, FN, FP, TN — and four business outcomes with four different prices. Every classification metric is a way of reading this table; read the table first.

Q · Before any metric, what did the classifier actually do to each of the four kinds of case, and what does each cell cost the business?
Precision, Recall & F1
▶ lab

Precision reads the flagged column: how many alarms were real. Recall reads the positive row: how many real cases were caught. F1 averages them as if the two mistakes cost the same, which they never do.

Q · Which of precision, recall and F1 corresponds to the complaint the business is making, and what does moving the threshold do to each?
Threshold Selection
▶ lab

Flag when P × cost_FN exceeds (1 − P) × cost_FP. The threshold falls out of the costs and the calibrated probability; 0.5 is what you get when the costs are equal and nobody checked.

Q · Why not always 0.5 — and given the costs, the prevalence and a calibrated probability, where should the threshold sit?
Accuracy Under Imbalance
▶ lab

When the positive class is one in a thousand, predicting "no" every time is 99.9% accurate. Accuracy measures the majority class; use the metrics that read the positive row and the flagged column.

Q · Why is a high accuracy on a rare-positive problem almost meaningless, and which numbers should replace it?
ROC AUC
▶ lab

The probability that a random positive scores above a random negative. A pure ranking metric — invariant to threshold, to prevalence, and therefore blind to the precision that prevalence destroys.

Q · What does ROC AUC actually measure, why does it look fine on rare-positive problems where the flagged set is mostly wrong, and when is it the right number?
PR AUC
▶ lab

Precision against recall across every threshold, and the area under it. It follows the positive class, so it falls when the flagged set fills with negatives — which is exactly what ROC AUC cannot see.

Q · What does the precision–recall curve show that the ROC curve hides, and why is its area the honest ranking summary when positives are rare?
Calibration
▶ lab

Does 0.8 mean 80%? The reliability curve answers it bin by bin. Calibration matters when the probability is multiplied by a value; it matters not at all for a pure ranking.

Q · When does it matter that the model's probabilities are true frequencies, how do you check, how do you fix it, and when can you ignore it?

Regression Metrics

4 lessons

MSE, RMSE, MAE, R² and the caveats on MAPE: what each punishes, what each hides, and how to choose one from the cost of being wrong.

MSE, RMSE and MAE
▶ lab

Squared error punishes a large miss quadratically and answers in squared units; RMSE restores the units but keeps the outlier sensitivity; MAE is the median-like metric that treats every unit of error the same.

Q · Two delivery-time models have nearly the same RMSE and very different MAE. Which one is better, and what does the difference in the two numbers tell you about how they miss?
R² (Coefficient of Determination)

R² is the fraction of variance the model explains relative to predicting the mean. It can be negative out of sample, it is not comparable across datasets, and a high value can describe a model that is useless for the decision.

Q · A vendor reports an R² of 0.9 for a demand model and your own model scores 0.6 on your data. Is theirs better, and what would it mean if yours went negative on next month's data?
MAPE and Its Caveats

Mean absolute percentage error reads naturally and fails badly: undefined at zero, dominated by small actuals, and asymmetric between over- and under-forecasting. On a demand forecast it blows up on exactly the low-volume items nobody was worried about.

Q · Your demand forecast reports a MAPE that looks poor, but the high-volume products — the ones that matter for revenue — are forecast well. Where is the number coming from, and what is it actually rewarding?
Choosing a Regression Metric

Derive the metric from the cost of being wrong: is a ten-unit miss the same on a hundred-unit item as on a ten-unit item, are large misses catastrophic or merely bad, and is the decision actually a threshold on the forecast — in which case it is classification in disguise.

Q · The team has tried MSE, MAE, R² and MAPE and each ranks the candidate models differently. Which questions about the business decide the metric, and when is the right answer that this is not a regression problem?

Evaluation

7 lessons

Business metrics against model metrics, offline against online, cross-validation and its temporal variant, slices — and the rule that the test set is touched once.

Business Metrics vs Model Metrics
▶ lab

A model metric describes the model; a business metric describes what happened when the model's output was acted on. The map between them is the operating point and the action, and a better model metric can produce a worse business outcome.

Q · The new fraud model has a clearly better AUC, and after rollout the fraud losses did not fall. What sits between the model metric and the business one, and which of them should decide the next release?
Offline vs Online Evaluation
▶ lab

Offline evaluation scores a model on a historical dataset produced by the previous policy. Online evaluation measures what happens when the model acts on live traffic. Strong offline numbers are a reason to run the online test, not a substitute for it.

Q · Offline, the new recommendation model beats the incumbent on every metric. What could make it worse in production, and what would you have to run to find out?
Cross-Validation
▶ lab

k-fold cross-validation trades k trainings for a lower-variance estimate and a spread. It is the right tool for small data and model selection, the wrong tool for temporal or grouped data unless the folds respect the structure, and it is not an evaluation of the model you will ship.

Q · With a few thousand labelled examples, a single holdout gives a metric that moves noticeably every time the split seed changes. When does k-fold fix that, when does it make things worse, and what does it cost?
Time-Series Validation
▶ lab

When the model will predict the future, validate on the future: forward-chaining folds, a gap between training end and validation start equal to the label delay, and never a shuffle. A random split on temporal data is a leakage simulator with a nicer name.

Q · A churn model validated with a random split looks excellent and degrades within a month of deployment. What did the split let the model see, and what does an honest temporal validation look like?
Evaluation Slices

An aggregate metric is a weighted average over subgroups, and the weights are the dataset's, not the business's. A model can improve on average and regress on the segment that matters, and only a sliced evaluation can see it.

Q · The new model is better overall and the complaints are up. Which subgroup got worse, why did the aggregate hide it, and what should the evaluation have reported instead?
Metric Uncertainty

A validation metric is a sample statistic with an interval around it. Two models compared on the same holdout need a paired comparison; a small test set cannot distinguish small improvements; and every comparison made against one holdout erodes it a little.

Q · The candidate beats the incumbent by a small margin on the holdout. Is that a real improvement, how would you know, and what has the holdout already been used for?
Never Tune on the Test Set
▶ lab

The test set is touched once. Every look costs information; hyperparameter search, feature selection, early stopping and model selection all happen on validation. A team that picks the best of forty runs on the test set has shipped noise with a certificate.

Q · Forty training runs, the best one chosen by its test-set score, and production well below that score. What did the test set stop being, and where should each of those forty decisions have been made?

Bias, Variance & Generalisation

6 lessons

Underfitting, overfitting, learning curves, regularisation and early stopping — the mechanics of why a model that memorised the training set looks perfect until it meets new data.

Bias and Variance
▶ lab

Every model is wrong in two ways at once: too simple to represent the pattern, or too flexible to ignore the noise. The gap between training and validation error tells you which.

Q · Two models both miss the target. One is systematically off in the same direction on every dataset, the other is right on average but swings wildly between training runs. Which one do you have, and what does that decide?
Overfitting
▶ lab

A model that memorises the noise in its training set scores perfectly on that set and poorly on the next one. Every route to a better training number is also a route to this.

Q · The training metric keeps improving as you add capacity, epochs and features, and the validation metric stopped improving a while ago. What has the model learned since then, and why does a leaked feature look like the opposite?
Underfitting
▶ lab

A model with too little capacity, or the wrong representation, misses structure that is plainly in the data. It is the honest failure — visible offline — and still the one most often fixed with the wrong tool.

Q · Training and validation error are both poor and nearly equal. More data does nothing. What is the model unable to express, and how do you know it is the model and not the labels?
Learning Curves
▶ lab

Error against training-set size, for training and validation together. The shape says whether more data, more capacity or better features is the fix — before any of them is tried.

Q · You can spend the next quarter labelling more data, or building a bigger model, or engineering features. Which one will move the validation number, and how can you know before spending it?
Regularisation
▶ lab

Every way of refusing part of the training fit: L1, L2, dropout, depth limits, shrinkage, early stopping. The strength is a hyperparameter, it is tuned on validation, and for the penalty forms the features must be on one scale.

Q · The model has more freedom than the data can constrain. How do you take some of it away without taking away the part that generalises, and how do you know how much to take?
Early Stopping
▶ lab

Stop training when validation loss stops improving, keep the best checkpoint, and accept that the validation set you stopped on is no longer an unbiased estimate of anything.

Q · Training loss is still falling. When do you stop, what do you keep, and what has the validation set become once it has decided that?

Trees & Ensembles

6 lessons

Decision trees, random forests and gradient boosting — how each learns, why boosting fits residuals, and XGBoost and LightGBM as implementations rather than as answers.

Decision Trees
▶ lab

A tree is a sequence of `feature < threshold?` questions ending in a constant. Readable, axis-aligned, piecewise flat — and incapable of predicting a value it has never seen.

Q · A decision tree is the most readable model there is. What does its shape let it express, what can it never express, and when does the readability stop being worth the limits?
How a Tree Chooses a Split
▶ lab

Gini, entropy or variance reduction score each candidate cut; the greedy search picks the best one at each node and recurses. Stopping rules are the only thing between that and a leaf per point.

Q · How does a tree decide which feature and which threshold to split on, why does growing it to completion memorise the data, and what does that imply for scaling and for categoricals?
Random Forests
▶ lab

Many deep trees, each on a bootstrap sample and a random feature subset, averaged. Variance falls because the trees disagree; the out-of-bag rows give a free validation estimate; the artifact is large.

Q · A single tree is high-variance. Why does averaging many of them help, why do the trees have to be different for it to work, and what does the ensemble cost at serving time?
Gradient Boosting

Fit a tree, compute the residuals, fit the next tree to them, repeat. Each tree follows the negative gradient of the loss; the learning rate shrinks each step; the number of trees is the capacity knob, chosen by early stopping.

Q · Boosting builds trees sequentially, each on the errors of the ensemble so far. Why is that a gradient descent, why does it overfit differently from a forest, and why does it find a leak before it finds anything else?
XGBoost and LightGBM as Implementations

Second-order gradients, a regularised objective, histogram binning, leaf-wise growth, native missing-value and categorical handling — what the fast implementations add to boosting, at the level of the mechanism and never the API.

Q · What do the production boosting libraries do that the textbook algorithm does not, and which of those choices changes how the model overfits, handles missing values or scales?
Tree Ensembles: When and When Not

A single tree, a forest, boosting and a linear model scored on quality, latency, cost, interpretability, data needed and operations — and the cases where boosting is the wrong answer even though it would win the benchmark.

Q · Boosting usually wins the offline tabular benchmark. When is it still the wrong model to ship, and what questions decide that before the benchmark is run?

k-NN, Naive Bayes & SVM

4 lessons

Three mental models, their assumptions, strengths and limits — taught as ways of thinking about data rather than as API calls.

Neural Networks

7 lessons

The neuron, activations, the forward pass, loss functions and backpropagation on a computational graph — the mechanism every deep learning framework hides.

Neural Networks
▶ lab

Input → linear layer → activation → hidden layers → output. A stack of learnable linear maps with nonlinearities between them, trained by gradient descent on a loss. Not always better.

Q · A network is a composition of linear maps and nonlinearities — what does that structure let it learn that a linear model cannot, and what does it demand in data, compute and monitoring in return?
The Neuron
▶ lab

z = w·x + b, then activation(z). One unit is a logistic regression; a layer is many of them sharing an input; the network is the same thing composed.

Q · A single unit computes a weighted sum, adds a bias, and applies a nonlinearity — what does each of the three parts do, and what does a unit assume about the scale of its inputs?
Activation Functions

ReLU, sigmoid, tanh, GELU. Nonlinearity is what stops a stack of linear layers collapsing into one; the choice decides which gradients survive the trip back.

Q · Why does a network need a nonlinearity between its layers at all, and how does the choice of activation decide whether the gradients reach the early layers?
The Forward Pass
▶ lab

Input → layers → prediction, as a sequence of matrix multiplications with a batch dimension. This is where the FLOPs go, and where inference cost is decided.

Q · A prediction is a chain of matrix multiplications — where does the compute go, what does the batch dimension change, and why does the same network cost so differently on different hardware?
Loss Functions
▶ lab

Prediction vs target → loss. MSE, binary and categorical cross-entropy, ranking losses. The loss is what the optimiser minimises; it is not the metric the business cares about, and the gap is the design.

Q · The optimiser minimises the loss, the business watches a metric, and the two are different functions — how is each common loss defined, what does it reward, and where does the proxy diverge from the objective?
Backpropagation
▶ lab

Forward pass → loss → backward pass → gradients → parameter update. The chain rule applied node by node, in reverse topological order, on the 2-2-1 network the lab runs.

Q · How does a network compute the gradient of one loss with respect to every parameter in a single backward sweep, and what can go wrong in that sweep that the loss curve will not show?
Computational Graphs
▶ lab

Nodes are operations, edges carry values forward and gradients backward. Reverse mode is cheap for many parameters and one loss, the framework builds the graph as you call it, and the activations it stores are the memory bill.

Q · Why does a framework record a graph of every operation, why is reverse mode the right direction for training, and why does the memory cost of training scale with the activations rather than the parameters?

Optimisation

7 lessons

Gradient descent, SGD, momentum and Adam; epochs, batches and steps; learning rate and batch size trade-offs; vanishing and exploding gradients; normalisation.

Gradient Descent
▶ lab

θ ← θ − η∇L. One update rule, one number that decides whether it crawls, converges or explodes. The learning rate is the single most important hyperparameter in deep learning.

Q · The loss curve is flat, or it jumps to NaN after a few hundred steps. Before touching the architecture or the data, what does the update rule itself predict about this behaviour?
Optimisers: SGD, Momentum, Adam
▶ lab

Three ways to decide what multiplies the gradient. None is universally best: Adam converges fast and sometimes generalises worse; SGD with momentum is still the default in much of vision; the choice interacts with the learning rate and with weight decay.

Q · A colleague says "just use Adam". Another says the vision team's models are all SGD with momentum and they generalise better. Who is right, and what would it take to know for this model?
Epoch, Batch, Step

An epoch is one pass over the data. A batch is the subset used for one gradient estimate. A step is one parameter update. "We trained for ten epochs" says nothing until you know the batch size.

Q · Two runs both "trained for ten epochs" and one is far better than the other. What is the unit of training actually being counted, and why is an epoch not it?
Batch Size and Learning Rate
▶ lab

Batch size trades memory, throughput and gradient noise against each other, and it moves the right learning rate with it. Larger batches want larger rates — up to a point — and small batches regularise for free.

Q · A bigger GPU arrived and the batch size was raised to fill it. Throughput doubled and the model got worse. What did the batch size change besides speed?
Vanishing and Exploding Gradients
▶ lab

Backpropagation multiplies one Jacobian per layer. A chain of factors below one shrinks the gradient to nothing by the early layers; a chain above one blows it up. Depth is hard to optimise for this reason, and every remedy attacks the product.

Q · The deep model trains worse than the shallow one it was supposed to improve on, and the early layers barely change. What is happening to the gradient on its way back?
Normalisation Layers

Batch norm normalises each feature over the batch; layer norm normalises each example over its features. The difference decides whether the layer behaves the same at training and inference — and batch norm does not, which makes it a train/serve skew source with a name.

Q · The model evaluated well in the training framework and behaves differently in the serving container, with identical weights. Which layer in the network has a different definition at inference time?
Initialisation and Convergence
▶ lab

Where the weights start decides whether training can begin; the warm-up and decay decide how it ends. A loss curve that plateaus, diverges or oscillates is a report on those choices, and a seed is not a reproducibility strategy.

Q · Two runs with the same config and different seeds ended far apart, and a third never left its starting loss. What did the initial weights and the schedule decide, and how much of the outcome is noise?

Embeddings

5 lessons

Discrete entities as dense vectors — words, users, products, documents — cosine similarity, and why a 2D projection distorts the geometry it claims to show.

Embeddings
▶ lab

A discrete entity — word, user, product, document — becomes a dense vector that is a parameter of some model, learned on a proxy task. The geometry encodes what that task rewarded, not "meaning".

Q · Two products sit close together in embedding space and a stakeholder asks whether that means they are "similar". Similar according to what, and who decided?
Embedding Training

Lookup tables as parameters, a contrastive signal from observed pairs against sampled negatives, and the consequence: rare entities get noise, and the table is part of the model artifact and must be versioned with it.

Q · What does the training signal for an embedding actually consist of, why does a rare entity end up with a meaningless vector, and what has to ship with the weights for the vectors to be usable?
Cosine Similarity
▶ lab

The dot product divided by the norms: the angle between two vectors, ignoring their length. Right when magnitude is noise, wrong when magnitude is signal — and at scale, nearest neighbours are an index problem, not a formula.

Q · The team switched the similarity function from cosine to Euclidean distance and the neighbours changed. Which one is right, and what does each throw away?
Embedding Projection Caveats
▶ lab

A 2D plot of high-dimensional vectors is a lossy projection. PCA keeps variance, not neighbourhoods; t-SNE and UMAP keep local structure and invent global structure. The clusters, distances and neighbours in the picture are not the ones the model uses.

Q · The projection shows two clean clusters and a stakeholder wants to act on them. What does the plot preserve from the space the model actually computes in, and what did it make up?
Embedding Drift
▶ lab

Retraining an embedding model produces a new coordinate system. Vectors stored from the old model are incompatible with it — a version mismatch, not a quality problem — and the vocabulary and the entities drift underneath as well.

Q · The embedding model was retrained and the stored vectors were left in place. What is now wrong, how would you detect it, and what does a safe rollout of a new embedding space look like?

Architectures

5 lessons

Convolutions for spatial structure, recurrent models for sequences, and transformers: tokens, embeddings, self-attention, positional information.

CNN Concepts

A convolution slides one small set of weights over the whole input. That weight sharing is a belief about the data — the same pattern matters wherever it appears — and it is the reason a CNN needs far fewer examples than a fully-connected net on pixels.

Q · A fully-connected network on raw pixels memorises the training images and fails on new ones. What does a convolution change, and what does it assume about the data?
Sequence Models

A recurrent network carries a hidden state step by step through a sequence; that is elegant and it is why long dependencies were hard. Transformers replaced the recurrence with attention so every position can be computed in parallel — and simpler models still win many forecasting problems.

Q · Recurrent networks read a sequence one step at a time. Why did that make long-range dependencies hard to learn, and what did transformers change about the computation?
Transformer Fundamentals
▶ lab

Tokens become embeddings, attention mixes information across positions, a feed-forward layer transforms each position on its own, and residual connections plus normalisation let dozens of those blocks stack. Knowing where the parameters and FLOPs live is what turns "use a transformer" into a cost you can budget.

Q · What does a transformer block actually compute, where do its parameters and FLOPs live, and why does the context length set the serving cost?
Self-Attention
▶ lab

Every token asks a question (query), every token advertises what it holds (key), and each token's new representation is a softmax-weighted mix of what the relevant tokens carry (value). The formula fits on one line; the weights it produces are a computation, not an explanation.

Q · How does a token decide which other tokens matter, what is the formula, and what can and cannot be read off the attention weights?
Positional Information

Attention is a weighted sum over a set: shuffle the tokens and it computes the same thing. Order has to be injected explicitly — learned, sinusoidal, relative or rotary — and the scheme you pick decides whether the model can say anything sensible past the lengths it was trained on.

Q · Attention treats its input as a set. How does a transformer know which token came first, and why does a model degrade on inputs longer than it was trained on?

Foundation Models & Fine-Tuning

5 lessons

Encoder and decoder families, pretrained models reused across tasks, transfer learning, fine-tuning and parameter-efficient adaptation — at the level of what changes and what it costs.

Encoder / Decoder Families

Encoder-only models turn text into a representation and are what you want for classification and embeddings; decoder-only models generate the next token; encoder–decoder models read one sequence and write another. Pick by what the output must be, not by which is newest.

Q · Encoder-only, decoder-only and encoder–decoder transformers exist side by side. What does each produce, and which one gives you the embeddings a retrieval system needs?
Foundation Models
▶ lab

A foundation model is pretrained once on broad data and reused across many tasks. "Pretrained" hides a training system you did not run, data you did not choose and an objective you did not pick — and what you inherit shows up as serving cost and as benchmark numbers that are not your task's numbers.

Q · What does "pretrained on broad data" actually give you, what does it hide, and why is a benchmark score not an evaluation of your system?
Transfer Learning

Pretrained model + task data → adapted model. The early layers carry structure that transfers; the late layers carry the old task. Freeze what transfers, train what does not, and expect the labelled-data requirement — and the split arithmetic — to change.

Q · You have a model pretrained on a large general dataset and a few thousand labelled examples of your task. What transfers, what must be relearned, and when is starting from scratch the better choice?
Fine-Tuning
▶ lab

Fine-tuning changes the weights with your labelled data; prompting and retrieval change the inputs and leave the weights alone. The first is an ML Engineering job with training, evaluation and a new artifact; the second is Agentic Engineering. Knowing which one you need is most of the decision.

Q · When does a task need the weights changed, how is that done without destroying what the pretrained model knew, and where is the line between fine-tuning and adapting the input instead?
Parameter-Efficient Fine-Tuning

Keep the base frozen, train a small number of new parameters — an adapter, a low-rank update to a few weight matrices — and ship the delta. Many task adapters can share one base in memory, which changes what an artifact is and what serving looks like; the price is a quality ceiling the base sets.

Q · How can a task be learned by training a tiny fraction of a model's parameters, what does that do to the artifact and to serving, and what quality does it give up?

Hyperparameter Tuning

5 lessons

Hyperparameters against learned parameters; grid, random and Bayesian search; the budget; and the rule that nothing is ever tuned on the test set.

Hyperparameters
▶ lab

Parameters are learned from the data. Hyperparameters are chosen before training, judged on validation, and belong in the experiment record — because they decide what the learning is allowed to do.

Q · Which knobs does the training procedure not set for itself, who sets them, on what evidence, and where does that decision get written down?
Grid Search and Random Search
▶ lab

Grid search is exhaustive and exponential. Random search covers each important setting better per trial, because most settings turn out not to matter. Neither is allowed anywhere near the test set.

Q · Given a budget of trials and a validation set, how should the trials be placed — and what does the best trial's score actually estimate?
Bayesian Optimisation, Successive Halving and Early Termination

When a trial costs hours, spend the trials sequentially: model the objective from the trials so far, choose the next one to balance exploration and exploitation, and kill trials that are clearly losing before they finish.

Q · When each trial is expensive, how does the search use what it has already learned to place the next trial — and to stop a trial that is not going to win?
The Tuning Budget

A search costs compute, time and validation-set credibility, and returns less with every trial. Tune the learning rate first, stop when the curve flattens, and remember that a fixed leak or a better feature usually beats any amount of tuning.

Q · How much should a hyperparameter search cost, what should it spend its first trials on, and when is the next trial worth less than the next feature?
AutoML Hides the Search

AutoML runs a search over pipelines and hyperparameters against a validation metric and hands you the winner. What it hides is the search space, the preprocessing leakage it may have committed inside the loop, the validation set it has now overfitted, and the serving cost of the pipeline it chose.

Q · When a tool searches over models and preprocessing for you, what did it search over, what did it leak, what did it overfit, and what will it cost to serve — and when is it fine not to ask?

Time Series

5 lessons

Forecasting, trend and seasonality, horizon, anomaly detection — and validation that respects time, because a random split on temporal data is leakage.

Forecasting

The target is a future value of the series you already have. Features are lags and windows that end at the forecast origin, the naive forecast is the baseline, and beating it is harder than it looks.

Q · When the thing to predict is the same series at a later time, what are the features, what is the baseline, and what does a model have to beat to be worth deploying?
Trend and Seasonality

Most series are a level, a trend, one or more seasonal cycles and calendar effects on top of noise. Model each explicitly or difference it away — and know that a model fitted to one regime is a bet that the trend continues.

Q · What are the components of a series, how does a model account for each, and what happens to a fitted model when the trend breaks?
The Forecast Horizon

One step ahead and twelve steps ahead are different problems with different errors. Direct and recursive strategies trade compounding error against training cost — and the horizon that matters is the one the decision needs.

Q · How far ahead does the decision need a forecast, how should a model produce a multi-step forecast, and how does error grow with distance from the origin?
Time-Series Anomaly Detection
▶ lab

Forecast the series, compare the actual to the forecast, and flag when the residual leaves a band. The band is a threshold with a false-alarm cost, the baseline must know about seasonality, labels are scarce, and an alert with no owner is noise.

Q · How do you flag that a series has done something it should not have, without paging someone every Monday morning — and what makes an alert worth sending?
Forecast Evaluation
▶ lab

Move the origin forward through time and score each forecast against what happened next; never shuffle. Report MAE or RMSE scaled against the naive forecast, per horizon and per segment — and treat MAPE with suspicion near zero.

Q · How do you produce a forecast error that predicts the error the forecast will have in production, and which error metric maps to the decision?

Recommendation Systems

7 lessons

Candidate generation and ranking, collaborative and content-based filtering, cold start — and feedback loops, where the model changes the data it will be trained on next.

Recommendation Systems

A recommender is a loop, not a model: events feed candidate generation, candidates are ranked, the ranking decides what users see, and what users see decides the next batch of events.

Q · What is a recommendation system made of, and why is its offline evaluation less trustworthy than a classifier's?
Collaborative Filtering
▶ lab

Learn from who interacted with what, with no item attributes at all — and inherit every bias in who was shown what, because the missing entries in the matrix are not negatives.

Q · How does a model recommend items using only interaction history, and what does it silently assume about the interactions it never saw?
Content-Based Recommendation

Recommend from what items and users are, not from who touched what. It works on day one for a new item and is limited to what the attributes can express.

Q · When should a recommender use item and user attributes instead of interactions, and what does an attribute-based model structurally miss?
Candidate Generation vs Ranking
▶ lab

Millions of items cannot be scored by a rich model inside a page-load budget. Retrieval narrows to hundreds with a cheap model; ranking orders them with an expensive one; each stage has its own metric and its own way to fail.

Q · Why is a recommender split into retrieval and ranking, how is the latency budget divided, and why do the two stages need different offline metrics?
Cold Start

A new user or item has no interaction history, so an interaction-trained model has nothing but noise for it. The answers are popularity, content, asking, and deliberately showing it — none of which is a better model.

Q · What does a recommender do for a user or item it has never seen, and why is the embedding of an unseen item not an answer?
Feedback Loops
▶ lab

The model decides what users see, what users see decides what they click, and what they click is the next training set. Retraining on that log does not correct the loop — it tightens it.

Q · How does a recommender shape its own training data, why does naive retraining make the bias worse, and what breaks the loop?
Exploration vs Exploitation

Showing the best-known item earns the most today and learns the least. Some exploration is the price of data you can trust — and in some domains that price cannot be paid.

Q · How much should a recommender show things it is unsure about, how do bandit strategies decide, and where is exploration unacceptable?

Experiments & Reproducibility

6 lessons

What every run must record, why random seeds alone do not reproduce anything, and versioning datasets, labels, features and models so lineage can be traced.

Experiment Tracking

Every run records the code, the data, the features, the configuration, the metrics, the artifacts and the environment. A number without that record is a claim nobody can check.

Q · What must be recorded about a training run for its metric to mean anything a month later?
Reproducibility
▶ lab

Same code, same data, same seed, different number. Reproducibility is a property of the entire environment — kernels, data order, library versions, reduction order across workers — and a seed pins only one of them.

Q · Why does a rerun with the same seed produce a different metric, and what has to be pinned for a training run to be reproducible?
Random Seeds

A seed fixes which random draws the code makes — the split, the initial weights, the shuffle, the dropout masks. Each is a different seed with a different effect, and the variance across them is a number a good comparison reports.

Q · What does a random seed actually control, which seeds matter for which decisions, and why should a metric be reported across several of them?
Dataset Versioning

A table name is not a version. A dataset the model trained on must be an immutable snapshot with an identifier that resolves to the same rows forever — or the run record points at nothing.

Q · How is a training dataset versioned so that a run record resolves to exactly the rows the model saw, and what breaks when the version is a name?
Feature and Model Versioning

A feature name is a contract whose definition changes; a model artifact is a file whose meaning depends on which definition it was trained against. The two versions must travel together, and a mismatch is a production failure with no error message.

Q · How are feature definitions and model artifacts versioned so that the model in production is always fed the features it was trained on?
Model Lineage
▶ lab

Raw data → Dataset v12 → Features v7 → Training Run 482 → Model v19 → Production. The graph that answers "which data did the production model learn from" during an incident, recorded by machines rather than remembered by people.

Q · When a production model misbehaves, how do you trace what it learned from, and what has to be recorded for that trace to exist?

Artifacts & Registry

5 lessons

What a model artifact contains, the registry lifecycle from candidate to archived, and promotion judged on quality, latency, memory, cost and robustness rather than one offline score.

What a Model Artifact Contains
▶ lab

A weights file alone is not a model. The artifact is parameters, architecture, fitted preprocessing, feature order, version and training metadata — and serving needs all of it.

Q · The training run finished and produced a file. What has to travel with that file for a serving process to reproduce the predictions the evaluation measured?
The Model Registry

The registry is a state machine over artifacts — Candidate, Registry, Staging, Production, Archived — that stores lineage, metrics, approvals and the feature-definition version, so "which model is live" has one answer.

Q · Three teams retrain the same model on different schedules. How does anyone know which artifact is in production, what it was trained on, and who approved it?
Promotion Is a Checklist, Not a Score
▶ lab

A challenger is promoted on quality, latency, memory, cost, robustness and — where relevant — fairness, compared against the champion on the same slice with the same threshold policy. One improved offline number is not a reason to ship.

Q · The retrained model has a better validation score than the one in production. What else has to be true before it replaces the champion?
Artifact Integrity

Hashes and signatures prove the bytes serving loads are the bytes that were evaluated. Deserialisation formats that execute code on load, and a serving process that loads the wrong file, are the two ways that proof gets skipped.

Q · Between the registry and the serving process the artifact is copied, cached and loaded. How do you know the file serving opened is the file that was promoted — and that opening it is safe?
Preprocessing Lives in the Artifact
▶ lab

The normaliser's means and standard deviations, the encoder's vocabulary, the imputation values, the feature order and the threshold are fitted on the training fold and ship with the weights. Recomputing any of them at serving time is a different model.

Q · The serving path has to turn a raw record into the tensor the model expects. Where do the numbers that transformation needs come from, and what happens if it computes them itself?

Inference Modes

7 lessons

Batch, online and streaming inference, how to choose between them from freshness, latency and volume, the serving architecture, batching, and CPU against GPU.

Batch Inference
▶ lab

Dataset → Model → Predictions, on a schedule. When the prediction can be precomputed, batch is the cheapest and most debuggable mode — and the staleness window is a property to design, not a defect.

Q · The product needs a prediction for every customer, but not right now. When can predictions be computed ahead of time, and what does the delay between scoring and use cost?
Online Inference
▶ lab

Request → Features → Model → Prediction → Response, inside a latency budget. The feature fetch is usually the latency, and the timeout and fallback are part of the model's quality, not an infrastructure detail.

Q · A prediction is needed inside a request that a user is waiting on. Where does the time go, and what is served when the model cannot answer in time?
Streaming Inference
▶ lab

Continuous events drive predictions: the model sits inside a stream processor, features are state kept per key, and ordering, late events and where the model sits in the topology decide correctness more than the weights do.

Q · Events arrive continuously and every one may change a prediction. When does the model belong inside the stream rather than behind an endpoint or in a nightly job — and what does the stream's semantics do to the prediction?
Choosing the Inference Mode
▶ lab

How fresh must the prediction be, can it be precomputed, does it need live features, what is the latency budget, what is the volume — those five questions decide batch, online, streaming or hybrid. Online is often unnecessary, and the churn case shows why.

Q · Before drawing the serving architecture: which questions decide whether predictions are computed in a nightly job, on request, on every event, or some combination?
Model Serving Architecture
▶ lab

Client → Backend → Model Service → Artifact → Prediction. Where preprocessing runs, model-in-process against model-as-service, versioned endpoints, warm-up and health checks — and the line where the Backend domain takes over.

Q · A prediction has to reach a user through a running system. Where does the model live, who owns the boxes around it, and what does the system have to do before a single request is safe to serve?
Inference Batching

Individual requests are grouped into a batch before the accelerator sees them. Throughput rises because the hardware runs one large matrix multiply instead of many small ones; latency rises because every request waits for the batch. Dynamic batching with a maximum wait is the knob.

Q · The accelerator is idle most of the time and the per-request cost is high. How does grouping requests change throughput and latency, and where is the trade-off set?
CPU or GPU for Inference

A workload decision: model size, available batch size, latency budget, cost per prediction and utilisation. A small tree model on CPU beats a GPU round-trip; a large transformer at volume does not fit on CPU. "GPU makes inference faster" is false as stated.

Q · The model is trained and needs hardware to serve it. Which questions decide whether an accelerator is worth its cost and its round-trip, and when does the CPU win outright?

Serving & Train/Serve Skew

7 lessons

Identical weights can fail if the features differ. Skew, feature stores as optional infrastructure, point-in-time correctness, freshness, latency breakdown and fallbacks.

Train / Serve Skew
▶ lab

The weights are identical in training and production. The features are not. A model can be exactly right about inputs it will never see again.

Q · The offline evaluation was strong, the artifact was promoted unchanged, and production quality is poor. What is different about the inputs?
Feature Stores
▶ lab

A feature store is optional infrastructure that makes one feature definition serve both training and low-latency inference, with lineage attached. It is one answer to skew, not a prerequisite for ML.

Q · Three teams compute "customer 30-day spend" three different ways and each ships a model on their own version. When is shared feature infrastructure worth its cost, and what does it actually guarantee?
Point-in-Time Correctness
▶ lab

A training example at time T may only use information that existed at T. The as-of join is how you build that, and the offline store exists to make it cheap.

Q · Our training set joins each event to the customer's "current" features. Which of those features existed when the event happened, and how do I build the join so the question cannot arise?
Feature Freshness
▶ lab

Features update in seconds, minutes, hours or days. The model was trained on values of a particular age, and the serving architecture must deliver the same age or the model is reading a different signal.

Q · How fresh do the features need to be, and does the serving path deliver the same freshness the training set had?
Latency Breakdown
▶ lab

A prediction request is parsing, feature fetch, preprocessing, model compute, postprocessing and network. The model is rarely the slow part for tabular systems, and almost always is for large networks.

Q · The prediction endpoint is over its latency budget. Which of the six stages is actually consuming it, and at p50 or at p99?
Throughput vs Latency
▶ lab

Throughput is predictions per unit time; latency is how long one waits. Batching raises the first by spending the second, and queue depth — not CPU — is the signal that says you are running out of both.

Q · We need more predictions per second without blowing the per-request latency budget. Which of batching, concurrency and autoscaling buys what, and what does each cost in latency?
Serving Fallbacks
▶ lab

When the model or its features are unavailable, the system must return something defined: the previous model, a rule, a cached score, a default ranking, or an explicit "no prediction". Which one is a product decision.

Q · The model server is down, or the feature store is slow. What does the endpoint return, who decided that, and does the caller know it happened?

GPUs & Efficiency

6 lessons

Parallel compute, matrix operations, memory bandwidth and VRAM; quantization from FP32 to INT8; pruning and distillation; and what inference actually costs.

GPU Fundamentals

A GPU is thousands of simple cores doing the same matrix arithmetic in lockstep. It is fast only when there is enough parallel work to fill it, which is why a single small request leaves it mostly idle.

Q · We moved inference to a GPU and per-request latency barely changed while cost went up. What is the GPU actually doing, and when does it help?
Memory Bandwidth & VRAM

What fits on the device is parameters times bytes per parameter, plus activations, plus — for training — optimizer state. What runs fast is bounded by how quickly those bytes can be read, and for large models every token reads all the weights.

Q · Will this model fit on the device, and once it fits, is inference bounded by arithmetic or by reading the weights?
Quantization

Storing weights in fewer bits — FP32 to FP16, BF16, INT8 — shrinks memory and speeds up memory-bound inference. The quality cost is real, concentrated on rare inputs, and only visible if you evaluate on the same slices you used before.

Q · The quantized model is half the size and passes the aggregate evaluation. Where would a quality loss hide, and how do I know it did not?
Model Compression

Quantization, pruning and distillation are three different bargains: fewer bits per weight, fewer weights, or a smaller model taught by the larger one. They trade quality, latency, cost and engineering effort differently, and can be combined.

Q · The model is too slow or too big for where it has to run. Which way of making it smaller fits this constraint, and what does each cost in quality and effort?
Pruning & Distillation

Pruning removes weights, and only speeds things up when it removes them in shapes the hardware can skip. Distillation trains a small model on a large model's outputs, and inherits everything the large model believed.

Q · The pruned model is ninety percent sparse and no faster; the distilled model is fast and wrong where the teacher was uncertain. What did each technique actually do?
Inference Cost
▶ lab

Cost per prediction is hardware cost per hour divided by predictions per hour, plus feature fetch and storage. Utilisation is the lever, and the first question is whether the prediction needs this model at all.

Q · What does one prediction actually cost, which term dominates, and which of the cheaper options — simpler model, batching, caching, quantization, fewer retrains — would move it?

Distributed Training

6 lessons

Data, model, tensor and pipeline parallelism, gradient synchronisation with all-reduce, checkpointing for recovery, and the cost of a training run.

Distributed Training

Splitting a training run across many devices buys compute and pays in coordination. It is needed when the data, the model or the calendar does not fit on one machine — and for most models it is neither needed nor free.

Q · The training run takes too long, or does not fit — when does spreading it across machines actually help, and what does the coordination cost?
Data Parallelism

Every worker holds the full model and a different shard of the data; each computes gradients on its shard and the gradients are averaged. It is the simplest split, and it silently multiplies the batch size.

Q · The model fits on one device and the data does not — how do several copies of the same model train as one, and what changes about the optimisation?
Model, Tensor & Pipeline Parallelism

When the model itself does not fit on one device, you cut the model rather than the data — across layers, inside matrix multiplies, or across the optimizer state. Every cut moves activations or weights over the wire, and the wire becomes the bottleneck.

Q · The model's weights, gradients and optimizer state exceed one device's memory — which way do you cut it, and what does each cut cost in communication?
Gradient Synchronisation
▶ lab

Workers agree on a gradient by all-reduce — a ring exchange that is bandwidth-optimal — and the choice between waiting for everyone and not waiting decides staleness, straggler exposure, and whether two runs can ever produce the same bits.

Q · N workers each have a gradient and all of them need the average — how does that exchange work, what happens when one worker is slow or dead, and why is the result never bit-identical between runs?
Checkpointing

A training checkpoint saves model weights, optimizer state, the step counter, the data position and the RNG state so a run can resume exactly where it died. It is not the model artifact, and a resume that does not restore all of it silently trains a different run.

Q · A long run will die before it finishes — what must be saved, how often, and what does resuming have to reproduce for the second half to be the same run as the first?
Training Cost
▶ lab

A training run costs GPU-hours, CPU-hours, storage, network and — the multiplier that dominates — the number of times you run it. A hyperparameter search turns one run's cost into a bill, and most of the questions that reduce it are not about the hardware.

Q · What does a training run actually cost, what multiplies that cost, and which questions should be asked before buying more GPUs?

ML Testing

7 lessons

A dedicated stack: data and feature tests, training smoke tests, model invariants, serving contracts, robustness — because a green unit test suite says nothing about a model.

The ML Testing Stack

Data tests, feature tests, training tests, model tests, serving tests, integration tests and drift tests — seven layers because a model can fail at every one of them while every unit test stays green.

Q · The unit tests pass and the model is wrong in production — which tests were missing, and where in the pipeline does each kind of test belong?
Data & Feature Tests
▶ lab

Schema, nulls, ranges, cardinality, target prevalence and distribution against the training reference — and the one test that catches most leakage: no feature timestamp may exceed its prediction time.

Q · What should be asserted about the training and serving data on every refresh, and which single assertion catches the failures that make offline metrics lie?
Training Smoke Tests
▶ lab

On a tiny dataset, in CI, in minutes: the pipeline runs end to end, the loss goes down, an artifact appears, and the model can memorise a handful of examples. A pipeline that cannot overfit ten rows is broken, whatever the full run reports.

Q · How do you test a training pipeline on every commit without running the training — and what does "the model can overfit ten examples" prove?
Model Invariant Tests
▶ lab

A probability is in [0, 1]. No output is NaN. A higher income does not lower a credit score. A change to an irrelevant field does not change the prediction. Invariants are the tests a model must pass regardless of its metric, and the ones a metric cannot express.

Q · What must be true of a model's outputs on inputs chosen to probe it — not on a held-out set — and how do you test behaviour that an aggregate metric would never reveal?
Serving Contract Tests
▶ lab

Request schema, preprocessing equivalence, model version, output schema, latency budget and fallback behaviour — the contract between the artifact and the request path, tested on every deploy, with a replay against the training path as the test that catches skew.

Q · What must be true of the path from a request to a prediction for the deployed artifact to be the model that was promoted — and how do you test it before traffic arrives?
Robustness Testing

Missing features, extreme values, noise, rare segments and corrupted inputs — the test is not whether the model stays accurate under damage but whether it does what the design says it should: degrade gracefully, refuse, or fall back.

Q · When the inputs are damaged — missing, extreme, noisy, corrupted, from a segment the model barely saw — what should the model do, what does it actually do, and how do you test the gap?
Model Regression Tests

A challenger with a better aggregate metric can still lose the cases the champion passes. A regression test holds the challenger to the champion's slices and to a golden set of known hard examples — and the golden set is a leakage risk the moment anyone trains on it.

Q · The challenger beats the champion on the validation metric — how do you check it has not quietly become worse on the slices and the specific cases the product depends on?

Fairness, Explainability & Causality

5 lessons

Subgroup performance with no universal fairness metric, explanations that are approximate, privacy as design, and the line between predicting Y and causing it.

Fairness
▶ lab

One aggregate number hides that a model can be a different model for different groups. There is no single fairness metric to optimise; choosing one is a policy decision, and several of them cannot all hold at once.

Q · The model's overall metric is fine. For whom is it fine, at what error rates, and who decided that those were the right error rates to equalise?
Explainability
▶ lab

An explanation describes the model, not the world, and describes a wrong model just as fluently. Know whether you need a global picture, a local reason or a counterfactual, and whether an interpretable model would make the question go away.

Q · A regulator or a customer wants to know why the model decided what it did. What can an explanation method actually tell them, and what does it only appear to tell them?
Causality vs Prediction

A model that predicts Y from X has learned that X and Y move together in data generated by an old policy. Acting on X to change Y is a different question, and usually needs an experiment rather than a model.

Q · The model says customers who receive a discount rarely churn. Should we give everyone a discount?
ML Privacy

A training set is personal data, an artifact can memorise it, and a prediction log is a record of people. Privacy is a design property of the pipeline — minimisation, retention, access, and honest limits on anonymisation.

Q · The model needs the data to learn and the logs to be monitored. What personal data does the system hold, where, for how long, and who can get it back out?
Human Oversight

A human in the loop is a threshold, a queue, and a source of labels. Decide where the human decides, size the queue from the threshold, watch for automation bias, and remember that overrides are training data — and biased training data.

Q · Where should a person make the decision instead of the model, and what happens to the model when the person's decisions become its next training set?

Monitoring & Drift

8 lessons

Data, feature, prediction and concept drift taught separately; drift that is not failure; ground truth that arrives weeks late; and performance decay diagnosed rather than assumed.

Model Monitoring
▶ lab

A model needs everything a service needs, plus three distributions a service does not have: features in, predictions out, and outcomes back. Four layers, each with an owner, each catching a different failure.

Q · The service is up, latency is fine, and nobody knows whether the model is still right. What does a deployed model need watched, and who watches each part?
Data Drift
▶ lab

The input distribution changed. A distance metric between the training reference and this week's traffic says so on the day; whether it matters depends on where the inputs moved to, and that needs the outcomes.

Q · The inputs the model receives no longer look like the inputs it was trained on. How do you measure that, and what does the measurement license you to conclude?
Feature Drift
▶ lab

One feature's distribution moved. Before it is drift it might be a bug: a null-rate spike, a unit change, a renamed category. Diagnose the pipeline first, because retraining on a broken feature teaches the model that broken is normal.

Q · A single feature's distribution changed this week. Is that the world, or the pipeline — and what happens if you retrain before you know?
Prediction Drift
▶ lab

The output distribution moved. It is the earliest model-level signal, needs no labels, and is the one that catches train/serve skew on rollout day — because the model reacts to its inputs immediately and to the truth never.

Q · The model's score distribution changed. What does that tell you on the day, before any outcome is known, and when is it the first thing you should look at?
Concept Drift
▶ lab

The relationship between features and outcome changed. The inputs did not move, so no input monitor fires; the scores did not move, so no prediction monitor fires. Only the outcomes reveal it, and they arrive late.

Q · Every feature distribution is stable, the prediction distribution is stable, and the model is now wrong. What changed, and what could have shown it?
Drift Is Not Failure
▶ lab

A distribution can change legitimately and the model can handle it. "Drift means retrain" retrains a working model on the strength of an input metric, costs a training run and a rollout, and answers a question the metric never asked.

Q · The drift alert fired. Before anyone touches the model: does the change actually hurt, and how would you know?
Ground-Truth Delay
▶ lab

The outcome arrives weeks or months after the prediction. Every quality number on the dashboard is about the past; the architecture has to say how far past, join outcomes back by id, and use proxies honestly in the meantime.

Q · The model's quality can only be measured once the outcomes exist, and they take a quarter to arrive. What does the monitoring show for this week, and how do you avoid being reassured by last quarter?
Performance Decay
▶ lab

Quality over time went down. Five different causes produce that chart, only one of them is fixed by retraining, and two are made worse by it. Diagnose in order — bug, product change, feedback loop, data drift, concept drift — before touching the model.

Q · Model quality has been falling for a month. Which of the five things that produce that chart is it, and what happens if you retrain before you know?

Retraining & Rollout

7 lessons

Retraining as a decision rather than a schedule, champion/challenger, shadow, canary, A/B — and rollback and fallback, which every serving system needs before it needs a second model.

Retraining as a Decision
▶ lab

Retraining is a change to a running system with a cost, a risk and a precondition. Four questions decide whether it is due; "drift" is not one of them.

Q · The drift monitor fired, the model is six weeks old and the team is asking whether to retrain. How do you decide, and what makes the answer "no"?
Retraining Strategies
▶ lab

Scheduled, drift-triggered, performance-triggered, manual and continuous: each is right for a particular ratio of label speed to world speed, and continuous training has risks the others do not.

Q · Which retraining trigger fits this system, and what does continuous training cost that a scheduled retrain with a human gate does not?
Champion / Challenger
▶ lab

A candidate earns production by beating the incumbent on the same traffic under the same threshold policy, on more than one number. A better validation score is a nomination, not a promotion.

Q · A retrained model scores better offline than the one in production. What comparison justifies replacing the incumbent, and why is the validation delta not it?
Shadow Deployment
▶ lab

The candidate scores production inputs but controls nothing. It catches skew, latency and crashes before a user sees them — and it cannot measure business impact, because it never makes a decision.

Q · What can a model running in shadow tell you that offline evaluation cannot, and what can it never tell you?
Canary Rollout
▶ lab

Give the candidate 1% of decisions, then 5%, 25%, 100%, watching quality, latency, cost and errors at each step — with the honesty that a 30-day label makes a 30-day canary.

Q · How do you roll a model out so that a mistake hurts a few users instead of all of them, and what do you watch at each step when the real outcome will not arrive for a month?
A/B Testing Models

The only measurement of business impact is to let two models decide for two comparable populations and compare what happens — with stable assignment, guardrails, enough sample, and honesty about interference and about the users in the experiment.

Q · Why is a live experiment the only way to know whether a model improved the business, and what makes such an experiment invalid?
Rollback & Fallback
▶ lab

When the model is wrong, go back; when the model is gone, degrade. Rollback must restore the feature definition with the artifact or it reintroduces skew, and the previous model has to be warm.

Q · A model deployment is hurting the product. How do you go back in one step, and what does the product do while there is no model at all?

ML Observability

5 lessons

Tracing one request through features, model version, prediction, decision and outcome; logging what is necessary and safe; and debugging an incident from the business metric down.

ML Observability
▶ lab

A healthy model server can serve a wrong model indefinitely. Observability for a model means tracing Request → Features → Model Version → Prediction → Decision → Outcome, and watching signals service health does not have.

Q · The serving dashboards are green and the model is wrong. What signals does a model need beyond service health, and how does one prediction get traced to its outcome?
Prediction Logging
▶ lab

The prediction log is the monitor's input, the incident's evidence, the outcome join's left side and the next training set. Log what is necessary, reference what is sensitive, and decide retention before the first row.

Q · What does each prediction record need to contain for monitoring, debugging and retraining, and what must it not contain?
Tracing a Prediction
▶ lab

One request id, from the click in the frontend through the backend, the feature service, the model server and the decision, to the outcome event weeks later. Each hop records something specific, and a hop that drops the id is where the next incident becomes a guess.

Q · What does each hop between a user action and an outcome record, and what becomes undiagnosable at the hop where the correlation id is lost?
ML Incident Debugging
▶ lab

Conversion fell after a deploy. Investigate from the business metric down — prediction distribution, model version, feature values, feature pipeline, raw data — in that order, and do not retrain until the cause has a name.

Q · The business metric dropped after a model deployment. In what order do you look, what does each layer rule out, and why is retraining before diagnosis the wrong move?
Model Postmortems
▶ lab

A model incident postmortem records the assumption that broke, the signal that should have fired, the label delay that hid it and the test now added — and never concludes that "the model" was at fault.

Q · What does a postmortem for a model incident have to record that a service postmortem does not, and why is "the model was wrong" never a root cause?

MLOps & Platforms

7 lessons

The practices that make ML reproducible, testable, deployable and observable — CI, CT and CD distinguished, platform capabilities, cloud primitives before vendors, cost.

What MLOps Is

Engineering practices and platform capabilities that make ML systems reproducible, testable, deployable, observable and maintainable. Not a product, and not a cluster.

Q · A team has three models in production that nobody can retrain without the original author. What is actually missing — and why is the answer not "adopt a platform"?
The MLOps Pipeline
▶ lab

Data → Validation → Training → Evaluation → Artifact → Registry → Deployment → Monitoring. Each stage has a way of failing that the next stage cannot see.

Q · A model went from raw data to production through eight stages. Which stage let the bad model through, and what would have stopped it there?
CI, CT and CD for ML
▶ lab

Three different loops with three different triggers. CI proves the code and data are sound; CT proves a new model can be trained; CD proves it is safe to serve. A green one proves only its own claim.

Q · The CI pipeline is green, the model retrained overnight, and the deployment succeeded. Which of those three facts says the model in production is good — and which questions does each one actually answer?
ML Platform Engineering

Shared capabilities — dataset access, feature pipelines, training jobs, tracking, registry, serving, monitoring, GPU scheduling — built once for many model teams. Premature before the third model.

Q · Four teams each built their own training and serving path. When does a shared ML platform pay for itself, what does it own, and where does its responsibility stop and the model team's begin?
Cloud ML Services

Every managed ML service is an implementation of a primitive you should already be able to name — a training job, a GPU, a registry, a hosted endpoint. Learn the primitive, then map the vendor.

Q · A cloud provider offers a managed training service, a model hosting service and a feature store. What is each one actually doing underneath, what does it hide, and what do you need to check before trusting it?
ML Orchestration

A DAG of data → features → train → evaluate → register → deploy, with scheduling, retries and backfills. The ML-specific hazards: a training step that is not idempotent, an evaluation gate, and artifact promotion as a step.

Q · The orchestrator retried a failed training step and the registry now holds two candidates from the same run. What about ML steps makes the standard orchestration assumptions wrong?
ML Cost Optimisation
▶ lab

Before buying cheaper GPUs, ask whether a simpler model works, whether training can happen less often, whether inference can be batched, quantized, cached or precomputed. Utilisation is the lever.

Q · The ML bill tripled and the first proposal is a cheaper GPU tier. Which questions come before that, and which number actually decides the bill?

ML Security

5 lessons

Poisoning, artifact integrity, sensitive-data leakage, adversarial inputs, supply chain and inference abuse — defensively, and at the level of what to validate and trust.

ML Security

Six ways an ML system is exposed that a service is not: poisoned training data, tampered artifacts, memorised sensitive data, adversarial inputs, an untrusted supply chain and abusable inference. Defensively, at the level of what to trust.

Q · A standard security review of the model service found nothing. What does an ML system expose that the review was not looking for?
Data Poisoning
▶ lab

A corrupt training source teaches the model wrong behaviour, and the offline metric — computed on the same corrupt data — approves. Provenance, validation, trusted pipelines and slice evaluation are the defence.

Q · A model retrained on data that users can influence started behaving strangely for one category. How does a corrupt source reach the weights, and what would have shown it?
Adversarial Inputs
▶ lab

Small, deliberate changes to a valid input flip the prediction. Defensively: validate content, test robustness, use ensembles and monitor confidence — and accept that fraud and spam are adversarial by nature.

Q · A valid-looking input produces a confidently wrong prediction, and slightly different versions of it produce the right one. What property of the model does that expose, and what defends against it without knowing the attack?
The Model Supply Chain

Pretrained weights and public datasets are dependencies: unpinned, unhashed, unsigned, and loaded by formats that execute code. Pin, hash, sign, use safe formats, and record provenance in the registry.

Q · A pretrained model was downloaded from a public hub, fine-tuned and deployed. What did the team just add to their dependency tree, and how would they know if it changed?
Inference Abuse

An endpoint that answers anyone reveals its decision function, its training data and its cost structure. Authenticate, rate-limit, return decisions rather than probabilities, and bound spend on GPU endpoints.

Q · A public prediction endpoint was built to be helpful: fast, unauthenticated, returning full probabilities. What can a caller learn or cost you by calling it a lot, and what do you withhold without breaking the product?

ML System Design

7 lessons

The questions to ask before drawing boxes, then recommendation, fraud, churn and search ranking designed end to end — and the boundary with Agentic Engineering.

ML System Design Architecture
▶ lab

Sources → data platform → features → training → registry → serving → application → monitoring. Eight boxes, five owning teams, and four interfaces that decide whether the system can be reasoned about at all.

Q · What are the boxes in an ML system, who owns each one, and what has to cross the boundaries between them for the whole thing to stay debuggable?
The Questions Before the Boxes
▶ lab

Ten questions — target, latency, batch or online, freshness, volume, label delay, model size, fallback, retraining, cost — each of which decides a part of the architecture before any model is chosen.

Q · Which questions have to be answered before an ML system can be designed, and what does each answer decide?
Designing a Recommendation System
▶ lab

Events → candidate generation → features and embeddings → ranking → serving → feedback. A two-stage latency budget, a loop in which the model writes its own training data, and an offline metric that measures agreement with the previous policy.

Q · How is a recommendation system designed end to end, and why can its offline ranking metric improve every quarter while the product gets worse?
Designing a Fraud Detection System
▶ lab

Rare positives, a strict online latency budget, asymmetric costs, an adversary who adapts to the model, and labels that arrive ninety days late. Every constraint in the domain at once.

Q · How is a fraud detection system designed when the positives are rare, the decision must be made in milliseconds, the labels arrive months later, and the people generating the positives are trying not to be caught?
Designing a Churn Prediction System
▶ lab

A weekly call list for a team of fixed capacity. Batch scoring, a threshold that is a queue size, labels a month late, explanations the callers can use — and a demonstration of why the online endpoint someone will propose is unnecessary.

Q · How is a churn prediction system designed around the decision it serves, and why is online inference the wrong default for it?
Designing Search Ranking
▶ lab

Query → candidate retrieval → ranking model → results. Lexical and embedding retrieval, learning-to-rank from click labels that carry position bias, NDCG-style evaluation at concept level, a latency budget per stage, and interleaving for the online test.

Q · How is a search ranking system designed so that click data trains a ranker without teaching it that whatever is at the top is what people want?
The Boundary With Agentic Engineering
▶ lab

ML Engineering owns the model: training, fine-tuning, evaluation, embeddings, inference, serving, drift, MLOps. Agentic Engineering owns what is built on top: prompting, RAG, tools, memory, agent architecture, agent evals. The line is where the depth lives, not where the LLM is.

Q · Where does Machine Learning Engineering end and Agentic Engineering begin, and which of the boundary cases — fine-tuning, prompt-tuning, embedding drift in a RAG system, retrieval evals — falls on which side?