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: with ; common are ReLU, GELU, sigmoid, tanh.
Example: ReLU turns into 0 and into 2.
Lesson: The forward pass
- Advantage
How much better an action turned out than what was expected from that state.
Formal: ; estimated as (REINFORCE with a baseline), with GAE (PPO), or as a group-normalized reward (GRPO).
Example: An episode returns from a cell whose baseline is , so the advantage is , 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 ; it sends 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
- 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, steps in total, and sends bytes per rank for a -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
- Anomaly detection
Finding data points that don't fit the normal pattern, usually without labeled examples of the anomalies.
Formal: Learn a score from mostly normal data so that unusual get high scores; flag , with 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
- Approximate nearest neighbor search
Finding vectors that are probably the closest to a query, checking only a small part of the collection instead of every vector.
Formal: An index returns a set of vectors that approximates the exact top- under a distance; quality is measured as recall@ against brute force.
Example: An IVF index with 1,024 cells that probes 8 scans about 0.8% of a million vectors.
Related: HNSW, Embedding, Cosine similarity
Lesson: Vector search
- Attention
A learned, soft lookup: each token gathers information from other tokens, weighted by how relevant they are.
Formal: , where queries, keys, and values are linear projections of the token vectors.
Example: With , keys and , the weights are .
Related: Transformer, Context window
Lesson: Self-attention
- Autocorrelation
How strongly a series is correlated with a shifted copy of itself.
Formal: ; plotting against 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 for every parameter that has
requires_grad=True. Gradients add into.grad, so they must be zeroed each step.Example: For with ,
L.backward()setsw.grad = -12andb.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 + aat a = 3, the two paths intoacontribute 6 and 1, soa.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: , 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, .
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 used to estimate the gradient .
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 ; an acquisition such as expected improvement picks the next .
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: ; 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
- 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 .
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 , token gets
B-X, tokens getI-X, all othersO;I-Xmay only followB-XorI-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: , typically , .
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 indices uniformly from with replacement; each row is left out with probability .
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
- 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 for all ; 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 , an -step answer is right with probability ; writing steps as tokens lowers because later tokens can condition on earlier results.
Example: At a 4-step answer is right with probability ; at it is .
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 at step , 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: . With Approach 3 constants, and , so the ratio drifts with budget.
Example: For FLOPs at 20 tokens per parameter: B, B 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 with overlap , giving about chunks.
Example: A 1,000-word document with 200-word chunks and 50-word overlap gives 7 chunks.
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 , so each class carries total weight . For logistic regression they inflate the predicted odds by about , which mainly moves the decision threshold.
Example: With 2,279 negatives and 121 positives, and : 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: ; requires dropping the condition (about 10%) during training. is plain conditional sampling.
Example: , , gives .
Related: Latent 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 . Contrast covariate drift (change in ) and prior drift (change in ). 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 (from a grammar compiled from the schema) get probability 0 and the rest are renormalized: .
Example: A tool call generated under the schema always parses, though
flight_idmay 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 , while maximizing task quality; with full history, total billed input over calls is .
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 over which attention is computed.
Example: Anything beyond the window is invisible to the model unless retrieved and inserted.
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 : ; repeat. Lasso solvers use it because each one-weight problem has a closed form (soft-thresholding).
Example: scikit-learn's
LassoandElasticNetare fitted by coordinate descent.Related: Soft-thresholding
- Cosine similarity
How closely two vectors point in the same direction, ignoring their lengths.
Formal: , between −1 and 1.
Example: and have cosine 0.730.
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: for one example; binary form .
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 sums over all paths that collapse to , computed with a forward algorithm in .
Example: With frame probabilities for (blank, a), and the loss is .
Related: Word error rate, Spectrogram
- 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: with , where is a pre-experiment covariate; the variance shrinks by a factor and the estimate stays unbiased.
Example: With 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 is dead on a dataset if for all ; then .
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 over minibatches from a replay buffer, with a target network and usually the Huber loss .
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: is equal for all groups . 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: ; 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: is -DP if for all neighbouring datasets and output sets . Costs add up over queries; post-processing is free.
Example: Releasing a count with Laplace noise of scale is -DP; at 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: ; the return is , and the effective horizon is about steps.
Example: With , a reward 10 steps away keeps of its weight.
Related: Markov decision process, Bellman equation
- 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
- Double DQN
A DQN variant that reduces overoptimistic Q-values by letting one network choose the next action and another score it.
Formal: .
Example: Online values pick action 4; the target network scores it , so instead of the vanilla .
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 , add to their sum, divide by the batch size, and step; an accountant tracks the total across steps (Abadi et al. 2016).
Example: 100 full-batch steps at , give ; 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: with a frozen reference model .
Example: At the start of training the policy equals the reference, so the loss is .
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 ; concept drift is a change in ; prompt drift is a change in what users ask.
Example: A demand model trained before a price change starts under-predicting.
Related: Generalization, Calibration
- Embedding
A dense vector that represents an item (word, token, document, user) so that similar items are close together.
Formal: A learned mapping , often a row of an embedding matrix of shape .
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: . Bits with , nats with .
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: optimization steps for examples and batch size .
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 choose uniformly among actions; otherwise choose .
Example: With and 4 actions, the greedy action is taken with probability .
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: is equal across groups for . Equal opportunity is the 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: . M-step: , , , the -weighted covariance.
Example: a point with responsibilities 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 tuples in a fixed-capacity FIFO buffer 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: for tokens, top- routing, experts, and capacity factor .
Example: 4,096 tokens, 64 experts, top-2, : .
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 of the input vector .
Example: Square footage when predicting house prices.
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 ; no weights change.
Example: One worked example ending in
Answer: 20made a model end every answer withAnswer: 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.
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 , , into SRAM blocks and uses an online softmax (running max and sum) to produce the same output as standard attention, with extra memory instead of 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.
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: , loss ; sample by integrating from to . Rectified flow adds reflow: retraining on the model's own (noise, sample) pairs to straighten paths.
Example: , , gives and target velocity .
Related: Latent diffusion
- Focal loss
Cross-entropy that down-weights examples the model already gets right, so rare hard examples dominate the gradient.
Formal: , where is the probability of the true class; gives cross-entropy.
Example: With , an easy example at keeps 1% of its cross-entropy; a hard one at 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_shardin FSDP2;SHARD_GRAD_OPandHYBRID_SHARDgive 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: ; the generator usually minimizes the non-saturating loss .
Example: For fixed , the best discriminator is , which is 0.5 everywhere at equilibrium.
Related: Mode collapse, Loss
- 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: , . gives the one-step TD error; gives the Monte Carlo return minus .
Example: With , , TD errors and then at the end give .
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: .
Example: For at , .
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: ; relative error below about (float64) passes, around or more indicates a bug.
Example: A backward pass missing the ReLU mask gives relative error about 1; the correct one gives .
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 -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 , where is the L2 norm over every parameter; the update keeps its direction.
Example: Gradients and have norm 13; clipping at 1 multiplies all of them by .
Related: Mixed precision, Gradient
- Gradient descent
Repeatedly nudging parameters a small step downhill on the loss surface.
Formal: ; stable along curvature only if .
Example: With , and gradient , the new weight is .
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 query heads and KV heads (), each group of query heads attends using the same and . is multi-head attention (MHA); 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.
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 responses with rewards , every token of response gets advantage ; the loss is PPO's clipped surrogate plus a KL penalty to a reference model.
Example: Rewards have mean 0.5 and std 0.5, giving advantages .
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: with labels .
Example: , gives loss ; 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 links per upper layer and at layer 0; search descends greedily from the top layer, then runs best-first search with a candidate list of size
efSearch.Example: With 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: if , else , with residual .
Example: Residuals give mean Huber 2.44 () 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 , usually selected on a validation set.
Example: Learning rate, tree depth, 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 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: , cross-entropy over candidates with temperature ; chance level is the log of the number of candidates.
Example: With 2 images (4 views) and , 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: , 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: , where is path length in random trees built on subsamples of size and .
Example: With , ; 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: .
Example: For and , 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 tensors per layer; each new token computes only its own query against them, 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 paired with features in supervised data.
Example: "Spam" or "not spam" for an email.
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 .
Example: With 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 ; set ; train on ; generate .
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
- Learning rate
How big a step the optimizer takes each update.
Formal: The scalar in ; 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: for , 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 (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: with .
Example: scores underflow to directly; shifted to they give probabilities .
Lesson: Naive Bayes
- Logit
The raw score a model outputs before it is turned into a probability.
Formal: For logistic regression, ; the probability is . 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: with frozen and trainable low-rank , .
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: , 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: . A dynamic scaler skips the step and halves when any gradient overflows, and doubles after a run of clean steps (2,000 by default in PyTorch). Not needed with bf16.
Example: A gradient of is 0 in fp16; times it is , which fp16 can hold.
Related: 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 of states, actions, transition probabilities , 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
- 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: ; below 1 beats seasonal naive.
Example: MAE 3.6 against a seasonal-naive MAE of 4.5 gives MASE 0.8.
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 ; replace 80% with
[MASK], 10% with a random token, keep 10%; minimize 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
- 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: , ranging from to .
Example: , , , gives MCC , 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: where is the power spectrogram and is a matrix of triangular filters equally spaced on the mel scale .
Example: 80 mel filters turn a power spectrogram into a 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.
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 log-mel spectrogram becomes a 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 at which the test has the chosen power at significance ; the sample size per arm scales as .
Example: Detecting 10% → 11% conversion (a 10% relative MDE) at 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 expert networks and a router that picks the top per token. Total parameters set memory; active parameters (shared plus 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.
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: concentrates on a subset of the modes of ; 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
- 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 to about 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.
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 (
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 bytes per token, 71× less than full keys and values for 128 heads.
Related: Grouped-query attention, KV cache
- Mutual information
How much knowing one variable reduces uncertainty about another; catches non-linear relationships that correlation misses.
Formal: , which is 0 exactly when and are independent.
Example: For with 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 to tags (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: , solved with a linear solver rather than an explicit inverse.
Example: For , it gives , .
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 among values maps to the unit vector .
Example: color = green among {red, green, blue} becomes .
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 , average the predictions of trees whose bootstrap sample excluded ; compute the metric over all rows.
Example: In scikit-learn,
RandomForestClassifier(oob_score=True)exposes it asoob_score_.Related: Bootstrap sample
- 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: . It is not .
Example: in a two-sided test gives .
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 , the vector of values the optimizer adjusts to minimize the loss .
Example: The slope and bias in .
Related: Hyperparameter, Gradient
Lesson: Linear regression
- pass@k
The chance that at least one of generated programs passes the tests.
Formal: From samples with passing, the unbiased estimate is .
Example: , : 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 independent tries, a measure of consistency.
Formal: For per-trial success rate , , versus (at least one success).
Example: With , pass^3 while pass@3 .
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: ; on a mistake, , .
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: 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 stages and micro-batches, a GPipe schedule is idle for of the step (the pipeline bubble). Only boundary activations cross between GPUs.
Example: 4 stages and 16 micro-batches leave 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: , derived with the log-derivative trick . REINFORCE uses .
Example: With logits and action 4 taken, ; scaling by an advantage of 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: over bins (usually reference deciles), with and 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: ; 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 with , plus a value loss and often an entropy bonus.
Example: With , a sample with and scores 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 prompt tokens, about FLOPs for a -parameter model. Its arithmetic intensity is about FLOPs per byte, so it is compute-bound, unlike decode.
Example: A 2,000-token prompt on an 8B model needs about FLOPs, 32 ms at a peak of 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 into subvectors, learn 256 centroids per position with k-means, store one-byte codes; query distances are sums of precomputed table lookups.
Example: A 768-dimensional float32 vector (3,072 bytes) with 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: ; converges to if every pair keeps being visited.
Example: , , best next value , , : the new value is .
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: ; the state value is .
Example: Acting greedily means picking .
Related: Q-learning, Bellman equation
- 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 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
- 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
- Random search
Trying hyperparameter settings sampled at random from chosen ranges instead of a fixed grid.
Formal: Draw configurations independently; if a fraction of the space is good, .
Example: With , 60 trials give .
Related: Hyperparameter, Bayesian optimization
Lesson: Hyperparameter tuning
- 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: , 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 (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: , commonly .
Example: A document ranked 1st by dense search and 3rd by BM25 scores .
Lesson: Vector search
- Reduce-scatter
Summing tensors across GPUs but giving each GPU only its own slice of the result.
Formal: Each of ranks ends with the reduced values of one chunk; it sends 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
- Regularization
Anything that discourages a model from memorizing, so it generalizes better.
Formal: Penalties (, ) or procedures (dropout, early stopping, augmentation) that reduce variance.
Example: Ridge regression shrinks the slope from 1.5 to 0.6 with in the course example.
Related: Overfitting
- 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: with .
Example: , , gives .
- 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 , where is the chosen and 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: , with one learned scale vector of size .
Example: Llama 3 8B has 65 RMSNorms of 4,096 parameters each (two per block plus a final one).
- 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: , with ; a common cutoff is 3.5.
Example: In , 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 at position are rotated by angle with (
rope_thetais the base). Then depends only on .Example: Llama 3 uses
rope_theta = 500000; methods such as YaRN rescale the angles to extend context.Related: Attention
- 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 by and by makes depend only on the offset .
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 and .
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: , where 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 , with training compute .
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 independent chains each correct with probability , a strict majority is correct with probability ; plurality voting can do better when wrong answers scatter.
Example: , gives at least 0.837; if wrong chains agree and , 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 on ; for with , add to .
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)) ≥ τ.
- 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: , where is the mean distance from point to the rest of its cluster and the mean distance to the nearest other cluster.
Example: , gives .
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: with orthonormal columns in and and nonnegative singular values on the diagonal of . For centered data, PCA variances are .
Example: five centered points with PCA variance have , so .
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 may attend key only if and . Cost is per layer, the KV cache holds tokens per layer, and stacked layers reach positions.
Example: With and , 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 and one of its nearest minority neighbors , SMOTE (Synthetic Minority Over-sampling Technique) creates with .
Example: From and neighbor with , SMOTE adds . 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: .
Example: , , .
Related: Coordinate descent
- Softmax
Turns a list of scores into probabilities that are all positive and add up to 1.
Formal: with temperature .
Example: Logits become .
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 , hop ), multiply by a window function, FFT each frame; shape .
Example: One second at 16 kHz with a 400-sample window, 160-sample hop, and 512-point FFT gives a 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 and per-token acceptance rate , the expected tokens per target pass is . With rejection-sampling verification, outputs follow the target model's distribution exactly.
Example: , : 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: , with and 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: , , and depends only on .
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 ; 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 ; any slope between the left and right slopes works.
Example: For at , any value in 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 configs, starting budget , and factor , round runs configs at budget , costing 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: : three matrices, parameters. GeGLU uses GELU instead of SiLU.
Example: Llama 3 8B: MLP parameters per layer.
Related: Activation
- 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: ; 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, : .
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 used in the TD target ; updated by a hard copy every steps or a soft update .
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 before softmax; sharpens, flattens.
Example: Logits : top probability 0.665 at , 0.867 at .
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: ; the bracket is the TD error .
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 holds 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 .
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: .
Example: 3 occurrences of a word found in 5 of 100 documents: .
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.
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 over topics and each topic as a distribution over the vocabulary; inference recovers and from word counts.
Example: A news article might be 60% "finance" and 40% "AI" topics.
Lesson: Topic modeling
- Training
Fitting a model's parameters to data by minimizing a loss.
Formal: , usually by gradient-based optimization.
Example: Running gradient descent for 2,000 steps to fit a regression line.
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: 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 followed by , operating on token embeddings plus positional information.
Example: GPT-2 small has 12 blocks of width 768 and 124M parameters.
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: with ; 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 pixels are linearly embedded (a stride- convolution), a [CLS] token and learned position embeddings are added, and a standard pre-norm transformer encoder processes the 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: with back-pointers; cost for tokens and 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 trains on rows before and tests on , with ; 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: (or ) for tanh; He: 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: , 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 .
Related: CTC
- 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 , stage 2 , stage 3 , versus 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, .
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