Skip to content
ML to LLMs

Glossary and formula reference

Every term in plain English first, then formally, with a small example and the lesson that teaches it.

Activation

The nonlinear function a neuron applies to its weighted sum, so the network can bend its decision boundaries.

Formal: a=f(z)a = f(z) with z=w⋅x+bz = w\cdot x + b; common ff are ReLU, GELU, sigmoid, tanh.

Example: ReLU turns z=−1.5z = -1.5 into 0 and z=2z = 2 into 2.

Related: Logit, Softmax

Lesson: The forward pass

Advantage

How much better an action turned out than what was expected from that state.

Formal: A(s,a)=Q(s,a)−V(s)A(s, a) = Q(s, a) - V(s); estimated as Gt−V(st)G_t - V(s_t) (REINFORCE with a baseline), with GAE (PPO), or as a group-normalized reward (GRPO).

Example: An episode returns −2.71-2.71 from a cell whose baseline is −3.5-3.5, so the advantage is +0.79+0.79, and the actions taken become more likely.

Related: Policy gradient, Generalized advantage estimation

Lesson: Policy gradients and REINFORCE

Agent

A system that uses a model in a loop to plan, call tools, observe results, and decide what to do next.

Formal: A controller that alternates model calls and tool executions until a stop condition, under step, cost, and permission limits.

Example: A support agent looks up an order, checks the refund policy, and drafts a reply for human approval.

Related: Tool calling, Prompt injection

Lesson: Production architecture

Agent memory

How an agent keeps information beyond one model call: a small working set in the prompt, plus an external store it writes to and searches with tools.

Formal: Two tiers: a bounded main context (system prompt, editable core memory, recent messages) and an external store (archival notes, evicted messages), connected by memory tools whose results are appended to the next prompt.

Example: The agent saves "dog is named Miso" with archival_memory_insert; 30 turns later, after the message was evicted, archival_memory_search("dog") pages it back in.

Related: Context window, RAG, Tool calling

Lesson: Agent memory

All-gather

Every GPU shares its slice so all GPUs end with the full concatenated tensor.

Formal: Each rank contributes one chunk and receives the other N−1N - 1; it sends N−1NT\frac{N-1}{N}T bytes per rank. The second half of a ring all-reduce.

Example: FSDP all-gathers a layer's sharded weights just before computing that layer.

Related: Reduce-scatter, All-reduce, FSDP

Lesson: Collective operations from scratch

All-reduce

A group operation that leaves every GPU holding the sum (or average) of everyone's tensors.

Formal: A ring all-reduce is a reduce-scatter followed by an all-gather, 2(N−1)2(N-1) steps in total, and sends 2N−1NT2\frac{N-1}{N}T bytes per rank for a TT-byte tensor.

Example: Data-parallel training all-reduces gradients every step: 13.48 GB of bf16 gradients over 8 GPUs means 23.58 GB sent per GPU.

Related: Reduce-scatter, All-gather, Data parallelism

Lesson: Collective operations from scratch

Anomaly detection

Finding data points that don't fit the normal pattern, usually without labeled examples of the anomalies.

Formal: Learn a score a(x)a(x) from mostly normal data so that unusual xx get high scores; flag a(x)>τa(x) > \tau, with τ\tau set from an alert budget.

Example: Flagging the top 200 of 1 million daily transactions by isolation forest score for analyst review.

Related: Isolation forest, Robust z-score

Lesson: Anomaly detection

Attention

A learned, soft lookup: each token gathers information from other tokens, weighted by how relevant they are.

Formal: softmax(QK⊤/dk)V\text{softmax}(QK^\top/\sqrt{d_k})V, where queries, keys, and values are linear projections of the token vectors.

Example: With q=[1,0]q = [1, 0], keys [1,0][1,0] and [0,1][0,1], the weights are [0.67,0.33][0.67, 0.33].

Related: Transformer, Context window

Lesson: Self-attention

Autocorrelation

How strongly a series is correlated with a shifted copy of itself.

Formal: rk=∑t(yt−yˉ)(yt−k−yˉ)/∑t(yt−yˉ)2r_k = \sum_t (y_t - \bar y)(y_{t-k} - \bar y) / \sum_t (y_t - \bar y)^2; plotting rkr_k against kk gives the ACF.

Example: Daily data with a weekly pattern has ACF spikes at lags 7, 14, and 21.

Related: Stationarity

Lesson: Time series

Autograd

A framework feature that records the operations applied to tensors and computes gradients by running the chain rule backwards over that record.

Formal: Reverse-mode automatic differentiation: one backward pass gives ∂L/∂θ\partial L / \partial \theta for every parameter θ\theta that has requires_grad=True. Gradients add into .grad, so they must be zeroed each step.

Example: For L=(wx+b−y)2L = (wx + b - y)^2 with x=2,w=3,b=1,y=10x = 2, w = 3, b = 1, y = 10, L.backward() sets w.grad = -12 and b.grad = -6.

Related: Backpropagation, Gradient

Lesson: Intro to PyTorch

Automatic differentiation

Computing exact gradients by recording each operation in the forward pass and applying the chain rule to that record in reverse.

Formal: Reverse-mode autodiff visits the computation graph in reverse topological order; each node adds (local derivative × upstream gradient) to its inputs' .grad.

Example: For a * a + a at a = 3, the two paths into a contribute 6 and 1, so a.grad = 7.

Related: Backpropagation

Lesson: Backpropagation

Average precision

A single-number summary of the precision-recall curve: the average precision at the rank of each positive example.

Formal: AP=1P∑kprecision@k⋅1[item k is positive]\text{AP} = \frac{1}{P}\sum_k \text{precision@}k \cdot \mathbb{1}[\text{item } k \text{ is positive}], where P is the number of positives.

Example: Positives at ranks 1, 2, 4, 6, 9 give AP = (1 + 1 + 0.75 + 0.667 + 0.556)/5 = 0.794.

Lesson: Classification metrics

Backpropagation

The method for computing how much each weight contributed to the loss, by applying the chain rule backward through the network.

Formal: Reverse-mode automatic differentiation over the computational graph, multiplying local derivatives from the loss to each parameter.

Example: For a sigmoid neuron with cross-entropy, ∂L/∂wj=(y^−y)xj\partial L/\partial w_j = (\hat{y} - y)x_j.

Related: Gradient, Gradient descent

Lesson: Backpropagation

Baseline

The simplest reasonable approach, used to judge whether a model is actually useful.

Formal: A reference score from a trivial predictor (mean, majority class, last value) or a simple model on the same evaluation data.

Example: With 5% positives, "always negative" scores 95% accuracy, so a 95% model has learned nothing.

Related: Metric

Lesson: Workflow, splits, and leakage

Batch

A small group of training examples processed together in one optimization step.

Formal: A mini-batch BB used to estimate the gradient 1∣B∣∑i∈B∇ℓi\frac{1}{|B|}\sum_{i\in B}\nabla\ell_i.

Example: 1,024 examples with batch size 32 give 32 steps per epoch.

Related: Epoch, Gradient descent

Lesson: Gradient descent

Bayesian optimization

A search that fits a cheap model of score versus settings, with uncertainty, and uses it to choose the next setting to try.

Formal: A surrogate (Gaussian process or TPE) gives μ(λ),σ(λ)\mu(\lambda), \sigma(\lambda); an acquisition such as expected improvement (μ−f∗−ξ)Φ(z)+σϕ(z)(\mu - f^* - \xi)\Phi(z) + \sigma\phi(z) picks the next λ\lambda.

Example: Optuna's default TPE sampler is a Bayesian optimization method.

Related: Random search, Hyperparameter

Lesson: Hyperparameter tuning

Bellman equation

The value of where you are equals the reward for one step plus the discounted value of where you land.

Formal: Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[r+γVπ(s′)]V^\pi(s) = \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a)[r + \gamma V^\pi(s')]; the optimality version replaces the average over actions with a max.

Example: Value iteration repeats the optimality version until values stop changing.

Related: Markov decision process, Q-learning, Temporal-difference learning

Lesson: MDPs, states, actions, and rewards

Benjamini-Hochberg

A correction for testing many metrics at once that controls the expected fraction of false "wins" rather than the chance of any false win.

Formal: Sort p-values p_(1) ≤ … ≤ p_(m); find the largest r with p_(r) ≤ q·r/m; reject hypotheses 1..r. Controls false discovery rate at q (for independent or positively dependent tests).

Example: For p = 0.001, 0.008, 0.012, 0.041, … with m = 10 and q = 0.05, the cut falls at rank 3 (0.012 ≤ 0.015, 0.041 > 0.02).

Related: p-value

Lesson: Experimentation and A/B testing

Bias-variance trade-off

Simple models are consistently wrong (bias); flexible models change a lot with the training data (variance); the best model balances both.

Formal: Expected squared error =bias2+variance+σ2= \text{bias}^2 + \text{variance} + \sigma^2.

Example: A degree-1 polynomial underfits a sine curve; degree 15 overfits it.

Related: Overfitting, Regularization

Lesson: Overfitting and bias-variance

BIO tagging

A way to label each token so a classifier can mark entity spans: B starts an entity, I continues it, O means outside any entity.

Formal: For a span (s,e,X)(s, e, X), token ss gets B-X, tokens s+1..e−1s+1..e-1 get I-X, all others O; I-X may only follow B-X or I-X.

Example: "New York City mayor" is tagged B-LOC I-LOC I-LOC O.

Related: Named entity recognition, Viterbi algorithm

Lesson: Named entity recognition

BM25

A keyword-ranking formula that scores documents by how often they contain the query's words, giving more weight to rare words and less to very long documents.

Formal: BM25(q,D)=∑t∈qIDF(t) f(t,D)(k1+1)f(t,D)+k1(1−b+b ∣D∣/avgdl)\text{BM25}(q, D) = \sum_{t \in q} \text{IDF}(t)\,\frac{f(t,D)(k_1+1)}{f(t,D) + k_1(1 - b + b\,|D|/\text{avgdl})}, typically k1≈1.2k_1 \approx 1.2, b≈0.75b \approx 0.75.

Example: A query for an error code like "E1234" is matched exactly by BM25 even when a dense embedding treats it as noise.

Related: TF-IDF, Reciprocal rank fusion

Lesson: Vector search

Bootstrap

Estimating the uncertainty of a statistic by resampling your data with replacement many times and recomputing it each time.

Formal: Draw B resamples of size n with replacement, compute the statistic on each, and take the 2.5th and 97.5th percentiles as a 95% interval.

Example: 870 of 1,000 correct gives a bootstrap 95% interval of about [0.850, 0.890] for accuracy.

Lesson: Probability and statistics

Bootstrap sample

A resample of the training set, the same size as the original, drawn with replacement, so some rows repeat and others are left out.

Formal: Draw nn indices uniformly from {1,…,n}\{1,\dots,n\} with replacement; each row is left out with probability (1−1/n)n≈e−1≈0.368(1 - 1/n)^n \approx e^{-1} \approx 0.368.

Example: From 1,000 rows, a bootstrap sample contains about 632 distinct rows; the roughly 368 left out are that tree's out-of-bag rows.

Related: Out-of-bag error

Lesson: Random forests and gradient boosting

Broadcasting

NumPy's rule for combining arrays of different shapes by stretching size-1 dimensions without copying data.

Formal: Align shapes from the right; each pair of dimensions must be equal or one must be 1 (missing dimensions count as 1). The result takes the larger size in each position.

Example: [1000, 3] - [3] gives [1000, 3]; [1000] - [1000, 1] gives [1000, 1000], usually a bug.

Related: Data leakage

Lesson: Python toolkit

Calibration

Whether a model's predicted probabilities match how often things actually happen.

Formal: A model is calibrated if P(y=1∣p^=p)=pP(y = 1 \mid \hat{p} = p) = p for all pp; measured with reliability diagrams or the Brier score.

Example: Of all emails scored 0.8 spam, about 80% should really be spam.

Related: Logit, Hallucination

Lesson: Classification metrics

Canary rollout

Shift a growing share of traffic to a new version and roll back automatically if guard metrics get worse.

Formal: Stages s₁ < … < 1; promote while metric_canary ≤ k · metric_baseline for every gate.

Lesson: Production architecture

Catastrophic forgetting

When training a model on a new, narrow task makes it lose skills it had before.

Formal: Performance on the original distribution drops after fine-tuning because gradient updates for the new objective overwrite weights the old behavior depended on.

Example: A model fine-tuned for many epochs on support tickets gets better at tickets but worse at general reasoning and safety refusals.

Related: Fine-tuning, LoRA

Lesson: Fine-tuning in practice

Chain-of-thought

Prompting a model to write out intermediate reasoning steps before its final answer, so each step is a small prediction.

Formal: If each step fails independently with probability ε\varepsilon, an ss-step answer is right with probability (1−ε)s(1-\varepsilon)^s; writing steps as tokens lowers ε\varepsilon because later tokens can condition on earlier results.

Example: At ε=0.15\varepsilon = 0.15 a 4-step answer is right with probability 0.854=0.5220.85^4 = 0.522; at ε=0.05\varepsilon = 0.05 it is 0.954=0.8150.95^4 = 0.815.

Related: Few-shot prompting, Self-consistency, ReAct

Lesson: Few-shot and chain-of-thought

Checkpoint

A saved snapshot of a model's weights (and often optimizer state) during or after training.

Formal: A serialized copy of θ\theta at step tt, used to resume training, evaluate, or deploy.

Example: Early stopping deploys the checkpoint with the lowest validation loss, not the last one.

Related: Epoch

Lesson: Training and regularization

Chinchilla-optimal

The split between model size and training tokens that gives the lowest loss for a fixed training compute budget, roughly 20 tokens per parameter.

Formal: N∗,D∗=arg⁡min⁡6ND=CL(N,D)N^*, D^* = \arg\min_{6ND = C} L(N, D). With Approach 3 constants, N∗∝C0.45N^* \propto C^{0.45} and D∗∝C0.55D^* \propto C^{0.55}, so the ratio drifts with budget.

Example: For C=6×1022C = 6 \times 10^{22} FLOPs at 20 tokens per parameter: N=22.4N = 22.4B, D=447D = 447B tokens. Models served heavily are trained far past this ratio on purpose.

Related: Scaling law

Lesson: Scaling laws

Chunking

Splitting documents into smaller pieces that can be retrieved individually.

Formal: Partitioning text into segments of size SS with overlap OO, giving about ⌈(N−O)/(S−O)⌉\lceil (N - O)/(S - O)\rceil chunks.

Example: A 1,000-word document with 200-word chunks and 50-word overlap gives 7 chunks.

Related: RAG, Embedding

Lesson: The RAG pipeline

Class weights

Multipliers on the loss that make mistakes on a rare class cost more, so the model pays attention to it.

Formal: Balanced weights are wc=n/(C⋅nc)w_c = n / (C \cdot n_c), so each class carries total weight n/Cn / C. For logistic regression they inflate the predicted odds by about n0/n1n_0 / n_1, which mainly moves the decision threshold.

Example: With 2,279 negatives and 121 positives, w0=0.5265w_0 = 0.5265 and w1=9.917w_1 = 9.917: one positive counts as 18.83 negatives.

Related: SMOTE, Calibration, Loss

Lesson: Imbalanced data

Classifier-free guidance

A sampling trick that strengthens how much a diffusion model follows its prompt by extrapolating from an unconditional prediction toward the conditional one.

Formal: ϵ~=ϵθ(zt,t,∅)+w[ϵθ(zt,t,c)−ϵθ(zt,t,∅)]\tilde\epsilon = \epsilon_\theta(z_t, t, \varnothing) + w[\epsilon_\theta(z_t, t, c) - \epsilon_\theta(z_t, t, \varnothing)]; requires dropping the condition (about 10%) during training. w=1w = 1 is plain conditional sampling.

Example: ϵ∅=0.2\epsilon_\varnothing = 0.2, ϵc=0.5\epsilon_c = 0.5, w=3w = 3 gives 0.2+3×0.3=1.10.2 + 3 \times 0.3 = 1.1.

Related: Latent diffusion

Lesson: Latent diffusion and Stable Diffusion

Cold start

The problem of making good predictions for a new user or item that has no interaction history yet.

Formal: For an entity with no logged interactions, collaborative signals are undefined, so the model must rely on content and context features, priors such as popularity, or deliberate exploration.

Example: A video uploaded a minute ago has no views; the item tower embeds its title and frames so it can still be retrieved, and re-ranking gives it a small freshness boost.

Related: Two-tower model, Position bias

Lesson: ML system design

Concept drift

The world's answer to the same input changes, so a model that was right becomes wrong even though its inputs look normal.

Formal: A change in P(y∣x)P(y \mid x). Contrast covariate drift (change in P(x)P(x)) and prior drift (change in P(y)P(y)). Only outcome monitoring with labels can detect it.

Example: Fraudsters change tactics, so the same basket size now carries a different fraud risk.

Related: Drift, Population Stability Index

Lesson: Model monitoring and drift

Constrained decoding

Forcing a model's output to follow a format, such as a JSON schema, by blocking any next token that would break it.

Formal: At each step, tokens outside the allowed set AtA_t (from a grammar compiled from the schema) get probability 0 and the rest are renormalized: p~(yt)∝p(yt) 1[yt∈At]\tilde p(y_t) \propto p(y_t)\,\mathbb{1}[y_t \in A_t].

Example: A tool call generated under the schema always parses, though flight_id may still be the wrong flight.

Related: Tool calling, Temperature

Lesson: Tool use and agents

Context engineering

Deciding everything that goes into a model call's context window (instructions, tools, retrieved documents, history, memory) and in what order, under a token budget.

Formal: Choose and order components so that input tokens plus the output reserve fit the window WW, while maximizing task quality; with full history, total billed input over TT calls is TF+h T(T−1)/2TF + h\,T(T-1)/2.

Example: Selecting 10 of 30 tools, 3 of 8 documents, and compacting history cut a synthetic 20-call conversation from 231,500 to 93,750 input tokens.

Related: Context window, Lost in the middle, Prefix caching, RAG

Lesson: Context engineering

Context window

The maximum number of tokens a language model can consider at once, prompt and output combined.

Formal: The maximum sequence length nmax⁡n_{\max} over which attention is computed.

Example: Anything beyond the window is invisible to the model unless retrieved and inserted.

Related: Token, Attention

Lesson: Tokenization and pretraining

Continuous batching

A serving scheduler that adds and removes requests from the running batch at every decode step, instead of waiting for a whole batch to finish.

Formal: Admission is decided per iteration: when a sequence emits its end token, its slot (and KV memory) is given to a waiting request on the next step. Also called in-flight or iteration-level batching.

Example: Two slots, requests of 2, 8, 3, and 3 tokens: static batching finishes at step 11 (1.45 tokens/step), continuous batching at step 8 (2.0 tokens/step).

Related: Batch, Paged attention, KV cache

Lesson: Serving LLMs

Coordinate descent

An optimizer that updates one parameter at a time, solving for it exactly while holding the others fixed, and sweeps until nothing moves.

Formal: For j=1,…,dj = 1, \dots, d: wj←arg⁡min⁡wjL(w1,…,wd)w_j \leftarrow \arg\min_{w_j} L(w_1, \dots, w_d); repeat. Lasso solvers use it because each one-weight problem has a closed form (soft-thresholding).

Example: scikit-learn's Lasso and ElasticNet are fitted by coordinate descent.

Related: Soft-thresholding

Lesson: Regularization and regression metrics

Cosine similarity

How closely two vectors point in the same direction, ignoring their lengths.

Formal: cos⁡(a,b)=a⋅b∥a∥∥b∥\cos(a, b) = \frac{a\cdot b}{\lVert a\rVert\lVert b\rVert}, between −1 and 1.

Example: [1,2,0][1, 2, 0] and [2,1,1][2, 1, 1] have cosine 0.730.

Related: Embedding, TF-IDF

Lesson: From text to vectors

Cost governor

Runtime budget caps (per call, steps, per task, spend rate, monthly) that halt an agent before it crosses a limit.

Lesson: Building reliable agents

Cross-entropy

A loss that punishes a model for giving low probability to the correct answer.

Formal: −ln⁡ptrue-\ln p_{\text{true}} for one example; binary form −[yln⁡p+(1−y)ln⁡(1−p)]-[y\ln p + (1-y)\ln(1-p)].

Example: Probability 0.9 on the true class costs 0.105; probability 0.01 costs 4.6.

Related: Loss, Perplexity

Lesson: Logistic regression

CTC

Connectionist temporal classification: a way to train a model to output text from many audio frames without knowing which frame produced which letter.

Formal: The model emits a distribution over tokens plus a blank at each frame; a path collapses to text by merging repeats and removing blanks, and P(y∣x)P(y \mid x) sums over all paths that collapse to yy, computed with a forward algorithm in O(T⋅(2U+1))O(T \cdot (2U+1)).

Example: With frame probabilities (0.4,0.6),(0.5,0.5),(0.7,0.3)(0.4, 0.6), (0.5, 0.5), (0.7, 0.3) for (blank, a), P("a")=0.77P(\text{"a"}) = 0.77 and the loss is −ln⁡0.77=0.261-\ln 0.77 = 0.261.

Related: Word error rate, Spectrogram

Lesson: Speech recognition: CTC, transducers, and attention

CUPED

A variance-reduction trick for A/B tests that subtracts the part of each user's outcome that was already predictable from their behavior before the experiment.

Formal: Ycuped=Y−θ(X−Xˉ)Y^{\text{cuped}} = Y - \theta(X - \bar{X}) with θ=Cov⁡(X,Y)/Var⁡(X)\theta = \operatorname{Cov}(X, Y)/\operatorname{Var}(X), where XX is a pre-experiment covariate; the variance shrinks by a factor 1−ρ21 - \rho^2 and the estimate stays unbiased.

Example: With ρ=0.5\rho = 0.5 between last month's and this month's sessions, variance drops 25%, so a test needing 14,749 users per arm needs about 11,062.

Related: Statistical power, Minimum detectable effect

Lesson: Experimentation and A/B testing

Curse of dimensionality

In many dimensions, random points are all about equally far apart, so "nearest neighbor" carries little information and data needed to cover the space grows exponentially.

Example: For 1,000 uniform random points and a random query, nearest/farthest distance ratio was 0.007 in 2 dimensions and 0.898 in 1,000 dimensions.

Lesson: K-nearest neighbors

Data leakage

When training uses information that won't be available at prediction time, making results look better than they are.

Formal: Any dependence of training features or preprocessing on test data, future data, or the target itself.

Example: Fitting a scaler on all data before splitting, or including "refund issued" when predicting fraud.

Related: Baseline, Generalization

Lesson: Workflow, splits, and leakage

Data parallelism

Every GPU holds a full copy of the model and trains on a different slice of the batch; gradients are averaged so all copies stay identical.

Formal: With equal shards, the mean of shard gradients equals the full-batch gradient; one gradient all-reduce per step. Throughput scales with GPUs, memory per GPU does not drop. PyTorch's DistributedDataParallel (DDP).

Example: A 7B-style model still needs about 108.6 GB per GPU under DDP, however many GPUs you add.

Related: All-reduce, ZeRO, Tensor parallelism

Lesson: Scaling and distributed training

Dead ReLU

A ReLU unit whose input is negative for every example, so it always outputs 0 and gets zero gradient, and stops learning.

Formal: Unit jj is dead on a dataset if zj(x)≤0z_j(x) \le 0 for all xx; then ∂L/∂zj=0\partial L / \partial z_j = 0.

Example: With hidden biases initialized to −3, 97% of a second layer's units were dead and its gradients were about 1,000 times smaller than in a healthy network.

Related: Activation, Gradient

Lesson: Debugging neural networks

Deadly triad

Function approximation, bootstrapping, and off-policy learning together can make value learning diverge.

Formal: Term from Sutton and Barto: any two of the three are stable in general, but combining all three removes convergence guarantees for TD methods.

Example: DQN has all three; replay and a target network make it work in practice without restoring the guarantee.

Related: Deep Q-network (DQN), Target network

Lesson: Deep Q-networks (DQN)

Deep Q-network (DQN)

Q-learning where a neural network, instead of a table, predicts the value of each action in a state.

Formal: Minimizes E[ℓ(Q(s,a;θ)−(r+γ(1−d)max⁡a′Q(s′,a′;θ−)))]\mathbb{E}\big[\ell\big(Q(s,a;\theta) - (r + \gamma(1-d)\max_{a'} Q(s',a';\theta^-))\big)\big] over minibatches from a replay buffer, with a target network θ−\theta^- and usually the Huber loss ℓ\ell.

Example: A 16 → 32 → 4 network learns the 6-step shortest path on a 4×4 GridWorld; the 2015 version learned dozens of Atari games from pixels.

Related: Experience replay, Target network, Double DQN

Lesson: Deep Q-networks (DQN)

Demographic parity

A fairness criterion that requires every group to be selected at the same rate.

Formal: P(Y^=1∣A=a)P(\hat Y = 1 \mid A = a) is equal for all groups aa. With unequal base rates it usually conflicts with equal error rates and equal precision.

Example: Approving 31% of group A and 52% of group B violates demographic parity even if both groups have the same TPR and FPR.

Related: Equalized odds

Lesson: Fairness

Dice coefficient

An overlap score for masks, equal to F1 computed on pixels; used as a loss for imbalanced segmentation.

Formal: Dice=2∣P∩Y∣/(∣P∣+∣Y∣)=2 IoU/(1+IoU)\text{Dice} = 2|P \cap Y| / (|P| + |Y|) = 2\,\text{IoU}/(1 + \text{IoU}); soft Dice loss replaces the sets with predicted probabilities.

Example: 40 shared pixels, 60 predicted, 50 true: Dice = 80/110 = 0.727, IoU = 0.571.

Related: Intersection over union, Loss

Lesson: Semantic segmentation and U-Net

Differential privacy

A guarantee that a computation's output would look almost the same whether or not any one person's record was in the data.

Formal: MM is (ε,δ)(\varepsilon, \delta)-DP if P[M(D)∈S]≤eεP[M(D′)∈S]+δP[M(D) \in S] \le e^\varepsilon P[M(D') \in S] + \delta for all neighbouring datasets D,D′D, D' and output sets SS. Costs add up over queries; post-processing is free.

Example: Releasing a count with Laplace noise of scale 1/ε1/\varepsilon is ε\varepsilon-DP; at ε=0.5\varepsilon = 0.5 the typical error is 2.

Related: DP-SGD

Lesson: Differential privacy

Discount factor

How much a reward later counts compared with the same reward now.

Formal: γ∈[0,1]\gamma \in [0, 1]; the return is Gt=∑kγkrt+kG_t = \sum_k \gamma^k r_{t+k}, and the effective horizon is about 1/(1−γ)1/(1-\gamma) steps.

Example: With γ=0.9\gamma = 0.9, a reward 10 steps away keeps 0.910≈0.350.9^{10} \approx 0.35 of its weight.

Related: Markov decision process, Bellman equation

Lesson: MDPs, states, actions, and rewards

Distillation

Training a small model to imitate a large one, to get similar quality more cheaply.

Formal: Minimizing the divergence between the student's outputs and the teacher's (soft) outputs, often alongside the true labels.

Example: A small classifier trained on a large LLM's labels serves high-volume traffic at a fraction of the cost.

Related: Quantization, Inference

Lesson: Reliability, cost, and observability

Double DQN

A DQN variant that reduces overoptimistic Q-values by letting one network choose the next action and another score it.

Formal: y=r+γ(1−d) Q(s′,arg⁡max⁡a′Q(s′,a′;θ);θ−)y = r + \gamma(1-d)\,Q\big(s', \arg\max_{a'} Q(s', a'; \theta); \theta^-\big).

Example: Online values [−5.5,−5.1,−5.7,−4.95][-5.5, -5.1, -5.7, -4.95] pick action 4; the target network scores it −5.0-5.0, so y=−1+0.99×(−5.0)=−5.95y = -1 + 0.99 \times (-5.0) = -5.95 instead of the vanilla −5.851-5.851.

Related: Deep Q-network (DQN)

Lesson: Deep Q-networks (DQN)

DP-SGD

Training with differential privacy: limit how much each example can push the model, then add noise to every update.

Formal: Clip each per-example gradient to norm CC, add N(0,σ2C2I)\mathcal{N}(0, \sigma^2 C^2 I) to their sum, divide by the batch size, and step; an accountant tracks the total ε\varepsilon across steps (Abadi et al. 2016).

Example: 100 full-batch steps at σ=4\sigma = 4, δ=10−5\delta = 10^{-5} give ε≈15\varepsilon \approx 15; σ=16\sigma = 16 gives about 3.2.

Related: Differential privacy, Gradient descent

Lesson: Differential privacy

DPO

Direct preference optimization: training a model on pairs of better and worse answers so it prefers the better kind, without a separate reward model or reinforcement learning loop.

Formal: L=−log⁡σ(β[log⁡πθ(yw∣x)πref(yw∣x)−log⁡πθ(yl∣x)πref(yl∣x)])\mathcal{L} = -\log\sigma\big(\beta[\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}]\big) with a frozen reference model πref\pi_{\text{ref}}.

Example: At the start of training the policy equals the reference, so the loss is ln⁡2=0.693\ln 2 = 0.693.

Related: Fine-tuning, LoRA

Lesson: Fine-tuning in practice

Drift

When the data or the world changes after deployment, so a model's performance degrades.

Formal: Data drift is a change in P(x)P(x); concept drift is a change in P(y∣x)P(y \mid x); prompt drift is a change in what users ask.

Example: A demand model trained before a price change starts under-predicting.

Related: Generalization, Calibration

Lesson: Reliability, cost, and observability

Embedding

A dense vector that represents an item (word, token, document, user) so that similar items are close together.

Formal: A learned mapping e:item→Rde: \text{item} \to \mathbb{R}^d, often a row of an embedding matrix of shape [V,d][V, d].

Example: "cat" and "kitten" have high cosine similarity even though the words differ.

Related: Cosine similarity, Token

Lesson: Word embeddings

Entropy

The average surprise of a probability distribution: how uncertain you are before seeing the outcome.

Formal: H(P)=−∑xp(x)log⁡p(x)H(P) = -\sum_x p(x)\log p(x). Bits with log⁡2\log_2, nats with ln⁡\ln.

Example: A fair coin has 1 bit of entropy; a coin that lands heads 99% of the time has 0.08 bits.

Related: Cross-entropy, KL divergence, Perplexity

Lesson: Information theory

Epoch

One full pass over the training data.

Formal: ⌈n/∣B∣⌉\lceil n/|B|\rceil optimization steps for nn examples and batch size ∣B∣|B|.

Example: Validation loss is usually checked once per epoch for early stopping.

Related: Batch, Checkpoint

Lesson: Gradient descent

Epsilon-greedy

Usually take the best-looking action, but with a small probability take a random one, so the agent keeps discovering.

Formal: With probability ε\varepsilon choose uniformly among actions; otherwise choose arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a).

Example: With ε=0.1\varepsilon = 0.1 and 4 actions, the greedy action is taken with probability 0.9+0.1/4=0.9250.9 + 0.1/4 = 0.925.

Related: Q-learning, SARSA

Lesson: Q-learning and SARSA

Equalized odds

A fairness criterion that requires the model to make the same kinds of mistakes in every group: equal true positive rates and equal false positive rates.

Formal: P(Y^=1∣Y=y,A=a)P(\hat Y = 1 \mid Y = y, A = a) is equal across groups for y∈{0,1}y \in \{0, 1\}. Equal opportunity is the y=1y = 1 half. When base rates differ, it cannot hold together with equal precision (unless the classifier is perfect).

Example: TPR 0.8 and FPR 0.1 in both groups satisfies equalized odds.

Related: Demographic parity, Calibration

Lesson: Fairness

Evaluator-optimizer

A workflow where one call drafts an answer and another critiques it against criteria, looping until it passes or a cap is hit.

Lesson: Building reliable agents

Expectation-maximization (EM)

A way to fit models with hidden labels, such as which Gaussian generated each point: guess soft labels, refit the parameters to them, and repeat. The likelihood never decreases.

Formal: E-step: γik=πkN(xi∣μk,Σk)/∑jπjN(xi∣μj,Σj)\gamma_{ik} = \pi_k \mathcal{N}(x_i \mid \mu_k, \Sigma_k) / \sum_j \pi_j \mathcal{N}(x_i \mid \mu_j, \Sigma_j). M-step: Nk=∑iγikN_k = \sum_i \gamma_{ik}, πk=Nk/n\pi_k = N_k/n, μk=∑iγikxi/Nk\mu_k = \sum_i \gamma_{ik} x_i / N_k, Σk\Sigma_k the γ\gamma-weighted covariance.

Example: a point with responsibilities (0.24,0.76)(0.24, 0.76) contributes 0.24 of itself to component 1's mean and 0.76 to component 2's.

Lesson: DBSCAN, hierarchical clustering, and Gaussian mixtures

Experience replay

A buffer of recent transitions that an RL agent trains on in random minibatches instead of in the order they happened.

Formal: Store (s,a,r,s′,d)(s, a, r, s', d) tuples in a fixed-capacity FIFO buffer D\mathcal{D} and sample minibatches uniformly (or by priority) for each gradient step. Valid for off-policy methods such as Q-learning.

Example: With capacity 2,000 and batch 32, each transition is reused in many updates, and a batch mixes transitions from many episodes.

Related: Deep Q-network (DQN), Target network

Lesson: Deep Q-networks (DQN)

Expert capacity

The fixed number of token slots each expert gets per batch; extra tokens sent to a full expert are dropped.

Formal: C=⌈c⋅Tk/E⌉C = \lceil c \cdot Tk/E \rceil for TT tokens, top-kk routing, EE experts, and capacity factor cc.

Example: 4,096 tokens, 64 experts, top-2, c=1.25c = 1.25: C=⌈1.25×128⌉=160C = \lceil 1.25 \times 128 \rceil = 160.

Related: Mixture of experts

Lesson: Mixture of experts

Faithfulness

How much of an answer is actually supported by the sources it was given.

Formal: The fraction of the answer's claims that an entailment model or judge marks as supported by the retrieved context.

Example: Two of three claims supported gives faithfulness 0.67, even if the third claim happens to be true.

Related: Calibration

Lesson: Evaluating LLM systems

Feature

An input variable the model uses to make a prediction.

Formal: A component xjx_j of the input vector x∈Rpx \in \mathbb{R}^p.

Example: Square footage when predicting house prices.

Related: Label, Parameter

Lesson: The language of ML

Feature store

A system that defines each feature once and serves the same values both to training pipelines and to the live model.

Formal: An offline store of historical feature values supporting point-in-time (as-of) joins for training, plus a low-latency online store for serving, both fed by the same feature definitions.

Example: "Clicks on this item in the last hour" is computed by one streaming job, written to the online store for serving and to the offline store so training examples get the value as of each impression.

Related: Training-serving skew, Data leakage

Lesson: ML system design

Few-shot prompting

Putting a few input-output examples in the prompt so the model copies the task's format and style.

Formal: In-context learning: the examples are part of the conditioning context p(y∣examples,x)p(y \mid \text{examples}, x); no weights change.

Example: One worked example ending in Answer: 20 made a model end every answer with Answer: N, so a strict parser found the answer in 100% of outputs instead of 24%.

Related: Chain-of-thought, Fine-tuning

Lesson: Few-shot and chain-of-thought

Fine-tuning

Continuing to train a pretrained model on task-specific data so it changes its behavior.

Formal: Further optimization of some or all pretrained weights (or added adapters such as LoRA) on a new dataset.

Example: Fine-tuning a model on support transcripts to adopt a consistent tone and format.

Related: RAG, LoRA

Lesson: Adapting LLMs

FlashAttention

An exact way to compute attention that keeps small tiles of the work in fast on-chip memory, so the full attention matrix is never written to slow GPU memory.

Formal: Tiles QQ, KK, VV into SRAM blocks and uses an online softmax (running max and sum) to produce the same output as standard attention, with O(T)O(T) extra memory instead of O(T2)O(T^2) and far less memory traffic.

Example: At 8,192 tokens, one head's 16-bit score matrix would be 134 MB; FlashAttention never materializes it.

Related: Attention, KV cache

Lesson: LLM inference

Flow matching

Training a generator by teaching a network the velocity that moves points along straight paths between noise and data, then following those velocities from noise.

Formal: xt=(1−t)x0+tx1x_t = (1-t)x_0 + t x_1, loss E∥vθ(xt,t)−(x1−x0)∥2\mathbb{E}\lVert v_\theta(x_t, t) - (x_1 - x_0)\rVert^2; sample by integrating dx/dt=vθdx/dt = v_\theta from t=1t = 1 to 00. Rectified flow adds reflow: retraining on the model's own (noise, sample) pairs to straighten paths.

Example: x0=2x_0 = 2, x1=−0.5x_1 = -0.5, t=0.25t = 0.25 gives xt=1.375x_t = 1.375 and target velocity −2.5-2.5.

Related: Latent diffusion

Lesson: Flow matching and rectified flows

Focal loss

Cross-entropy that down-weights examples the model already gets right, so rare hard examples dominate the gradient.

Formal: FL=−α(1−pt)γln⁡pt\text{FL} = -\alpha(1 - p_t)^\gamma \ln p_t, where ptp_t is the probability of the true class; γ=0\gamma = 0 gives cross-entropy.

Example: With γ=2\gamma = 2, an easy example at pt=0.9p_t = 0.9 keeps 1% of its cross-entropy; a hard one at pt=0.1p_t = 0.1 keeps 81%.

Related: Cross-entropy, Loss

Lesson: Loss functions

FSDP

PyTorch's built-in version of fully sharded data parallelism: each GPU keeps only a slice of the model and gathers each layer's weights when it needs them.

Formal: Fully Sharded Data Parallel, equivalent to ZeRO stage 3. Weights are all-gathered before each wrapped module's forward and backward, and gradients are reduce-scattered. fully_shard in FSDP2; SHARD_GRAD_OP and HYBRID_SHARD give ZeRO-2-like and per-node variants.

Example: A 70B-style model first fits on 80 GB GPUs at 16 GPUs (about 72 GB each).

Related: ZeRO, All-gather

Lesson: ZeRO and FSDP

GAN

A generative adversarial network: a generator makes fake samples and a discriminator learns to tell them from real ones; the generator improves by fooling it.

Formal: min⁡Gmax⁡DEx[log⁡D(x)]+Ez[log⁡(1−D(G(z)))]\min_G \max_D \mathbb{E}_x[\log D(x)] + \mathbb{E}_z[\log(1 - D(G(z)))]; the generator usually minimizes the non-saturating loss −log⁡D(G(z))-\log D(G(z)).

Example: For fixed GG, the best discriminator is D∗(x)=pdata/(pdata+pg)D^*(x) = p_{\text{data}}/(p_{\text{data}} + p_g), which is 0.5 everywhere at equilibrium.

Related: Mode collapse, Loss

Lesson: GANs, generator versus discriminator

Generalization

How well a model performs on new data it never saw during training.

Formal: Expected loss on the data distribution, estimated by held-out data that played no part in building the model.

Example: A model with 99% training accuracy and 70% test accuracy generalizes poorly.

Related: Overfitting, Data leakage

Lesson: The language of ML

Generalized advantage estimation

An advantage estimate that blends one-step and multi-step lookaheads, trading bias from the critic against variance from the real returns.

Formal: δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t), A^t=∑k≥0(γλ)kδt+k\hat A_t = \sum_{k \ge 0} (\gamma\lambda)^k \delta_{t+k}. λ=0\lambda = 0 gives the one-step TD error; λ=1\lambda = 1 gives the Monte Carlo return minus VV.

Example: With γ=0.99\gamma = 0.99, λ=0.95\lambda = 0.95, TD errors −0.091-0.091 and then −0.1-0.1 at the end give A^=−0.091+0.9405×(−0.1)=−0.185\hat A = -0.091 + 0.9405 \times (-0.1) = -0.185.

Related: Advantage, PPO

Lesson: PPO

Goodput

The share of requests that met every latency target at once.

Formal: Fraction of requests with TTFT ≤ a, TPOT ≤ b, and end-to-end latency ≤ c.

Lesson: Serving LLMs

Gradient

The direction and steepness of the loss surface: which way each parameter should move to increase the loss fastest.

Formal: ∇θL=[∂L/∂θ1,…,∂L/∂θP]\nabla_\theta L = [\partial L/\partial\theta_1, \dots, \partial L/\partial\theta_P].

Example: For L=x2+2y2L = x^2 + 2y^2 at (1,1)(1, 1), ∇L=(2,4)\nabla L = (2, 4).

Related: Gradient descent, Backpropagation

Lesson: Calculus for ML

Gradient accumulation

Running several small batches and adding up their gradients before taking one optimizer step, to get the effect of a batch too big for memory.

Formal: Effective batch size = micro-batch size × accumulation steps. With a masked token loss, sum the per-token gradients and divide by the total token count across micro-batches, not the average of per-micro-batch means.

Example: Micro-batch 4 with 8 accumulation steps trains like a batch of 32.

Related: Calibration

Lesson: Fine-tuning in practice

Gradient check

Testing a hand-written backward pass by comparing its gradients with finite-difference estimates.

Formal: gnum=[L(w+h)−L(w−h)]/2hg_{\text{num}} = [L(w + h) - L(w - h)]/2h; relative error below about 10−710^{-7} (float64) passes, around 10−310^{-3} or more indicates a bug.

Example: A backward pass missing the ReLU mask gives relative error about 1; the correct one gives 2×10−72 \times 10^{-7}.

Related: Backpropagation, Autograd

Lesson: Numerical stability

Gradient checkpointing

Saving memory in training by keeping only some layer inputs and recomputing the rest of the forward pass during backward.

Formal: Store the input of every kk-th layer; during backward re-run each segment's forward to rebuild its activations. Gradients are identical; compute rises by about 33% (one extra forward per step). Also called activation recomputation.

Example: A 7B-style model at 2,048 tokens keeps about 9.13 GB of activations, or 0.822 GB checkpointing every layer.

Related: Activation, Backpropagation

Lesson: Gradient checkpointing

Gradient clipping

Capping how big one update can be, so a single bad batch cannot throw the weights far off.

Formal: Global-norm clipping rescales all gradients by min⁡(1,c/∥g∥)\min(1, c / \lVert g \rVert), where ∥g∥\lVert g \rVert is the L2 norm over every parameter; the update keeps its direction.

Example: Gradients [3,4][3, 4] and [12][12] have norm 13; clipping at 1 multiplies all of them by 1/131/13.

Related: Mixed precision, Gradient

Lesson: Gradient clipping and mixed precision

Gradient descent

Repeatedly nudging parameters a small step downhill on the loss surface.

Formal: θ←θ−η∇θL\theta \leftarrow \theta - \eta\nabla_\theta L; stable along curvature λ\lambda only if η<2/λ\eta < 2/\lambda.

Example: With η=0.1\eta = 0.1, w=1w = 1 and gradient −7.33-7.33, the new weight is 1.7331.733.

Related: Learning rate, Gradient

Lesson: Gradient descent

Grounding

Tying a model's answer to supplied evidence, so every claim can be traced to a source.

Formal: The fraction of an answer's claims supported by the provided context, often with citations.

Example: "Refunds are allowed within 30 days [2]," where source 2 contains that sentence.

Related: RAG, Hallucination

Lesson: Evaluating LLM systems

Grouped-query attention

Attention where several query heads share one key/value head, which shrinks the KV cache with little quality loss.

Formal: With nhn_h query heads and nkvn_{kv} KV heads (1<nkv<nh1 < n_{kv} < n_h), each group of nh/nkvn_h / n_{kv} query heads attends using the same KK and VV. nkv=nhn_{kv} = n_h is multi-head attention (MHA); nkv=1n_{kv} = 1 is multi-query attention (MQA).

Example: 32 query heads and 8 KV heads cut the KV cache to a quarter of MHA's: 131,072 instead of 524,288 bytes per token in a synthetic 8B-style model.

Related: KV cache, Attention

Lesson: LLM inference

GRPO

Group relative policy optimization: RL for LLMs that scores several sampled answers per prompt and pushes up the ones better than the group average, without a value model.

Formal: For GG responses with rewards rir_i, every token of response ii gets advantage (ri−mean(r))/std(r)(r_i - \text{mean}(r)) / \text{std}(r); the loss is PPO's clipped surrogate plus a KL penalty to a reference model.

Example: Rewards [1,0,0,1][1, 0, 0, 1] have mean 0.5 and std 0.5, giving advantages [1,−1,−1,1][1, -1, -1, 1].

Related: PPO, Policy gradient, DPO

Lesson: Fine-tuning in practice

Hallucination

A fluent, confident statement that isn't supported by facts or the provided sources.

Formal: Generated content inconsistent with the source context or the world, arising because the model optimizes likely text rather than truth.

Example: Inventing a refund policy detail that appears in no document.

Related: Grounding, Calibration

Lesson: Adapting LLMs

Hinge loss

The SVM's per-point penalty: zero for points safely past the margin, growing linearly for points inside it or on the wrong side.

Formal: max⁡(0, 1−y f(x))\max(0,\, 1 - y\,f(x)) with labels y∈{−1,+1}y \in \{-1, +1\}.

Example: y=+1y = +1, f(x)=−0.2f(x) = -0.2 gives loss 1.21.2; f(x)=3f(x) = 3 gives 0.

Lesson: Support vector machines

HNSW

Hierarchical navigable small world: a vector index that links each vector to its near neighbors in a layered graph and searches by hopping toward the query.

Formal: Each node keeps up to MM links per upper layer and 2M2M at layer 0; search descends greedily from the top layer, then runs best-first search with a candidate list of size efSearch.

Example: With M=32M = 32 and 4-byte IDs, the bottom-layer links cost about 256 bytes per vector, 256 MB per million vectors.

Related: Approximate nearest neighbor search, Embedding

Lesson: Vector search

Huber loss

A regression loss that is squared for small errors and linear for large ones, so outliers can't dominate.

Formal: 12r2\tfrac12 r^2 if ∣r∣≤δ|r| \le \delta, else δ(∣r∣−12δ)\delta(|r| - \tfrac12\delta), with residual rr.

Example: Residuals [−0.5,0.5,0,10][-0.5, 0.5, 0, 10] give mean Huber 2.44 (δ=1\delta = 1) versus MSE 25.1.

Related: Loss, Overfitting

Lesson: Loss functions

Hyperparameter

A setting you choose before training that controls how learning happens.

Formal: A value fixed outside the optimization of θ\theta, usually selected on a validation set.

Example: Learning rate, tree depth, KK in K-nearest neighbors.

Related: Parameter

Lesson: The language of ML

Idempotency key

A unique token sent with a write so that retrying it does not repeat the side effect.

Formal: key = hash(task, action, payload); the server stores one result per key and returns it on repeats.

Lesson: Building reliable agents

Inference

Running a trained model to make predictions on new inputs.

Formal: Computing fθ∗(xnew)f_{\theta^*}(x_{\text{new}}) with fixed parameters; for LLMs, generating tokens from a prompt.

Example: Scoring a new transaction for fraud in 20 milliseconds.

Related: Training, Quantization

Lesson: The language of ML

InfoNCE

The contrastive loss: each item must pick out its true partner from a batch of distractors.

Formal: ℓi=−log⁡exp⁡(sim(zi,zi+)/τ)∑k≠iexp⁡(sim(zi,zk)/τ)\ell_i = -\log \dfrac{\exp(\text{sim}(z_i, z_{i^+})/\tau)}{\sum_{k \ne i} \exp(\text{sim}(z_i, z_k)/\tau)}, cross-entropy over candidates with temperature τ\tau; chance level is the log of the number of candidates.

Example: With 2 images (4 views) and τ=0.5\tau = 0.5, the lesson's example gives a loss of 0.871 versus a chance level of ln 3 = 1.099.

Related: Cross-entropy, Temperature, Cosine similarity

Lesson: Self-supervised vision

Intersection over union

How much two regions overlap, as a fraction of the area they cover together; 1 is identical, 0 is disjoint.

Formal: IoU(A,B)=∣A∩B∣/∣A∪B∣\text{IoU}(A, B) = |A \cap B| / |A \cup B|, for boxes or pixel masks.

Example: Boxes (50, 50, 150, 150) and (60, 60, 160, 160) overlap in 8100 pixels out of 11,900, so IoU = 0.68.

Related: Non-maximum suppression, Metric

Lesson: Object detection and YOLO

Isolation forest

An anomaly detector that counts how many random cuts it takes to separate a point from the rest; fewer cuts means more anomalous.

Formal: s(x)=2−E[h(x)]/c(ψ)s(x) = 2^{-E[h(x)]/c(\psi)}, where hh is path length in random trees built on subsamples of size ψ\psi and c(n)=2(ln⁡(n−1)+γ)−2(n−1)/nc(n) = 2(\ln(n-1) + \gamma) - 2(n-1)/n.

Example: With ψ=256\psi = 256, c=10.245c = 10.245; a point isolated in 4 cuts on average scores 0.763.

Related: Anomaly detection

Lesson: Anomaly detection

KL divergence

The extra surprise you pay for believing distribution Q when reality follows P. Zero only when they match; not symmetric.

Formal: DKL(P∥Q)=∑xp(x)log⁡p(x)q(x)=H(P,Q)−H(P)≥0D_{\text{KL}}(P \Vert Q) = \sum_x p(x)\log\frac{p(x)}{q(x)} = H(P, Q) - H(P) \ge 0.

Example: For P=[0.7,0.2,0.1]P = [0.7, 0.2, 0.1] and Q=[0.6,0.25,0.15]Q = [0.6, 0.25, 0.15], KL is 0.023 nats; reversed it is 0.024.

Related: Cross-entropy, Entropy, Distillation

Lesson: Information theory

KV cache

Saved attention keys and values of earlier tokens, so generation doesn't recompute the whole prefix for every new token.

Formal: Cached K,VK, V tensors per layer; each new token computes only its own query against them, O(n)O(n) per step.

Example: Long contexts and large batches make the KV cache the main GPU-memory cost of serving.

Related: Attention, Context window

Lesson: Self-attention

Label

The correct answer attached to a training example.

Formal: The target value yiy_i paired with features xix_i in supervised data.

Example: "Spam" or "not spam" for an email.

Related: Feature, Loss

Lesson: The language of ML

Label smoothing

Training against slightly softened targets (a little probability on every wrong class) so the model can't push its logits to infinity.

Formal: target =(1−ε) one-hot+ε/K= (1 - \varepsilon)\,\text{one-hot} + \varepsilon / K.

Example: With ε=0.1\varepsilon = 0.1 and 10 classes, the true class's target is 0.91 and every other class gets 0.01.

Related: Cross-entropy, Calibration, Regularization

Lesson: Loss functions

Latent diffusion

Running a diffusion model on a compressed representation from a frozen autoencoder instead of on raw pixels, then decoding once at the end.

Formal: Train E,DE, \mathcal{D}; set z0=sfE(x)z_0 = s_f E(x); train ϵθ(zt,t,c)\epsilon_\theta(z_t, t, c) on zt=αˉtz0+1−αˉtϵz_t = \sqrt{\bar\alpha_t} z_0 + \sqrt{1 - \bar\alpha_t}\epsilon; generate x=D(z0/sf)x = \mathcal{D}(z_0 / s_f).

Example: Stable Diffusion 1.5 maps 512×512×3 images to 64×64×4 latents, 48 times fewer values.

Related: Classifier-free guidance, Flow matching

Lesson: Latent diffusion and Stable Diffusion

Learning rate

How big a step the optimizer takes each update.

Formal: The scalar η\eta in θ←θ−η∇L\theta \leftarrow \theta - \eta\nabla L; often scheduled (warmup, decay).

Example: Too high diverges (loss explodes); too low trains very slowly.

Related: Gradient descent, Hyperparameter

Lesson: Gradient descent

Learning-rate warmup

Starting training with a small learning rate and raising it linearly to its peak over the first steps, before decaying it.

Formal: ηt=ηmax⁡ t/Tw\eta_t = \eta_{\max}\, t / T_w for t<Twt < T_w, usually followed by cosine decay.

Example: max 3e-4 with 100 warmup steps gives 1.5e-4 at step 49.

Lesson: Training and regularization

Load balancing (MoE)

Keeping a mixture-of-experts router from sending most tokens to the same few experts.

Formal: Either an auxiliary loss αE∑eFePe\alpha E \sum_e F_e P_e (1 when uniform), or a per-expert selection bias nudged down for overloaded experts and up for underloaded ones, which leaves the gates unchanged.

Example: With 8 experts and top-2 on 12 tokens, balancing cut the busiest expert from 8 requests to 4 and dropped assignments from 6 to 2.

Related: Mixture of experts

Lesson: Mixture of experts

Local outlier factor (LOF)

An anomaly score comparing a point's local density with the density around its neighbors.

Formal: The ratio of the neighbors' average local reachability density to the point's own; values well above 1 mean the point is in a sparser region than its neighbors.

Example: A point just outside a tight cluster gets a high LOF even if it is closer to the cluster than normal points in a wide cluster are to theirs.

Related: Isolation forest, Anomaly detection

Lesson: Anomaly detection

Log-sum-exp trick

Turning log scores into probabilities without overflow or underflow by subtracting the largest score before exponentiating.

Formal: log⁡∑iesi=m+log⁡∑iesi−m\log\sum_i e^{s_i} = m + \log\sum_i e^{s_i - m} with m=max⁡isim = \max_i s_i.

Example: scores (−1000,−1001)(-1000, -1001) underflow to 0/00/0 directly; shifted to (0,−1)(0, -1) they give probabilities (0.731,0.269)(0.731, 0.269).

Lesson: Naive Bayes

Logit

The raw score a model outputs before it is turned into a probability.

Formal: For logistic regression, z=w⋅x+bz = w\cdot x + b; the probability is σ(z)\sigma(z). For multiclass models and LLMs, a vector of logits feeds softmax.

Example: A logit of 0 corresponds to probability 0.5.

Related: Softmax, Calibration

Lesson: Logistic regression

LoRA

A cheap way to fine-tune a large model by training small add-on matrices instead of all the weights.

Formal: W=W0+αrBAW = W_0 + \frac{\alpha}{r}BA with frozen W0W_0 and trainable low-rank B∈Rdout×rB \in \mathbb{R}^{d_{\text{out}}\times r}, A∈Rr×dinA \in \mathbb{R}^{r \times d_{\text{in}}}.

Example: Rank 8 on a 4096 × 4096 matrix trains 65,536 parameters instead of 16.8 million.

Related: Fine-tuning

Lesson: Adapting LLMs

Loss

A single number measuring how wrong the model's predictions are, which training tries to minimize.

Formal: L(θ)=1n∑iℓ(fθ(xi),yi)L(\theta) = \frac{1}{n}\sum_i \ell(f_\theta(x_i), y_i), plus any regularization terms.

Example: Mean squared error for regression; cross-entropy for classification.

Related: Metric, Gradient descent

Lesson: The language of ML

Loss scaling

Multiplying the loss by a big number before backward so tiny fp16 gradients do not round to zero, then dividing it back out.

Formal: ∇(SL)=S∇L\nabla(S\mathcal{L}) = S\nabla\mathcal{L}. A dynamic scaler skips the step and halves SS when any gradient overflows, and doubles SS after a run of clean steps (2,000 by default in PyTorch). Not needed with bf16.

Example: A gradient of 10−810^{-8} is 0 in fp16; times 2162^{16} it is 6.55×10−46.55 \times 10^{-4}, which fp16 can hold.

Related: Mixed precision

Lesson: Gradient clipping and mixed precision

Lost in the middle

The tendency of language models to use information at the start or end of a long context more reliably than information in the middle.

Formal: Answer accuracy as a function of the relevant passage's position in the input is often U-shaped (Liu et al., 2023); the size of the effect varies by model and task.

Example: Ordering retrieved chunks so the most relevant sit first and last, with the weakest in the middle, is a common mitigation.

Related: Context engineering, Context window

Lesson: Context engineering

Markov decision process

The standard way to write down a sequential decision problem: what the agent sees, what it can do, what happens next, and what score it gets.

Formal: A tuple (S,A,P,r,γ)(\mathcal{S}, \mathcal{A}, P, r, \gamma) of states, actions, transition probabilities P(s′∣s,a)P(s' \mid s, a), rewards, and a discount, where the next state depends only on the current state and action (the Markov property).

Example: In a grid world the state is the cell, actions are the four moves, and each move costs −1 until the goal.

Related: Bellman equation, Discount factor

Lesson: MDPs, states, actions, and rewards

MASE

Mean absolute scaled error: forecast error divided by the error of the seasonal-naive forecast, so it compares across series of any scale.

Formal: MASE=MAE/(1T−m∑t>m∣yt−yt−m∣)\text{MASE} = \text{MAE} / \big(\frac{1}{T-m}\sum_{t>m} |y_t - y_{t-m}|\big); below 1 beats seasonal naive.

Example: MAE 3.6 against a seasonal-naive MAE of 4.5 gives MASE 0.8.

Related: Baseline, Metric

Lesson: Time series

Masked language modeling

A pretraining task where some tokens are hidden and the model guesses them using the words on both sides.

Formal: Select about 15% of positions M\mathcal{M}; replace 80% with [MASK], 10% with a random token, keep 10%; minimize −1∣M∣∑i∈Mlog⁡P(xi∣x~)-\frac{1}{\lvert\mathcal{M}\rvert}\sum_{i \in \mathcal{M}} \log P(x_i \mid \tilde{x}) with a bidirectional encoder.

Example: In "the cat [MASK] on the mat", the words on both sides make "sat" the likely answer.

Related: Attention, Cross-entropy, Embedding

Lesson: BERT and masked language modeling

Matthews correlation coefficient

A score for a yes/no classifier that uses all four cells of the confusion matrix and is 0 for any constant or random predictor, so it can't be gamed by predicting the majority class.

Formal: MCC=TP⋅TN−FP⋅FN(TP+FP)(TP+FN)(TN+FP)(TN+FN)\text{MCC} = \dfrac{TP \cdot TN - FP \cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}, ranging from −1-1 to +1+1.

Example: TP=27TP = 27, FP=128FP = 128, FN=7FN = 7, TN=638TN = 638 gives MCC =16330/51026.9=0.320= 16330 / 51026.9 = 0.320, while accuracy is 0.831.

Related: Average precision, Metric

Lesson: Imbalanced data

Mean average precision

The standard detection score: how well confidence ranks correct boxes above wrong ones, averaged over classes (and, for COCO, over IoU thresholds).

Formal: AP is the area under the interpolated precision-recall curve at one IoU threshold; mAP averages AP over classes; mAP@0.5:0.95 also averages over IoU thresholds 0.50, 0.55, ..., 0.95.

Example: Detections ranked TP, TP, FP, FP, TP against 3 objects give AP@0.5 = 0.867.

Related: Intersection over union, Metric

Lesson: Object detection and YOLO

Mel spectrogram

A spectrogram whose frequency axis is pooled into bands spaced the way human pitch perception is: narrow at low frequencies, wide at high ones.

Formal: S=log⁡(max⁡(PB⊤,ϵ))S = \log(\max(P B^\top, \epsilon)) where PP is the power spectrogram and BB is a matrix of triangular filters equally spaced on the mel scale m=2595log⁡10(1+f/700)m = 2595 \log_{10}(1 + f/700).

Example: 80 mel filters turn a 98×25798 \times 257 power spectrogram into a 98×8098 \times 80 log-mel spectrogram, the input format of models like Whisper.

Related: Spectrogram, MFCC

Lesson: Spectrograms and mel features

Metric

How people judge a model's performance, which can differ from the loss used for training.

Formal: Any evaluation function of predictions and labels, possibly non-differentiable and threshold-dependent.

Example: RMSE in dollars, recall at a review budget, p95 latency, cost per request.

Related: Loss, Baseline

Lesson: The language of ML

MFCC

Mel-frequency cepstral coefficients: a compact summary of each audio frame's spectral shape, made by compressing the log-mel spectrum.

Formal: Apply a type-II discrete cosine transform to each log-mel frame and keep the first (usually 13) coefficients; coefficient 0 tracks overall energy.

Example: A 98×8098 \times 80 log-mel spectrogram becomes a 98×1398 \times 13 MFCC matrix.

Related: Mel spectrogram

Lesson: Spectrograms and mel features

Minimum detectable effect

The smallest true improvement an experiment is designed to detect reliably.

Formal: The effect size δ\delta at which the test has the chosen power 1−β1 - \beta at significance α\alpha; the sample size per arm scales as 1/δ21/\delta^2.

Example: Detecting 10% → 11% conversion (a 10% relative MDE) at α=0.05\alpha = 0.05 and power 0.8 takes 14,749 users per arm; halving the MDE takes about four times as many.

Related: Statistical power, P-value

Lesson: Experimentation and A/B testing

Mixed precision

Training with most math in a 16-bit format (bf16 or fp16) for speed and memory, while keeping master weights and sensitive reductions in float32.

Formal: bf16 has float32's 8 exponent bits and 7 fraction bits; fp16 has 5 and 10 (max 65,504), so fp16 needs dynamic loss scaling to keep small gradients from flushing to zero.

Example: torch.autocast(device_type="cuda", dtype=torch.bfloat16) runs matmuls in bf16 without a loss scaler.

Related: Quantization, Log-sum-exp trick

Lesson: Numerical stability

Mixture of experts

A model whose feed-forward layers are split into many "experts", with a router sending each token to only a few of them, so it has many parameters but uses few per token.

Formal: Each MoE layer has EE expert networks and a router that picks the top kk per token. Total parameters set memory; active parameters (shared plus kk experts) set compute per token.

Example: 4B shared + 16 experts × 2B with top-2 routing: 36B total (72 GB in BF16), 8B active per token.

Related: Parameter, Inference

Lesson: LLM inference

Mode collapse

A generator failure where it produces only a few kinds of output and ignores parts of the data distribution.

Formal: pgp_g concentrates on a subset of the modes of pdatap_{\text{data}}; shows up as low recall or coverage even when sample quality and losses look fine.

Example: A GAN trained on two clusters at -2 and +2 puts every sample near +2.

Related: GAN

Lesson: GANs, generator versus discriminator

Model Context Protocol (MCP)

An open standard for connecting AI applications to tools and data, so one integration works with many apps.

Formal: MCP clients inside a host application talk JSON-RPC (over stdio or HTTP) to MCP servers, which expose tools (callable functions), resources (readable data), and prompts (templates).

Example: An issue-tracker MCP server lets any compliant IDE or agent search and create tickets without custom glue code.

Related: Tool calling, Agent, Prompt injection

Lesson: Tool use and agents

Multi-agent system

Several LLM agents, each with its own prompt and context, that split a task and pass messages, usually coordinated by an orchestrator.

Formal: Designs range from fixed pipelines and fan-out/fan-in to orchestrator-worker (a model plans subtasks and delegates them) and peer swarms. Parallel workers cut the critical path from ksks to about s+2s + 2 calls; total tokens depend on how much each worker re-explores.

Example: An orchestrator sends four research briefs to parallel workers and synthesizes their 400-token summaries.

Related: Agent, ReAct

Lesson: Multi-agent systems

Multi-head latent attention

DeepSeek's attention variant that caches one small compressed vector per token instead of full keys and values for every head.

Formal: Hidden states are projected down to a latent of size rr (kv_lora_rank), cached together with a shared RoPE key, and projected back up to per-head keys and values at attention time.

Example: DeepSeek-V3 caches (512+64)⋅2⋅61=70,272(512 + 64) \cdot 2 \cdot 61 = 70{,}272 bytes per token, 71× less than full keys and values for 128 heads.

Related: Grouped-query attention, KV cache

Lesson: Open models: architecture walkthroughs

Mutual information

How much knowing one variable reduces uncertainty about another; catches non-linear relationships that correlation misses.

Formal: I(X;Y)=∑x,yp(x,y)ln⁡p(x,y)p(x)p(y)I(X;Y) = \sum_{x,y} p(x,y) \ln \frac{p(x,y)}{p(x)p(y)}, which is 0 exactly when XX and YY are independent.

Example: For y=x2y = x^2 with xx symmetric around 0, correlation is about 0 but mutual information is large.

Related: Feature

Lesson: Feature engineering

Named entity recognition

Finding names of people, organizations, places, and other typed things in text, as spans.

Formal: A sequence-labeling task mapping tokens x1..xnx_1..x_n to tags y1..yny_1..y_n (usually BIO), evaluated with entity-level precision, recall, and F1 on exact span and type matches.

Example: "Ada Lovelace joined Acme Corp" yields (Ada Lovelace, PER) and (Acme Corp, ORG).

Related: BIO tagging, Viterbi algorithm

Lesson: Named entity recognition

Nested cross-validation

Cross-validation wrapped around a whole tuning procedure, so the reported score isn't inflated by picking the best of many trials.

Formal: Outer folds hold out test data; inside each, an inner CV selects hyperparameters; the outer scores are averaged.

Example: A search's best inner score of 0.88 next to a nested score of 0.85 shows the selection optimism.

Related: Hyperparameter, Overfitting

Lesson: Hyperparameter tuning

Non-maximum suppression

The cleanup step after a detector: keep the highest-scoring box, delete boxes that overlap it too much, repeat.

Formal: Greedy: sort boxes by score; repeatedly keep the top box and remove every remaining box with IoU above a threshold (often 0.45 to 0.7), usually per class.

Example: Three boxes on one object with IoUs above 0.6 to the best one collapse to that single box at threshold 0.5.

Related: Intersection over union

Lesson: Object detection and YOLO

Normal equation

The closed-form solution to least-squares linear regression, found by setting the gradient of the squared error to zero.

Formal: X⊤X θ=X⊤yX^\top X\,\theta = X^\top y, solved with a linear solver rather than an explicit inverse.

Example: For x=[1,2,3]x = [1, 2, 3], y=[2,4,5]y = [2, 4, 5] it gives w=1.5w = 1.5, b=0.667b = 0.667.

Lesson: Linear regression

One-hot encoding

Turning a category into one 0/1 column per possible value, so no fake ordering is implied.

Formal: A category cc among KK values maps to the unit vector ec∈{0,1}Ke_c \in \{0,1\}^K.

Example: color = green among {red, green, blue} becomes [0,1,0][0, 1, 0].

Related: Target encoding, Feature

Lesson: Feature engineering

Out-of-bag error

A free validation estimate for a random forest: score each row using only the trees that never saw it during training.

Formal: For row ii, average the predictions of trees whose bootstrap sample excluded ii; compute the metric over all rows.

Example: In scikit-learn, RandomForestClassifier(oob_score=True) exposes it as oob_score_.

Related: Bootstrap sample

Lesson: Random forests and gradient boosting

Overfitting

When a model learns the training data's noise and does worse on new data.

Formal: A large gap between training and validation performance, typically from high variance.

Example: A degree-15 polynomial with training MSE 0.056 and validation MSE 0.52.

Related: Regularization, Bias-variance trade-off

Lesson: Overfitting and bias-variance

P-value

How surprising the observed result would be if the change actually did nothing.

Formal: P(test statistic at least as extreme as observed∣H0)P(\text{test statistic at least as extreme as observed} \mid H_0). It is not P(H0∣data)P(H_0 \mid \text{data}).

Example: z=2.825z = 2.825 in a two-sided test gives p=2(1−Φ(2.825))=0.0047p = 2(1 - \Phi(2.825)) = 0.0047.

Related: Statistical power, Sample ratio mismatch

Lesson: Experimentation and A/B testing

Paged attention

Storing each sequence's KV cache in small fixed-size blocks allocated as needed, like virtual-memory pages, instead of one big reserved region.

Formal: A per-sequence block table maps logical token positions to physical KV blocks (for example 16 tokens each). Waste is under one block per sequence, and blocks can be shared between sequences with a common prefix.

Example: With a 40 GB KV budget and 600-token requests, reserving 4,096 tokens each fits 74 sequences; 16-token blocks fit 501.

Related: KV cache, Continuous batching, Prefix caching

Lesson: Serving LLMs

Parameter

A number the model learns from data during training.

Formal: An entry of θ\theta, the vector of values the optimizer adjusts to minimize the loss L(θ)L(\theta).

Example: The slope ww and bias bb in y^=wx+b\hat{y} = wx + b.

Related: Hyperparameter, Gradient

Lesson: Linear regression

pass@k

The chance that at least one of kk generated programs passes the tests.

Formal: From nn samples with cc passing, the unbiased estimate is 1−(n−ck)/(nk)1 - \binom{n-c}{k} / \binom{n}{k}.

Example: n=20n = 20, c=3c = 3: pass@1 = 0.15, pass@5 = 0.601.

Related: Calibration

Lesson: Evaluating LLM systems

pass^k

The chance an agent gets a task right on every one of kk independent tries, a measure of consistency.

Formal: For per-trial success rate ss, passk=sk\text{pass}^k = s^k, versus pass@k=1−(1−s)k\text{pass@}k = 1 - (1-s)^k (at least one success).

Example: With s=0.7s = 0.7, pass^3 =0.343= 0.343 while pass@3 =0.973= 0.973.

Related: Agent, Metric

Lesson: Building reliable agents

Per-channel quantization

Each row (output channel) of a weight matrix gets its own scale, so one large weight doesn't crush the precision of the rest.

Formal: s_i = max_j |W_ij| / 127, q_ij = round(W_ij / s_i).

Related: Quantization

Lesson: LLM inference

Perceptron

A single neuron with a hard threshold that outputs 1 if its weighted sum is at least 0, trained by nudging weights toward misclassified points.

Formal: y^=[w⋅x+b≥0]\hat{y} = [w \cdot x + b \ge 0]; on a mistake, w←w+η(y−y^)xw \leftarrow w + \eta (y - \hat{y}) x, b←b+η(y−y^)b \leftarrow b + \eta (y - \hat{y}).

Example: It learns AND in a few passes but never converges on XOR, because no line separates XOR's classes.

Lesson: The neural-network forward pass

Permutation test

A significance test that shuffles group labels to see how often chance alone produces a difference as large as the one observed.

Formal: p = (number of shuffles with |difference| ≥ observed + 1) / (number of shuffles + 1).

Example: Comparing per-example scores of two models: p = 0.004 means about 4 in 1,000 random relabelings beat the real gap.

Lesson: Probability and statistics

Perplexity

How "surprised" a language model is by text, roughly the number of tokens it's choosing between.

Formal: exp⁡\exp of the mean next-token cross-entropy.

Example: Mean loss 1.25 gives perplexity 3.49; uniform guessing over 50,000 tokens gives 50,000.

Related: Cross-entropy, Token

Lesson: Tokenization and pretraining

Pipeline parallelism

Giving each GPU a block of consecutive layers, like stations on an assembly line, and streaming micro-batches through.

Formal: With pp stages and mm micro-batches, a GPipe schedule is idle for (p−1)/(m+p−1)(p-1)/(m+p-1) of the step (the pipeline bubble). Only boundary activations cross between GPUs.

Example: 4 stages and 16 micro-batches leave 3/19≈16%3/19 \approx 16\% of the schedule idle.

Related: Tensor parallelism, Data parallelism

Lesson: Scaling and distributed training

Point-in-time join

Joining each training label to the feature values as they were at the label's timestamp, never later ones.

Formal: For label (entity e, time t), use the feature row for e with the largest timestamp s ≤ t (optionally s ≥ t − TTL).

Example: A churn label at day 70 uses the day-70 snapshot of "days since last purchase", not the day-175 one.

Related: Training-serving skew, Feature store, Data leakage

Lesson: ML system design

Policy gradient

A way to train a policy directly: make actions that led to better-than-expected outcomes more likely, and worse ones less likely.

Formal: ∇θJ(θ)=Eτ∼πθ[∑tAt∇θlog⁡πθ(at∣st)]\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\big[\sum_t A_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\big], derived with the log-derivative trick ∇P=P∇log⁡P\nabla P = P \nabla \log P. REINFORCE uses At=Gt−b(st)A_t = G_t - b(s_t).

Example: With logits [0,0.5,−0.5,1][0, 0.5, -0.5, 1] and action 4 taken, ∇zlog⁡π=[−0.167,−0.276,−0.102,0.545]\nabla_z \log \pi = [-0.167, -0.276, -0.102, 0.545]; scaling by an advantage of +0.79+0.79 raises action 4's logit.

Related: Advantage, PPO, Softmax

Lesson: Policy gradients and REINFORCE

Population Stability Index

A score for how much a feature's distribution has moved between a reference window and a current window.

Formal: PSI=∑b(ab−eb)ln⁡(ab/eb)\text{PSI} = \sum_b (a_b - e_b)\ln(a_b / e_b) over bins (usually reference deciles), with ebe_b and aba_b the reference and current shares. Conventional bands: under 0.1 stable, 0.1 to 0.25 moderate, over 0.25 significant.

Example: Two decile bins falling to 5% and one rising to 20% gives PSI 0.139.

Related: Drift, Concept drift

Lesson: Model monitoring and drift

Position bias

Users interact with items partly because of where they are shown, so top slots get more clicks regardless of quality.

Formal: P(click∣item,position)≈P(examined∣position)⋅P(relevant∣item)P(\text{click} \mid \text{item}, \text{position}) \approx P(\text{examined} \mid \text{position}) \cdot P(\text{relevant} \mid \text{item}); training on raw clicks confounds the two factors.

Example: A ranker trained on raw clicks learns to promote whatever the previous model put first, creating a feedback loop; adding position as a feature fixed at serving time, or inverse propensity weighting, corrects for it.

Related: Cold start, Calibration

Lesson: ML system design

PPO

Proximal policy optimization: a policy-gradient method that reuses each batch for several updates but stops rewarding any action's probability change beyond about ±20%.

Formal: Maximizes Et[min⁡(rtA^t,clip⁡(rt,1−ε,1+ε)A^t)]\mathbb{E}_t[\min(r_t \hat A_t, \operatorname{clip}(r_t, 1-\varepsilon, 1+\varepsilon)\hat A_t)] with rt=πθ(at∣st)/πold(at∣st)r_t = \pi_\theta(a_t \mid s_t) / \pi_{\text{old}}(a_t \mid s_t), plus a value loss and often an entropy bonus.

Example: With ε=0.2\varepsilon = 0.2, a sample with r=1.5r = 1.5 and A^=2\hat A = 2 scores min⁡(3.0,2.4)=2.4\min(3.0, 2.4) = 2.4 and contributes no gradient.

Related: Policy gradient, Generalized advantage estimation, GRPO, DPO

Lesson: PPO

Prefill

The first phase of generation, where the model processes the whole prompt in parallel, fills the KV cache, and produces the first output token.

Formal: One forward pass over NN prompt tokens, about 2PN2PN FLOPs for a PP-parameter model. Its arithmetic intensity is about NN FLOPs per byte, so it is compute-bound, unlike decode.

Example: A 2,000-token prompt on an 8B model needs about 3.2×10133.2 \times 10^{13} FLOPs, 32 ms at a peak of 101510^{15} FLOP/s.

Related: KV cache, Time to first token, Inference

Lesson: LLM inference

Prefix caching

Reusing the saved KV cache for a prompt beginning that many requests share, so it isn't recomputed each time.

Formal: KV blocks are keyed by the exact token prefix they encode; a new request whose prompt starts with a cached prefix skips prefill for those tokens and shares the blocks.

Example: A 2,000-token shared system prompt plus 200 user tokens: a cache hit prefills 200 tokens instead of 2,200 (90.9% less).

Related: Prefill, Paged attention, KV cache

Lesson: Serving LLMs

Product quantization

Compressing vectors by cutting each into pieces and storing, for every piece, only the ID of its nearest prototype.

Formal: Split x∈Rdx \in \mathbb{R}^d into mm subvectors, learn 256 centroids per position with k-means, store mm one-byte codes; query distances are sums of mm precomputed table lookups.

Example: A 768-dimensional float32 vector (3,072 bytes) with m=96m = 96 takes 96 bytes, 32 times smaller.

Related: BM25

Lesson: Vector search

Prompt injection

Text that tries to override a model's instructions, typed by a user or hidden in content the model reads.

Formal: Adversarial input exploiting the model's inability to separate trusted instructions from untrusted data; indirect injection arrives via retrieved documents, pages, emails, or tool outputs.

Example: A web page containing hidden text telling the assistant to email the user's invoices elsewhere.

Related: Agent, Tool calling

Lesson: Securing AI systems

Q-learning

An off-policy TD method that learns the value of acting greedily, whatever exploring the agent does while it learns.

Formal: Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha[r + \gamma \max_{a'} Q(s', a') - Q(s, a)]; converges to Q∗Q^* if every pair keeps being visited.

Example: Q=−2Q = -2, r=−1r = -1, best next value −1.5-1.5, γ=0.9\gamma = 0.9, α=0.5\alpha = 0.5: the new value is −2.175-2.175.

Related: SARSA, Epsilon-greedy, Temporal-difference learning

Lesson: Q-learning and SARSA

Q-value

How much total reward you expect if you take a particular action in a particular state and then keep following your policy.

Formal: Qπ(s,a)=Eπ[Gt∣st=s,at=a]Q^\pi(s, a) = \mathbb{E}_\pi[G_t \mid s_t = s, a_t = a]; the state value is Vπ(s)=∑aπ(a∣s)Qπ(s,a)V^\pi(s) = \sum_a \pi(a \mid s) Q^\pi(s, a).

Example: Acting greedily means picking arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a).

Related: Q-learning, Bellman equation

Lesson: MDPs, states, actions, and rewards

QLoRA

LoRA fine-tuning on top of a base model stored in 4-bit precision, so large models fit on a single smaller GPU.

Formal: Frozen base weights stored in 4-bit NF4 with blockwise (double-quantized) scales, dequantized to bf16 on the fly; only 16-bit LoRA matrices A,BA, B receive gradients.

Example: A synthetic 7B-style model needs about 108.6 GB to fully fine-tune but about 5.3 GB with QLoRA at rank 16.

Related: LoRA, Quantization

Lesson: Fine-tuning in practice

Quantization

Storing model weights with fewer bits to save memory and often speed up inference.

Formal: Mapping weights from 16 or 32-bit floats to 8 or 4-bit integers with scale factors; memory = parameters × bits / 8.

Example: A 7B model needs 14 GB in fp16 and 3.5 GB in int4.

Related: Distillation, Inference

Lesson: Reliability, cost, and observability

Query rewriting

Changing the user's question before retrieval so it uses the words and shape the documents use.

Formal: Common forms: multi-query (several paraphrases, results fused), HyDE (embed a model-written hypothetical answer), and decomposition (split into sub-questions).

Example: "Can I get reimbursed for a game I never opened?" gains "refund", "digital downloads", and "accessed", and now matches the refund policy.

Related: BM25

Lesson: RAG pipeline

RAG

Retrieval-augmented generation: look up relevant documents at query time and give them to the model to answer from.

Formal: A pipeline of ingestion, chunking, indexing, retrieval, optional reranking, context construction, and grounded generation; it changes the model's context, not its weights.

Example: A support bot retrieves the current refund policy and cites it.

Related: Grounding, Fine-tuning

Lesson: The RAG pipeline

ReAct

An agent pattern where the model alternates short reasoning notes with tool calls and reads each result before deciding the next step.

Formal: The trajectory interleaves thought, action, and observation: (τ1,a1,o1,τ2,a2,o2,… )(\tau_1, a_1, o_1, \tau_2, a_2, o_2, \dots), each generated conditioned on everything before it.

Example: "UA412 is cheapest; check refundability" → get_fare_rules(UA412) → {"refundable": false} → "check AS330".

Related: Agent, Tool calling

Lesson: Tool use and agents

Receptive field

The patch of the input image that can influence one output pixel of a CNN layer.

Formal: Each layer adds (k−1)×(k - 1) \times (product of earlier strides) pixels.

Example: Three stacked 3×3 stride-1 convolutions have a 7×7 receptive field.

Lesson: Convolutional networks

Reciprocal rank fusion

A way to merge ranked lists from different search methods using only each document's rank, not its score.

Formal: RRF(d)=∑j1c+rankj(d)\text{RRF}(d) = \sum_j \frac{1}{c + \text{rank}_j(d)}, commonly c=60c = 60.

Example: A document ranked 1st by dense search and 3rd by BM25 scores 1/61+1/63=0.03231/61 + 1/63 = 0.0323.

Related: BM25, RAG

Lesson: Vector search

Reduce-scatter

Summing tensors across GPUs but giving each GPU only its own slice of the result.

Formal: Each of NN ranks ends with the reduced values of one 1/N1/N chunk; it sends N−1NT\frac{N-1}{N}T bytes per rank. The first half of a ring all-reduce.

Example: In ZeRO, each GPU receives the summed gradient for only the parameters whose optimizer state it owns.

Related: All-reduce, All-gather, ZeRO

Lesson: Collective operations from scratch

Regularization

Anything that discourages a model from memorizing, so it generalizes better.

Formal: Penalties (λ∥w∥2\lambda\lVert w\rVert^2, λ∥w∥1\lambda\lVert w\rVert_1) or procedures (dropout, early stopping, augmentation) that reduce variance.

Example: Ridge regression shrinks the slope from 1.5 to 0.6 with λ=1\lambda = 1 in the course example.

Related: Overfitting

Lesson: Regularization and regression metrics

Reparameterization trick

Writing a random sample as a deterministic function of the model's outputs plus independent noise, so gradients can flow through the sampling step.

Formal: z=μ+σϵz = \mu + \sigma \epsilon with ϵ∼N(0,1)\epsilon \sim \mathcal{N}(0, 1).

Example: μ=1\mu = 1, σ=1\sigma = 1, ϵ=0.5\epsilon = 0.5 gives z=1.5z = 1.5.

Lesson: Autoencoders, diffusion, and transfer learning

Reward model

A model that reads a response and outputs one number saying how much people would prefer it.

Formal: Trained on preference pairs with the Bradley-Terry loss −log⁡σ(r(yw)−r(yl))-\log \sigma(r(y_w) - r(y_l)), where ywy_w is the chosen and yly_l the rejected response.

Example: In RLHF, PPO updates the policy to raise the reward model's score while a KL penalty keeps it near the reference model.

Related: Calibration

Lesson: Adapting LLMs

RMSNorm

A simpler layer normalization that rescales activations by their root-mean-square, without subtracting the mean or adding a bias.

Formal: RMSNorm(x)=γ⊙x/1h∑ixi2+ϵ\text{RMSNorm}(x) = \gamma \odot x / \sqrt{\tfrac{1}{h}\sum_i x_i^2 + \epsilon}, with one learned scale vector γ\gamma of size hh.

Example: Llama 3 8B has 65 RMSNorms of 4,096 parameters each (two per block plus a final one).

Related: SwiGLU, RoPE

Lesson: Open models: architecture walkthroughs

Robust z-score

A z-score that uses the median and median absolute deviation, so outliers can't hide by inflating the mean and spread.

Formal: zrobust=0.6745 (x−x~)/MADz^{\text{robust}} = 0.6745\,(x - \tilde x)/\text{MAD}, with MAD=median∣xi−x~∣\text{MAD} = \text{median}|x_i - \tilde x|; a common cutoff is 3.5.

Example: In [10,11,12,12,13,14,50][10, 11, 12, 12, 13, 14, 50], 50 has plain z 2.44 but robust z 25.6.

Related: Anomaly detection

Lesson: Anomaly detection

RoPE

Rotary position embedding: positions are encoded by rotating each query and key by an angle that grows with position, so attention scores depend on relative distance.

Formal: Pairs of dimensions (x2i,x2i+1)(x_{2i}, x_{2i+1}) at position mm are rotated by angle mθim\theta_i with θi=base−2i/d\theta_i = \text{base}^{-2i/d} (rope_theta is the base). Then qm⋅knq_m \cdot k_n depends only on m−nm - n.

Example: Llama 3 uses rope_theta = 500000; methods such as YaRN rescale the angles to extend context.

Related: Attention

Lesson: Open models: architecture walkthroughs

Rotary position embedding (RoPE)

A way to give attention position information by rotating each pair of query and key features by an angle proportional to the token's position.

Formal: Rotating qq by pθp\theta and kk by mθm\theta makes q⋅kq \cdot k depend only on the offset p−mp - m.

Example: Used by most current open LLMs in place of a learned position table.

Lesson: The transformer architecture

Sample ratio mismatch

When the number of users in each arm of an experiment differs from the planned split by more than chance allows, a sign that assignment or logging is broken.

Formal: Tested with a chi-square goodness-of-fit test on arm counts against the designed allocation; a tiny p-value (often below 0.001) invalidates the experiment's readout.

Example: 50,600 versus 49,400 users in a 50/50 test gives χ2=14.4\chi^2 = 14.4 and p≈0.00015p \approx 0.00015.

Related: P-value

Lesson: Experimentation and A/B testing

SARSA

An on-policy TD method that learns the value of the policy it is actually running, exploration included.

Formal: Q(s,a)←Q(s,a)+α[r+γQ(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha[r + \gamma Q(s', a') - Q(s, a)], where a′a' is the action the agent will actually take next.

Example: On a cliff grid, SARSA learns a path one row away from the edge because its targets include its own random moves.

Related: Q-learning, Epsilon-greedy

Lesson: Q-learning and SARSA

Scaling law

A measured power-law relationship that predicts a model's loss from its size, its training data, or its training compute.

Formal: The Chinchilla form is L(N,D)=E+A/Nα+B/DβL(N, D) = E + A/N^\alpha + B/D^\beta, with training compute C≈6NDC \approx 6ND.

Example: With Hoffmann et al.'s fitted constants, a 70B model on 1.4T tokens is predicted to reach loss 1.937.

Related: Chinchilla-optimal, Cross-entropy

Lesson: Scaling laws

Self-consistency

Sampling several reasoning chains and returning the most common final answer.

Formal: With NN independent chains each correct with probability pp, a strict majority is correct with probability ∑k>N/2(Nk)pk(1−p)N−k\sum_{k > N/2} \binom{N}{k} p^k (1-p)^{N-k}; plurality voting can do better when wrong answers scatter.

Example: p=0.7p = 0.7, N=5N = 5 gives at least 0.837; if wrong chains agree and p=0.4p = 0.4, voting drops to 0.317.

Related: Chain-of-thought, Temperature

Lesson: Few-shot and chain-of-thought

Self-training

A semi-supervised recipe: train on the few labeled rows, label the unlabeled rows the model is confident about, add them, and retrain.

Formal: Repeat: fit ff on DL\mathcal{D}_L; for x∈DUx \in \mathcal{D}_U with max⁡kPf(k∣x)≥τ\max_k P_f(k \mid x) \ge \tau, add (x,arg⁡max⁡kPf(k∣x))(x, \arg\max_k P_f(k \mid x)) to DL\mathcal{D}_L.

Example: With 6 labels and threshold 0.9 on two well-separated synthetic blobs, self-training reaches about the same accuracy as using all 200 labels.

Lesson: Learning paradigms

Semantic cache

Reuse a stored answer when a new query is similar enough to a stored one.

Formal: Serve the cached answer if cos(embed(q), embed(q_stored)) ≥ τ.

Lesson: Reliability, cost, and observability

Sequential testing

An A/B test design that lets you look at results repeatedly and stop early without inflating false positives.

Formal: An always-valid procedure such as the mixture SPRT: stop when the mixture likelihood ratio Λ_n ≥ 1/α; under H0 the chance Λ_n ever crosses is at most α (Ville's inequality).

Example: In 4,000 synthetic A/A tests with 14 daily looks, naive peeking gave a 0.216 false-positive rate and mSPRT gave 0.013.

Related: p-value, Statistical power

Lesson: Experimentation and A/B testing

Shadow traffic

Mirror real requests to a candidate and log its output without returning it to users.

Lesson: Production architecture

Silhouette score

How well a point fits its own cluster compared with the nearest other cluster, averaged over all points. Near 1 means tight, well-separated clusters; near 0 means points sit on boundaries; negative means likely misassigned.

Formal: si=(bi−ai)/max⁡(ai,bi)s_i = (b_i - a_i)/\max(a_i, b_i), where aia_i is the mean distance from point ii to the rest of its cluster and bib_i the mean distance to the nearest other cluster.

Example: ai=1a_i = 1, bi=4b_i = 4 gives si=3/4=0.75s_i = 3/4 = 0.75.

Lesson: K-means clustering

Singular value decomposition (SVD)

Any matrix factors into a rotation, a stretch along perpendicular axes, and another rotation. On centered data, the axes are the principal components.

Formal: X=USV⊤X = U S V^\top with orthonormal columns in UU and VV and nonnegative singular values sks_k on the diagonal of SS. For centered data, PCA variances are λk=sk2/(n−1)\lambda_k = s_k^2/(n-1).

Example: five centered points with PCA variance λ1=3.771\lambda_1 = 3.771 have s12=4×3.771=15.08s_1^2 = 4 \times 3.771 = 15.08, so s1≈3.88s_1 \approx 3.88.

Lesson: PCA, t-SNE, and UMAP

Sliding-window attention

Attention where each token looks only at the last few tokens instead of the whole sequence.

Formal: Query ii may attend key jj only if j≤ij \le i and i−j<wi - j < w. Cost is O(nw)O(nw) per layer, the KV cache holds ww tokens per layer, and LL stacked layers reach L(w−1)+1L(w-1)+1 positions.

Example: With n=16n = 16 and w=4w = 4, the mask has 58 cells instead of 136 for causal attention.

Related: Attention, KV cache, Context window

Lesson: Attention variants

SMOTE

A way to add synthetic examples of a rare class by placing new points between real rare-class points that are close together.

Formal: For a minority point xix_i and one of its kk nearest minority neighbors xjx_j, SMOTE (Synthetic Minority Over-sampling Technique) creates xi+λ(xj−xi)x_i + \lambda (x_j - x_i) with λ∼U[0,1)\lambda \sim U[0, 1).

Example: From (1.0,2.0)(1.0, 2.0) and neighbor (1.5,2.5)(1.5, 2.5) with λ=0.4\lambda = 0.4, SMOTE adds (1.2,2.2)(1.2, 2.2). Apply it only inside training folds.

Related: Data leakage, Class weights

Lesson: Imbalanced data

Soft-thresholding

The lasso's update for one weight: shrink it toward zero by a fixed amount, and set it to exactly zero if it would cross zero.

Formal: S(z,g)=sign⁡(z)max⁡(∣z∣−g,0)S(z, g) = \operatorname{sign}(z)\max(|z| - g, 0).

Example: S(1.0,0.25)=0.75S(1.0, 0.25) = 0.75, S(−1.0,0.25)=−0.75S(-1.0, 0.25) = -0.75, S(0.2,0.25)=0S(0.2, 0.25) = 0.

Related: Coordinate descent

Lesson: Regularization and regression metrics

Softmax

Turns a list of scores into probabilities that are all positive and add up to 1.

Formal: pi=ezi/T/∑jezj/Tp_i = e^{z_i/T}/\sum_j e^{z_j/T} with temperature TT.

Example: Logits [2,1,0.1][2, 1, 0.1] become [0.659,0.242,0.099][0.659, 0.242, 0.099].

Related: Logit, Temperature

Lesson: Logistic regression

Spectrogram

A time-by-frequency picture of sound: how much energy each frequency has in each short slice of time.

Formal: The squared magnitude of the short-time Fourier transform: frame the waveform (window WW, hop HH), multiply by a window function, FFT each frame; shape F×(Nfft/2+1)F \times (N_{\text{fft}}/2 + 1).

Example: One second at 16 kHz with a 400-sample window, 160-sample hop, and 512-point FFT gives a 98×25798 \times 257 spectrogram.

Related: Mel spectrogram, MFCC

Lesson: Spectrograms and mel features

Speculative decoding

A cheap draft model guesses several next tokens, and the large model checks them all in one pass, keeping the ones it agrees with.

Formal: With draft length γ\gamma and per-token acceptance rate α\alpha, the expected tokens per target pass is (1−αγ+1)/(1−α)(1 - \alpha^{\gamma+1})/(1 - \alpha). With rejection-sampling verification, outputs follow the target model's distribution exactly.

Example: α=0.8\alpha = 0.8, γ=4\gamma = 4: 3.36 tokens per target pass; with draft cost 0.05 per token, a 2.8× speedup.

Related: Inference, Temperature

Lesson: LLM inference

Spotlighting

Visibly mark untrusted text (for example with datamarking) so the model treats it as data; it lowers injection success but is not a security boundary.

Related: Prompt injection

Lesson: Securing AI systems

Standardization

Rescaling a numeric feature so it has mean 0 and standard deviation 1, so features with large units don't dominate.

Formal: z=(x−μ)/σz = (x - \mu)/\sigma, with μ\mu and σ\sigma computed on the training split only.

Example: With training mean 5 and standard deviation 2, a value of 9 becomes 2.

Related: Feature, Data leakage

Lesson: Feature engineering

Stationarity

A series is stationary when its average level, spread, and pattern of dependence don't change over time.

Formal: Weak stationarity: E[yt]=μE[y_t] = \mu, Var(yt)=σ2\text{Var}(y_t) = \sigma^2, and Cov(yt,yt−k)\text{Cov}(y_t, y_{t-k}) depends only on kk.

Example: Daily demand growing 0.05 per day is not stationary; its day-over-day differences are.

Related: Autocorrelation, Walk-forward validation

Lesson: Time series

Statistical power

The probability that an experiment detects an effect when the effect is real.

Formal: Power =1−β=P(reject H0∣true effect=δ)= 1 - \beta = P(\text{reject } H_0 \mid \text{true effect} = \delta); conventionally targeted at 0.8.

Example: With 14,749 users per arm and a 10% baseline, power is 0.8 for a true 10% relative lift but only about 0.29 for a 5% lift.

Related: Minimum detectable effect, P-value

Lesson: Experimentation and A/B testing

Subgradient

A stand-in for the gradient at a corner of a function that is not smooth, such as the hinge loss at yf(x)=1y f(x) = 1; any slope between the left and right slopes works.

Example: For ∣x∣|x| at x=0x = 0, any value in [−1,1][-1, 1] is a subgradient.

Lesson: Support vector machines

Successive halving

Train many configurations briefly, keep the best fraction, train those longer, and repeat; Hyperband runs several such brackets.

Formal: With NN configs, starting budget b0b_0, and factor η\eta, round rr runs N/ηrN/\eta^r configs at budget b0ηrb_0\eta^r, costing Nb0N b_0 per round.

Example: 27 configs at 1, 3, and 9 epochs cost 81 epochs, versus 243 to train all for 9.

Related: Random search, Hyperparameter

Lesson: Hyperparameter tuning

SwiGLU

A gated feed-forward layer: one projection, passed through a Swish activation, multiplies a second projection elementwise before a down projection.

Formal: SwiGLU(x)=Wdown(SiLU(Wgatex)⊙Wupx)\text{SwiGLU}(x) = W_{\text{down}}\big(\text{SiLU}(W_{\text{gate}}x) \odot W_{\text{up}}x\big): three matrices, 3hf3hf parameters. GeGLU uses GELU instead of SiLU.

Example: Llama 3 8B: 3⋅4,096⋅14,336=176,160,7683 \cdot 4{,}096 \cdot 14{,}336 = 176{,}160{,}768 MLP parameters per layer.

Related: Activation

Lesson: Open models: architecture walkthroughs

System prompt

Standing instructions (role, rules, output format) sent with every call before the conversation.

Formal: The leading message(s) of the context, typically held fixed so they form a cacheable prefix; their tokens are billed on every call.

Example: A 600-token system prompt over 200,000 calls a day is 120 million input tokens a day.

Related: Prefix caching, Prompt injection

Lesson: Prompt engineering

Target encoding

Replacing each category with the average label for that category, smoothed toward the overall average.

Formal: enc(c)=(ncyˉc+myˉ)/(nc+m)\text{enc}(c) = (n_c \bar y_c + m \bar y)/(n_c + m); fit out of fold on training rows to avoid leaking each row's own label.

Example: A category with 2 rows, both positive, global rate 0.3, m=10m = 10: (2+3)/12=0.417(2 + 3)/12 = 0.417.

Related: One-hot encoding, Data leakage

Lesson: Feature engineering

Target network

A frozen copy of a value network used only to compute training labels, so the labels do not shift with every gradient step.

Formal: Weights θ−\theta^- used in the TD target r+γmax⁡a′Q(s′,a′;θ−)r + \gamma \max_{a'} Q(s', a'; \theta^-); updated by a hard copy θ−←θ\theta^- \leftarrow \theta every CC steps or a soft update θ−←τθ+(1−τ)θ−\theta^- \leftarrow \tau\theta + (1-\tau)\theta^-.

Example: Atari DQN copied the weights every 10,000 steps; without a target network the Q estimate in the lesson's GridWorld swings to −43 against a true value of −5.85.

Related: Deep Q-network (DQN), Deadly triad

Lesson: Deep Q-networks (DQN)

Temperature

A decoding knob that makes a model's choices more predictable (low) or more varied (high).

Formal: Logits are divided by TT before softmax; T<1T < 1 sharpens, T>1T > 1 flattens.

Example: Logits [2,1,0][2, 1, 0]: top probability 0.665 at T=1T = 1, 0.867 at T=0.5T = 0.5.

Related: Softmax

Lesson: Decoding

Temporal-difference learning

Learning a value estimate after every step by nudging it toward the reward plus your own estimate of the next state, without waiting for the episode to end.

Formal: V(s)←V(s)+α[r+γV(s′)−V(s)]V(s) \leftarrow V(s) + \alpha[r + \gamma V(s') - V(s)]; the bracket is the TD error δ\delta.

Example: Q-learning, SARSA, DQN, and the critic in PPO all use TD errors.

Related: Q-learning, SARSA, Bellman equation

Lesson: Q-learning and SARSA

Tensor

An n-dimensional array of numbers with a shape, a data type, and a device (CPU or GPU): the basic data structure of deep-learning frameworks.

Formal: A tensor of shape [B,d][B, d] holds B×dB \times d values; operations broadcast trailing dimensions of size 1 or matching size.

Example: A batch of 32 RGB images of 224×224 pixels is a tensor of shape [32,3,224,224][32, 3, 224, 224].

Related: Autograd, Batch

Lesson: Intro to PyTorch

Tensor parallelism

Splitting each weight matrix across GPUs so they share every layer's work.

Formal: Column-split outputs are concatenated; row-split outputs are summed with an all-reduce. Megatron-style MLPs column-split the first matrix and row-split the second, needing one all-reduce per block. Communicates every layer, so usually kept within one server.

Example: 8-way tensor parallelism cuts a 7B-style model's 107.8 GB of training state to 13.5 GB per GPU.

Related: Pipeline parallelism, Data parallelism

Lesson: Scaling and distributed training

TF-IDF

A word weight that is high when a word is frequent in a document but rare across the corpus.

Formal: TF(t,d)×ln⁡(N/DF(t))\text{TF}(t,d)\times\ln(N/\text{DF}(t)).

Example: 3 occurrences of a word found in 5 of 100 documents: 3×ln⁡20=8.993 \times \ln 20 = 8.99.

Related: Cosine similarity, Embedding

Lesson: From text to vectors

Time to first token

How long a user waits from sending a request until the first word of the answer appears.

Formal: TTFT = queueing time + prefill time. Paired with TPOT (time per output token, or inter-token latency): end-to-end latency = TTFT + TPOT × (output tokens − 1).

Example: TTFT 200 ms and TPOT 25 ms for 300 tokens gives 7.675 s end to end.

Related: Prefill, Inference

Lesson: LLM inference

Token

The unit of text a language model actually reads and writes: often a word piece.

Formal: An element of the tokenizer's vocabulary, mapped to an integer ID and then to an embedding.

Example: "unbelievable" might be split into "un", "believ", "able".

Related: Context window, Embedding

Lesson: Tokenization and pretraining

Tool calling

A model asking the application to run a function (search, look up an order, compute) by emitting a structured request.

Formal: The model outputs a function name and arguments matching a schema; the application validates, authorizes, executes, and returns the result.

Example: get_order_status(order_id=123), executed only if the user owns order 123.

Related: Agent, Prompt injection

Lesson: Production architecture

Tool poisoning

Hidden instructions placed in a tool or MCP server description, which the model reads as trusted context.

Related: Prompt injection, Tool calling

Lesson: Securing AI systems

Topic model

An unsupervised model that finds recurring themes (groups of words that occur together) in a collection of documents.

Formal: LDA models each document as a mixture θd\theta_d over KK topics and each topic as a distribution ϕk\phi_k over the vocabulary; inference recovers θ\theta [D,K][D, K] and ϕ\phi [K,V][K, V] from word counts.

Example: A news article might be 60% "finance" and 40% "AI" topics.

Related: TF-IDF, Embedding

Lesson: Topic modeling

Training

Fitting a model's parameters to data by minimizing a loss.

Formal: θ∗=arg⁡min⁡θ1n∑iℓ(fθ(xi),yi)\theta^* = \arg\min_\theta \frac{1}{n}\sum_i\ell(f_\theta(x_i), y_i), usually by gradient-based optimization.

Example: Running gradient descent for 2,000 steps to fit a regression line.

Related: Inference, Loss

Lesson: The language of ML

Training-serving skew

Any difference between the data a model sees during training and the data it gets in production, caused by the pipeline rather than by the world changing.

Formal: Ptrain(x)≠Pserve(x)P_{\text{train}}(x) \ne P_{\text{serve}}(x) for the same underlying events, due to different feature code, defaults, freshness, or preprocessing between the offline and online paths.

Example: A counter computed hourly in the training pipeline but read as 0 when the online cache misses makes the model wrong on exactly the requests where the cache fails.

Related: Feature store, Drift, Data leakage

Lesson: ML system design

Transformer

The neural architecture behind modern LLMs: stacked blocks of attention and feed-forward layers with residual connections.

Formal: Blocks of x+MHA(LN(x))x + \text{MHA}(\text{LN}(x)) followed by x+FFN(LN(x))x + \text{FFN}(\text{LN}(x)), operating on token embeddings plus positional information.

Example: GPT-2 small has 12 blocks of width 768 and 124M parameters.

Related: Attention, Token

Lesson: The transformer architecture

Two-tower model

A retrieval model with one network for users (or queries) and one for items, scoring a pair by the dot product of their vectors.

Formal: s(u,i)=fθ(u)⋅gϕ(i)s(u, i) = f_\theta(u) \cdot g_\phi(i) with fθ(u),gϕ(i)∈Rdf_\theta(u), g_\phi(i) \in \mathbb{R}^d; item vectors are precomputed and searched with an approximate nearest neighbor index.

Example: A feed retrieves 1,000 of 10M videos in milliseconds by computing one 64-dimensional user vector and querying an ANN index of item vectors.

Related: Embedding, Cold start

Lesson: ML system design

Vision transformer

A transformer applied to an image cut into square patches, each patch treated like a word token.

Formal: Patches of P×PP \times P pixels are linearly embedded (a stride-PP convolution), a [CLS] token and learned position embeddings are added, and a standard pre-norm transformer encoder processes the HW/P2+1HW/P^2 + 1 tokens.

Example: ViT-B/16 on a 224-pixel image uses 196 patch tokens plus [CLS] and has 86.6M parameters.

Related: Transformer, Attention, Embedding

Lesson: Vision transformers

Vision-language model

A language model that can read images: a vision encoder's features are translated into the LLM's token space and placed in the prompt.

Formal: Vision encoder (usually a CLIP or SigLIP ViT) → projector (often a two-layer MLP) → decoder LLM; projected patch features replace <image> placeholder tokens.

Example: A 336-pixel image with 14-pixel patches adds 576 tokens to the prompt.

Related: Transformer, Token, Hallucination

Lesson: Vision-language models

Viterbi algorithm

Dynamic programming that finds the highest-scoring sequence of labels without trying every sequence.

Formal: δi(k)=ei(k)+max⁡j[δi−1(j)+A(j,k)]\delta_i(k) = e_i(k) + \max_j[\delta_{i-1}(j) + A(j, k)] with back-pointers; cost O(nK2)O(nK^2) for nn tokens and KK tags.

Example: With "New" P(O)=0.6, P(B-LOC)=0.4 and "York" P(I-LOC)=0.5, Viterbi picks B-LOC I-LOC (0.20) over the invalid greedy O I-LOC.

Related: BIO tagging

Lesson: Named entity recognition

Walk-forward validation

Validating a forecaster by training on the past, testing on the next block, then moving forward and repeating.

Formal: Fold kk trains on rows before sks_k and tests on [sk,sk+h)[s_k, s_k + h), with s1<s2<…s_1 < s_2 < \dots; expanding or fixed-length (sliding) training windows.

Example: scikit-learn's TimeSeriesSplit(n_splits=5, test_size=60).

Related: Data leakage, Stationarity

Lesson: Time series

Weight initialization

Choosing the random scale of starting weights so activations neither shrink to zero nor blow up as they pass through many layers.

Formal: Xavier/LeCun: Var(w)=1/fan_in\text{Var}(w) = 1/\text{fan\_in} (or 2/(fan_in+fan_out)2/(\text{fan\_in}+\text{fan\_out})) for tanh; He: Var(w)=2/fan_in\text{Var}(w) = 2/\text{fan\_in} for ReLU.

Example: At width 256, a fixed std of 0.01 leaves activations about 1e-8 after 10 tanh layers; He init keeps ReLU activations near 1 after 20.

Lesson: Training and regularization

Word error rate

The standard speech-recognition metric: the fraction of reference words you'd have to fix to turn the transcript into the reference.

Formal: WER=(S+D+I)/N\text{WER} = (S + D + I)/N, word-level edit distance divided by the number of reference words, computed after text normalization; it can exceed 1.

Example: Reference "turn on the kitchen lights", hypothesis "turn the kitchen light on": 1 substitution, 1 deletion, 1 insertion, WER =3/5=0.6= 3/5 = 0.6.

Related: CTC

Lesson: Speech recognition: CTC, transducers, and attention

ZeRO

A way to stop every data-parallel GPU from storing duplicate copies of optimizer state, gradients, and weights.

Formal: Zero Redundancy Optimizer (Rajbhandari et al., 2020). Per-GPU memory with mixed-precision AdamW: stage 1 4P+12P/N4P + 12P/N, stage 2 2P+14P/N2P + 14P/N, stage 3 16P/N16P/N, versus 16P16P for DDP. Stages 1 and 2 send the same bytes as DDP; stage 3 about 1.5 times as much.

Example: A 7B-style model on 8 GPUs: 108.6 GB per GPU under DDP, 37.9 GB under ZeRO-1, 14.3 GB under ZeRO-3 (including activations).

Related: FSDP, Reduce-scatter, Data parallelism

Lesson: ZeRO and FSDP

Zero-shot classification

Classifying into categories the model was never trained on, by comparing the input with text descriptions of each category.

Formal: With a shared image-text embedding space, y^=arg⁡max⁡kcos⁡(f(x),g(promptk))\hat{y} = \arg\max_k \cos(f(x), g(\text{prompt}_k)).

Example: CLIP labels a photo by embedding "a photo of a cat", "a photo of a dog", ... and picking the closest.

Related: Embedding, Cosine similarity

Lesson: CLIP and contrastive image-text pretraining