Reading: 14 min, plus 4 in closed details. Which mathematics each part of machine learning uses and which child page owns it, one tiny model's training step with every number, the objects that wear several hats, and how to read an equation in a paper. Data as of October 2026.
The idea in one screen
One training step of one model uses almost all of the mathematics of machine learning, each area for one move: linear algebra scores the input, probability turns the scores into a bet and prices it, information theory says what the price means, calculus finds the downhill direction, optimisation decides how far to step, and statistics asks, from outside the loop, whether the model really got better. Floating point sits under every move, and variational inference is where the areas meet.
The running example every child page uses
A language model with a three-word vocabulary, cat, dog and sat, has read "the cat"; the right next word is sat. The context is the vector and the model is one weight matrix with one row per word: cat , dog , sat . It scores the words , turns the scores into the bet , and so bets on cat and gives the truth only 9%. A real language model does the same with a vocabulary of about 100,000 tokens and thousands of numbers per word. Every child page works its examples on this model (or on the two-layer version in the Gradient lab), so a number met on one page can be checked on another.
Fig. 1 plays one training step of it, forward along the front row and backward along the row behind it, and pins each child page's concept where it acts. Every number is the tiny model's own, computed on this page; each step links to the section that owns it.
Input and weights(linear algebra). The context "the cat" is the vector ; the whole model is one weight matrix , the glass plate, with one row per word. Linear algebra, section 1
Score(linear algebra). : one dot product per row, large when a word's row points where points. Linear algebra, section 3
Bet(probability). Softmax turns the scores into the bet : most on cat, 9% on sat, the truth. Probability, sections 6 and 7
Pay(information theory). The loss is the surprise at the truth, nats bits, above the uniform guess's (the flat plate). Information theory, sections 1 and 3
Gradient on the scores(calculus). The backward pass starts at the loss and runs along the back row: , prediction minus target. Calculus and optimisation, section 2
Gradient on the weights(matrix calculus). , the bar field behind the plate: shaped like , of rank 1, fed by the gradient arriving and the input the forward pass kept. Matrix calculus and backprop, section 5
Step(optimisation). , then the forward pass again: sat's probability rises from 0.090 to 0.170 and the loss falls to 1.773. The learning rate stays under the local limit . Calculus and optimisation, section 4
Was it real?(statistics). The training sentence's loss fell by construction; only the average change on held-out sentences, with its error bar, says the model improved. With a spread of 0.5 nats per sentence and 100 sentences, a 0.1-nat gain has a 95% error bar of : it only just clears zero. Statistics, sections 5 and 7
Under every box(numerical computing). Every number above is a float: passes the largest float32 at , so a real softmax subtracts the largest score first. Where all the areas meet, in a model with a hidden cause, is the ELBO. Numerical computing, section 7; Variational inference, section 3
You need: nothing; this is the entry page, and each child page says what it assumes.
New terms
Logits: raw scores, one per word, before softmax turns them into probabilities.
Loss (negative log-likelihood): , minus the log of the probability given to what happened.
Nat and bit: units of the loss with and ; 1 nat = 1.443 bits. Training code prints nats.
Gradient: one slope of the loss per number in the model, the same shape as what it is the gradient of.
Curvature: how fast the slope changes; with many weights, the Hessian matrix.
Standard error: the uncertainty of an average, .
1. The map: which maths each part of ML uses
Read a row as "when you work on this part of a model, this is the maths, this is the one object to know, and this page owns it". The last column is where the maths is applied in depth outside this topic.
Part of ML
Maths
The object to know
Owner (section)
Applied on
Embeddings, layers, attention scores
linear algebra
the dot product, the matrix product and the shape of every tensor
The two letters that change meaning between pages: this page and most children write for the model and or for the target; Information theory uses the textbook convention, the truth and the model, and says so at its top. is a Hessian on the optimisation pages and an entropy on the information page; the Notation decoder lists such clashes.
2. One training step, with every number
Fig. 1's moves as one table: each with the one number that matters, what that number teaches, and where it is explained. Every value is recomputed by the page's scripts (src/read/recompute.py), and the Gradient lab recomputes them live when you change the model.
Move
The tiny model's number
What it teaches
Explained on
Score
; cosine of each row with : cat 0.894, dog 0.447, sat 0
a score is a dot product: large when the word's row points where the input points
the loss is a surprise in nats; this model did worse than knowing nothing. With a real vocabulary of 50,000 tokens the uniform guess, and so the loss at initialisation, is nats
a spread of 0.5 nats per sentence needs about 100 sentences to see a 0.1-nat gain; a 500-question benchmark near 50% has a 95% interval of about points
the loss on the training sentence fell by construction; only the average change on held-out text, with its error bar, says whether the model improved
The step itself is gradient descent, . On this model the new scores are with , so at each score moves by half its gradient and sat's probability rises from 0.090 to 0.170. One backward pass did two matrix products ( for the weights, for the input) against the forward pass's one: the factor of two behind "training costs about 6 FLOPs per parameter per token", derived on Matrix calculus and backprop, section 8.
3. The same object in different hats
Two objects turn up on several child pages under different names. Seeing that each is one thing is the payoff of learning the areas together, and no single child can show it.
Cross-entropy wears four hats
Same scores and bet , but suppose the right word had been cat, the model's favourite. One number, 0.408 nats, read four ways:
Probability: a likelihood
The negative log-likelihood of cat under a categorical model; minimising its average is maximum likelihood. Probability, section 7
Information: a code length
0.588 bits
The same number divided by : cat's codeword length in a code built from the bet. Averaged over real data it is entropy plus KL. Information theory, section 3
Read cat as the positive and dog and sat as two negatives with similarities 2, 1 and 0: 0.408 is the InfoNCE loss with , and it certifies at least 0.691 nats of mutual information by (van den Oord et al. 2018). Information theory, section 9
With the real answer, sat, the loss is 2.408 and the bound is negative: it certifies nothing. The bound can never exceed , which is why contrastive models such as CLIP train with huge batches (32,768 pairs; Radford et al. 2021).
Curvature is read three ways
For a yes-or-no prediction with score and probability , three quantities from three areas are the same number, : 0.25 at (its largest value) and 0.09 at (). Drag in the Gradient lab, panel 4, which computes each one by its own route.
The score (the slope of the log-likelihood in ) is ; its variance, the Fisher information, is . Statistics, section 2
A confident prediction therefore sits in a flat part of the loss. On the tiny model the many-word version holds: the Hessian of the loss in the scores, , is exactly the covariance matrix of the one-hot draw, with per-word variances (a simulation of 200,000 draws gives 0.222, 0.185, 0.081), and its largest eigenvalue, times , is section 2's .
Why this matters for natural gradients, and a correction to the old page
For the matched pairs (sigmoid with binary cross-entropy, softmax with cross-entropy, identity with squared error) the curvature in the scores does not depend on the label, so it equals its own average over labels, the Fisher. That is why natural-gradient methods and K-FAC precondition with the Fisher, and why the curvature of TRPO's KL constraint is the Fisher matrix. A correction to the old page: the equality is exact with respect to the scores only. With respect to the weights of a deep network the Hessian gains an extra term (the residual times the curvature of the network itself), so there the Fisher equals the Hessian only approximately; it is exactly the "generalised Gauss-Newton" part of it (Martens 2020, New insights and perspectives on the natural gradient method).
4. Which area to reach for: a diagnosis
When a paper or a training run confuses you, first ask which move of the step it is about. The symptom usually names the area, and the area names one word to look for.
Symptom
Area
The word to look for
Page
You cannot see why a loss is that loss and not another
probability
the distribution: choose it and the loss is decided
An equation in a paper is a compressed paragraph, and every child page's notation meets in it. Expanding it takes five steps, always in the same order. Here they are on scaled dot-product attention, equation 1 of Attention Is All You Need (Vaswani et al. 2017):
Name every symbol. holds the queries (one row per position, "what should I look at?"), the keys ("what I contain"), the values ("what I hand over"), the length of each query and key row, the transpose, softmax applied to each row separately. If a symbol is not defined near the equation, search the paper for its first use; the Notation decoder lists the conventions papers assume without saying.
Write the shape beside every symbol. With queries and keys: is , is , so is , one score for every query-key pair; is , so the result is , one output row per query. If the shapes do not fit, you have misread a symbol.
Read the operations from the inside out, in words. Dot each query with each key (how well they match); divide by ; turn each query's row of scores into weights that add up to 1; return, for each query, the weighted average of the value rows.
Plug in tiny numbers. One query , the three keys and values are the rows of the tiny model's , . The raw scores are ; divided by they are , and softmax turns them into weights . The output is : mostly cat's row. Without the division the weights would be , sharper.
Ask why each piece is there. Why ? The paper's footnote: if a query's and a key's entries are independent with mean 0 and variance 1, their dot product has variance . With raw scores would typically be about 8 apart, softmax would put nearly all the weight on one key, and its gradients would vanish; dividing by brings the variance back to 1. A term you cannot justify is usually the thing the paper is really about.
The habit
Name, shape, read, plug, ask. Step 4 is also how you test your own derivations: if tiny numbers do not come out right, the algebra is wrong. The attention block itself, with every shape, is owned by The transformer from zero; its backward pass on these same numbers is in Matrix calculus and backprop, section 6.
6. The child pages
Each child owns the depth this page only maps. In this order each builds on the ones before: the matrices first, then their derivatives, then probability and statistics, then curvature and optimisation, then information, then what floating point does to all of it, and generative models last because they use everything. Times are each page's own header: core reading, plus optional closed blocks.
Child page, about 45 min, plus 13 in closed details.
Every matrix as rotate, stretch, rotate: products and shapes, rank, norms, least squares, eigenvalues, the SVD, conditioning, and what is really low rank in GPT-2's weights and in real LoRA updates.
Child page, about 32 min, plus 22 in closed details.
The shape of every derivative, the chain rule as Jacobian products, reverse mode, backprop through a two-layer network by hand, the layer gradients, what the backward pass costs and keeps, and gradient checking.
Child page, about 32 min, plus 16 in closed details.
A model's output as a distribution: scored (losses as likelihoods, proper scoring, calibration on three real models), reshaped (temperature, priors, Bayes), averaged (LLN and CLT) and sampled (Gumbel-max, reparameterisation).
Child page, about 33 min, plus 6 in closed details.
How much a number computed from data would move on another sample: estimators, maximum likelihood, intervals, the bootstrap, tests and power, Bayesian estimation, regression, cross-validation (bias and variance for model choice and double descent are on Regularisation).
Child page, about 32 min, plus 11 in closed details.
Taylor models as the thread through loss gradients, Hessians, gradient descent and its step limit, Newton and quasi-Newton, convexity, Lagrange and KKT, stochastic gradients and the edge of stability.
Child page, about 38 min, plus 8 in closed details.
What a log-loss number means: entropy and codes, cross-entropy and KL, temperature, perplexity and bits per byte measured on real text, mutual information, InfoNCE, KL penalties and estimators. Uses the textbook letters ( the truth, the model).
Child page, about 40 min, plus 9 in closed details.
A number bit by bit and what that does to training: IEEE 754, epsilon and rounding, the formats from float64 to FP8, cancellation, summation error and determinism, the stable softmax, mixed precision and loss scaling, NaN hunting.
Child page, about 23 min, plus 18 in closed details.
The evidence lower bound derived three ways with its gap drawn, mean-field and amortised inference, gradients through samples, then the closed derivations D1 to D8 that the VAE, diffusion and flow-matching pages cite.
Practice on the tiny model across pages: the Gradient lab (losses, backprop, curvature, overflow, eight gradient bugs). Symbols and conventions in papers: the Notation decoder. Books, courses and papers: Further reading.
Glossary: every term this page uses, each linked to the page that owns it (reference)
Terms
Vocabulary: the set of tokens a language model can output (3 words here, about 100,000 in real models).
Vector: an ordered list of numbers; its dimension is how many.
Matrix: a table of numbers; its shape is rows by columns.
Dot product: multiply two vectors entry by entry and add; large when they point the same way.
Fourteen equations that carry modern ML, quoted exactly as their papers print them, decoded symbol by symbol. The aim is to read the next paper's maths without getting stuck: every symbol named, every shape given with real sizes, every equation run once on tiny numbers.
Name every symbol. Find the line where the paper defines it; the same letter means different things in different papers ( is a decay rate in Adam, a KL weight in DPO, a noise level in DDPM). Here: tap a symbol.
Write the shape beside every symbol. Check that every product's inner sizes match; most misreadings fail this test.
Read the operations from the inside out, in words. Here: the "Read it aloud" sentence.
Plug in tiny numbers. Two or three tokens, a 3 by 3 matrix: compute it once by hand. Here: "With tiny numbers".
Ask why each piece is there. Why the square root, why the hat, why this subscript under the E. Here: "Traps".
Each card links the paper (arXiv id, version, equation number and PDF page) and the knowledge base pages that teach the mechanism. Every worked number is recomputed by src/notation/recompute.py; numbers marked illustrative are made-up inputs run through the real formula.
As printed, with the paper's capital T for the transpose. The paper prints the softmax argument in plain round brackets.
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: queries
Meaning
One row per position that is asking a question: what am I looking for?
Shape
: here (3 tokens, ); in the paper's base model .
Defined
§3.2.1, p. 4: queries "packed together into a matrix Q".
: keys
Meaning
One row per position that can be looked at: what do I contain, as a label to match against?
Shape
: here . Self-attention has ; cross-attention can differ.
Defined
§3.2.1, p. 4.
: transpose
Meaning
Swap rows and columns, so is every query dotted with every key. Other papers write or : same thing.
Shape
is : here .
Defined
Not defined in the paper: standard notation.
: values
Meaning
One row per position: what that position hands over if you attend to it.
Shape
: here ; paper base .
Defined
§3.2.1, p. 4.
: key dimension
Meaning
Length of each query and key vector. Dividing by keeps the dot products from growing with (footnote 4: if the components are independent with mean 0 and variance 1, has variance ).
Shape
A number: here 4, so ; paper base 64, so 8.
Defined
§3.2.1 and footnote 4, p. 4; values in §3.2.2, p. 5.
: softmax, row by row
Meaning
Turns each row of scores into weights that are positive and sum to 1: . Applied to each row separately (one query at a time); the paper says so in words ("apply a softmax function to obtain the weights on the values").
Shape
in, out: here .
Defined
§3.2.1, p. 4 (in words; the formula itself is not printed).
: the output
Meaning
For each query, a weighted average of the value rows.
Shape
: here .
Defined
Eq. (1), p. 4.
Read it aloud
Attention of Q, K, V equals: take every query dotted with every key, divide by the square root of the key length, turn each row into weights with a softmax, and use those weights to average the rows of V.
With tiny numbers
Real tiny matrices: 3 tokens, dₖ = 4, dᵥ = 2. Step through them in the animation below; the numbers are recomputed in recompute.py.
A smaller case is worked in the Reading tab, section 5 ("How to read an equation in a paper"): one query against the tiny model's three keys, dk = 2, scores (2, 1, 0), weights (0.576, 0.284, 0.140). This one adds a second and third query so the whole matrix form, and every shape, shows.
The animation, step by step
The inputs. One row per token: and are 3 × 4 (), is 3 × 2.
Transpose K. Its rows become columns, 3 × 4 becomes 4 × 3, so every query can meet every key.
Scores, row by row. Each query dotted with each key: row 1 is (2, 0, 1), its first cell 1·1 + 0·0 + 1·1 + 0·0 = 2; row 2 is (0, 3, 2); row 3 is (2, 2, 2), a query that matches every key the same. 36 multiply-adds.
Divide by . The shape is unchanged; this keeps the scores from growing with (the paper's footnote 4).
Softmax each row. Exponentiate and divide by the row's sum: row 1 becomes (0.506, 0.186, 0.307), row 2 (0.122, 0.547, 0.331), row 3 equal thirds. Every row sums to 1.
Weighted sum of V's rows. Output row 1 = 0.506·v₁ + 0.186·v₂ + 0.307·v₃ = (0.814, 0.494); row 2 is (0.453, 0.878); row 3 (0.667, 0.667). 18 more multiply-adds.
Scores, row by row. The same raw scores: (2, 0, 1), (0, 3, 2), (2, 2, 2). 36 multiply-adds.
No division. Plain dot-product attention, the method Eq. (1) replaced, skips the , so the raw scores go straight into the softmax.
Softmax each row. Row 1 becomes (0.665, 0.09, 0.245), row 2 (0.035, 0.705, 0.259), row 3 equal thirds: sharper than the scaled weights.
Weighted sum of V's rows. Output rows (0.91, 0.335), (0.295, 0.965) and (0.667, 0.667). 18 more multiply-adds.
Done. Shapes (3×4)(4×3) → 3×3 scores → softmax 3×3 → (3×3)(3×2) → 3×2, and the same 36 + 18 multiply-adds: the division costs nothing.
All steps at once (static)
The inputs: three queries, three keys, three values.
Each cell is one query dotted with one key: row 1, column 1 is 1·1 + 0·0 + 1·1 + 0·0 = 2.
Divide every score by √d_k = 2.
Softmax each row: every row now sums to 1. Row 3 had equal scores, so its weights are equal.
Each output row is a weighted average of V's rows; shapes (3×3)(3×2) give 3×2.
Traps
The softmax runs along each row (over keys), never over the whole matrix and never down a column. In code: softmax(scores, dim=-1).
Rows are tokens. ML papers usually stack examples or positions as rows (), so a layer is , not . Check which way round a paper writes it before multiplying.
is the square root of the key length, not of the sequence length. Without it, scores grow with and the softmax saturates (Vaswani et al. footnote 4).
The decoder's mask is not in Eq. (1): §3.2.3 says it is applied by setting illegal positions to before the softmax.
As printed in §3.2.2 (the paper sets it as two centred lines; aligned here).
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: query projection of head i
Meaning
A learned matrix that maps each token's -vector to that head's query. The superscript is a label, not a power.
Shape
: here ; paper .
Defined
§3.2.2, p. 5: "the projections are parameter matrices".
: key projection of head i
Meaning
Same idea for keys.
Shape
: here .
Defined
§3.2.2, p. 5.
: value projection of head i
Meaning
Same idea for values.
Shape
: here .
Defined
§3.2.2, p. 5.
: output projection
Meaning
Mixes the concatenated heads back into one vector per token.
Shape
: here ; paper .
Defined
§3.2.2, p. 5.
: head i
Meaning
One run of scaled dot-product attention (Eq. 1) on projected inputs.
Shape
: here .
Defined
§3.2.2, p. 5.
: number of heads
Meaning
How many heads run side by side. The paper uses and .
Shape
A number: here 2.
Defined
§3.2.2, p. 5.
: concatenate
Meaning
Place the heads' outputs side by side, column-wise, for each token.
Shape
blocks of become : here .
Defined
§3.2.2, p. 5.
: the inputs
Meaning
In self-attention all three are the same matrix of token vectors (§3.2.3).
Shape
: here .
Defined
§3.2.3, p. 5.
Read it aloud
Multi-head attention runs h small attentions in parallel, each on its own learned projections of Q, K and V, glues their outputs side by side and mixes them with one more matrix W O.
With tiny numbers
Two tokens, d_model = 4, h = 2 heads, d_k = d_v = 2. The projections are chosen so head 1 reads dimensions 1 and 2 and head 2 reads dimensions 3 and 4 (illustrative weights, real arithmetic).
Self-attention: Q = K = V = X. Head 1's projections keep the first two coordinates.
Each head sees a 2 × 2 slice: shape (2×4)(4×2) = 2×2.
Eq. (1) inside each head, with √d_k = √2.
Side by side: 2 × (2+2) = 2 × 4.
W O mixes heads: each output column takes half of one head's column and half of the other's.
Traps
Superscripts on are names, not powers; the subscript is the head index. reads "W, head i, for queries".
here is the number of heads; in the LayerNorm and many RNN papers is a hidden state. Same letter, different object: always check the paper's own definition.
Splitting into heads costs no extra compute: with the paper notes the total cost is similar to one full-width head (§3.2.2).
As printed (the recurrent form, superscript t is the time step), with the paper's three side-by-side parts stacked here for width. Bold marks vectors.
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: summed inputs
Meaning
The vector being normalised: one layer's pre-activations for one example at time step . Bold means a vector; (not bold, subscript ) is its -th entry.
Shape
numbers: here .
Defined
§4, p. 3: "a^t = W_hh h^(t-1) + W_xh x^t".
: one entry of a
Meaning
The i-th hidden unit's summed input.
Shape
A number.
Defined
Eq. (3)-(4).
: mean over the layer
Meaning
Average of the H entries of this one example. Not a batch mean: that is batch normalisation, Eq. (2).
Shape
A number per example (per time step).
Defined
Eq. (3), p. 2; Eq. (4), p. 3.
: standard deviation over the layer
Meaning
Square root of the average squared distance from . Divides by , not : the population (biased) version.
Shape
A number per example.
Defined
Eq. (3), p. 2.
: gain
Meaning
Learned per-unit scale (modern code calls it or weight).
Shape
numbers: same dimension as .
Defined
§4, p. 3: "b and g are defined as the bias and gain parameters".
: bias
Meaning
Learned per-unit shift (modern code: or bias).
Shape
numbers.
Defined
§4, p. 3.
: element-wise product
Meaning
Multiply entry by entry (the Hadamard product), not a matrix product.
Shape
Two vectors of length H give one of length H.
Defined
§4, p. 3: "element-wise multiplication between two vectors".
: nonlinearity
Meaning
The activation function applied after normalising (the paper's RNN setting). In a Transformer's LayerNorm there is no f: take it as the identity.
Shape
A function, applied entry by entry.
Defined
Eq. (1), p. 2.
: number of hidden units
Meaning
How many entries are averaged.
Shape
A number: here 4.
Defined
Eq. (3), p. 2: "H denotes the number of hidden units in a layer".
: output
Meaning
The normalised, rescaled, shifted vector.
Shape
numbers.
Defined
Eq. (4), p. 3.
Read it aloud
h at time t equals f of: g over sigma, times element by element the vector a minus its mean, plus b; where mu is the average of a's H entries and sigma the square root of their average squared deviation.
With tiny numbers
One example, H = 4, f = identity (as in a Transformer). Gain and bias are illustrative.
The mean of this one example's four entries.
Divide by H = 4, not 3.
Now mean 0 and (population) standard deviation 1.
Scale entry by entry, then shift.
The trap: dividing by H − 1 gives different outputs. PyTorch's LayerNorm uses the paper's 1/H (biased) version.
Traps
Bold is the vector; plain is one entry; the superscript is a time step, not a power. is "sigma at time t", not sigma to the t.
The paper's has no . Code adds one inside the square root: PyTorch's LayerNorm computes with by default and the biased variance (docs).
The averages run over the features of one example (the layer), not over the batch. Eq. (2), batch normalisation, averages over examples with .
The language-modelling objective (next-token log-likelihood)
Radford et al. 2018, Improving Language Understanding by Generative Pre-Training (GPT-1) · Eq. (1), PDF page 3 · §3.1 · Not on arXiv; OpenAI's PDF.
As printed in §3.1.
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: the objective (to maximise)
Meaning
Total log-likelihood of the corpus. It is a sum of logs of probabilities, so it is negative and the paper maximises it. The loss you see in code is its negative, divided by the number of tokens.
Shape
A number.
Defined
Eq. (1), p. 3: "maximize the following likelihood".
: the corpus
Meaning
An unlabelled sequence of tokens .
Shape
token ids.
Defined
§3.1, p. 3.
: the token to predict
Meaning
Token number ; the sum index runs over positions in the corpus.
Shape
One token id (an integer in the vocabulary).
Defined
§3.1, p. 3.
: the context
Meaning
The tokens before position ; is the context window (512 in GPT-1, §4.1).
Shape
token ids.
Defined
§3.1, p. 3: "k is the size of the context window".
: the model's probability
Meaning
Probability the network assigns to the actual next token. Eq. (2) says how: , a softmax over the vocabulary.
Shape
A number in (0, 1], read off a vector of length (vocabulary size).
Defined
Eq. (2), p. 3.
: given
Meaning
Conditional probability: probability of the left side given the right side.
Shape
Notation.
Defined
Standard.
: parameters (after a semicolon)
Meaning
The semicolon separates what we condition on (data) from the parameters that define the model. It is not conditioning in the probabilistic sense.
Shape
All the network's weights (a 12-layer decoder, §4.1).
Defined
§3.1, p. 3: "neural network with parameters Θ".
: natural log
Meaning
Base e, as almost everywhere in ML papers; values are in nats. Divide by ln 2 for bits.
Shape
Function.
Defined
Not stated in the paper (convention).
Read it aloud
L one of U equals the sum, over every position i, of the log of the probability the model with parameters Theta gives to token u i, given the k tokens before it.
With tiny numbers
Vocabulary (the, cat, sat); corpus "the cat sat"; the model's logits at each position are illustrative, the arithmetic is real. Same logits z = (2, 1, 0) as the Reading tab's running example.
Position 2: the right answer, cat, gets 0.245.
Position 3: sat gets 0.844.
Sum the logs (natural log). Position 1 has no context, so it contributes nothing here.
What a training log prints: the negative, averaged per token.
Traps
is maximised; a "loss" is minimised. Papers switch between the two: check the sign and whether the text says maximise or minimise.
The sum is over tokens, so grows with corpus length; training logs report the per-token mean. Comparing a summed and a mean number is a factor of the token count.
is natural (nats). Bits per token divide by ; bits per byte also divide by bytes per token, and only that is comparable across tokenizers.
marks parameters, marks conditioning. Some papers write or : the same thing.
The six update lines of Algorithm 1, as printed, without the comments in brackets.
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: gradient at step t
Meaning
Gradient of this step's (mini-batch) loss with respect to the parameters, evaluated at the previous parameters.
Shape
Same shape as the parameters (here one number; in a model, every weight).
Defined
Algorithm 1, p. 2.
: gradient with respect to θ
Meaning
The vector of partial derivatives, one per parameter.
Shape
Same shape as θ.
Defined
Standard.
: element-wise square
Meaning
Each entry squared on its own, , not a dot product and not a matrix square.
Shape
Same shape as θ.
Defined
Algorithm 1 caption, p. 2: "g_t^2 indicates the elementwise square".
: first moment (running mean of gradients)
Meaning
An exponential moving average of gradients: momentum.
Shape
Same shape as θ; starts at 0.
Defined
Algorithm 1, p. 2.
: second raw moment (running mean of squared gradients)
Meaning
An exponential moving average of squared gradients: a per-parameter scale.
Shape
Same shape as θ; starts at 0.
Defined
Algorithm 1, p. 2.
: bias-corrected estimates (the hat)
Meaning
The hat marks a corrected estimate: because m and v start at 0, early averages are too small; dividing by 1 − β^t undoes that.
Shape
Same shape as θ.
Defined
Algorithm 1 and §3, p. 2-3.
: β to the power t
Meaning
Here the superscript is a real power: . The caption says so ("we denote β1 and β2 to the power t").
Shape
A number.
Defined
Algorithm 1 caption, p. 2.
: decay rates
Meaning
How much of the old average to keep each step. Defaults 0.9 and 0.999.
Shape
Numbers.
Defined
Algorithm 1 caption, p. 2.
: step size (learning rate)
Meaning
Default 0.001. Roughly the largest step any parameter takes.
Shape
A number.
Defined
Algorithm 1 caption and §2.1.
: a small constant
Meaning
Keeps the division safe when is tiny. Default . Here is a constant, unlike the noise in diffusion.
Shape
A number.
Defined
Algorithm 1 caption, p. 2.
: parameters after step t
Meaning
The weights being trained; subscript t is the step number.
Shape
Any shape (a vector of all weights).
Defined
Algorithm 1, p. 2.
: assignment
Meaning
Overwrite the left side with the right side (an algorithm step), not an equation to solve.
Shape
Notation.
Defined
Standard pseudocode.
Read it aloud
Get the gradient; update the running average of gradients and of squared gradients; correct both for starting at zero; then move each parameter by alpha times its corrected average gradient divided by the square root of its corrected average squared gradient plus epsilon.
With tiny numbers
One parameter θ, loss f(θ) = θ², so g = 2θ. Start θ0 = 1, α = 0.1 (larger than the 0.001 default so the steps are visible), β1 = 0.9, β2 = 0.999, ε = 10⁻⁸.
Both averages start at 0, so after one step they are far too small.
Bias correction restores the gradient's real size.
The first step is exactly α in size, whatever the gradient's scale.
Now 1 − β1² = 0.19 and 1 − β2² = 0.001999.
Again a step close to α.
The trap: skipping bias correction makes the first step about 3 times α here.
Traps
Two kinds of superscript in one algorithm: is an element-wise square, is a power, and as a subscript is a step counter.
The hat means "bias-corrected estimate" here. In PPO and the hat means "estimated from samples". Same mark, related but different job.
sits outside the square root in Algorithm 1. Some libraries put it inside; the difference matters only when is tiny.
are Adam's decay rates; the same letter is a KL strength in DPO and RLHF and a noise schedule in DDPM.
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: the frozen pretrained weight
Meaning
The original matrix; it receives no gradient updates.
Shape
: here ; a 4096-wide projection is .
Defined
§4.1, p. 4: "W0 ∈ R^(d×k)".
: the input
Meaning
One input vector, written as a column: the weight multiplies it from the left.
Shape
: here 3 numbers.
Defined
§4.1, p. 4.
: the update
Meaning
The change fine-tuning makes to . means "change in", not a separate variable.
Shape
, but never stored: it is .
Defined
§4.1, p. 4.
: up-projection
Meaning
Trainable; initialised to zero, so the update starts at zero.
Shape
: here .
Defined
§4.1, p. 4: "B ∈ R^(d×r)"; zero init in the next paragraph.
: down-projection
Meaning
Trainable; random Gaussian initialisation.
Shape
: here .
Defined
§4.1, p. 4.
: the output
Meaning
What the layer produces for input x.
Shape
.
Defined
§4.1, p. 4.
Read it aloud
h equals W zero times x plus the update times x, and the update is B times A, so the extra output is B times A times x.
With tiny numbers
d = k = 3, rank r = 1. Illustrative weights, real arithmetic.
The frozen path.
Squeeze x down to r = 1 number.
Expand back to d = 3 numbers.
Add the two paths.
Why it is cheap: r(d + k) numbers instead of d × k.
Traps
Column-vector convention: LoRA writes with of shape (out by in). PyTorch's nn.Linear stores its weight as (out, in) too but computes on row vectors. Same numbers, transposed bookkeeping.
Eq. (3) leaves out the scaling: the paper scales by (§4.1), and implementations do too. A rank change without a matching change changes the effective learning rate.
Read right to left: costs multiplications per input; forming first costs memory.
As printed (≜ means "defined as"). Appendix D.2, Eq. (10), gives the fit: E = 1.69, A = 406.4, B = 410.7, α = 0.34, β = 0.28.
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: predicted loss (the hat)
Meaning
The hat marks a model's prediction of the loss, not a measured one. The loss is the final pretraining loss in nats per token on the paper's data.
Shape
A number.
Defined
Eq. (2), p. 6.
: parameters
Meaning
Model size: number of parameters.
Shape
A number, e.g. for Chinchilla.
Defined
§3, p. 6.
: training tokens
Meaning
How many tokens the model is trained on.
Shape
A number, e.g. .
Defined
§3, p. 6.
: irreducible loss
Meaning
The paper: "the loss for an ideal generative process on the data distribution", which "should correspond to the entropy of natural text". Not an expectation here: a constant.
Shape
A number: 1.69.
Defined
§3.3, p. 6.
: fitted coefficients
Meaning
Constants fitted to the training runs.
Shape
Numbers: 406.4 and 410.7.
Defined
Eq. (10), Appendix D.2, p. 25.
: exponents
Meaning
How fast each term shrinks: is a power. Fitted , .
Shape
Numbers.
Defined
Eq. (10), p. 25.
: defined as
Meaning
This is a definition of the form, not a result to be checked. Same job as := elsewhere.
Shape
Notation.
Defined
Eq. (2).
Read it aloud
L hat of N and D is defined as E, plus A over N to the alpha, plus B over D to the beta: an irreducible floor plus a penalty for a small model plus a penalty for too little data.
With tiny numbers
The paper's fitted constants, plugged in at two real models: Chinchilla (70B parameters, 1.4T tokens) and Gopher (280B, 300B tokens).
The data term is the bigger penalty here.
Predicted loss, nats per token.
Four times the parameters, under a quarter of the tokens: a higher predicted loss.
At similar compute, the smaller model trained longer is predicted to win: the paper's point.
Traps
is a constant (the loss floor), not an expectation . Font and context tell them apart: is blackboard bold and is followed by brackets.
The printed constants are rounded; re-deriving the paper's other numbers from them lands slightly off (the Chinchilla paper page shows by how much, and the Besiroglu et al. 2024 replication).
and here are exponents of a fit; in Adam they are a step size and decay rates. Letters are reused freely across papers.
As printed in §2.3 (Eq. (3) defines f_k on the same page).
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: the loss, for sets of N
Meaning
The subscript N is the number of samples in each set: one positive plus N − 1 negatives.
Shape
A number.
Defined
Eq. (4), p. 3.
: average over sets X
Meaning
The subscript under E says what is random: here the set X of samples. In practice, the mean over the sets in a batch.
Shape
Notation.
Defined
§2.3, p. 3.
: one set of candidates
Meaning
: one sample from (the positive) and from (negatives).
Shape
items: here 3.
Defined
§2.3, p. 3.
: score function
Meaning
A positive score, (Eq. 3); the paper shows it is proportional to a density ratio, not a probability.
Shape
A positive number per candidate.
Defined
Eq. (3), p. 3; Eq. (2), p. 3.
: the true future sample
Meaning
What actually came k steps after time t: the positive.
Shape
One input (e.g. a window of audio); scored through its encoding z.
Defined
§2.1-2.3.
: context
Meaning
The model's summary of everything up to time t.
Shape
A vector (256 dimensions in the audio experiments, §3.1).
Defined
§2.2, p. 3: c_t = g_ar(z_≤t), a summary of all encodings up to t.
: every candidate in the set
Meaning
The sum index: j runs over all N candidates, the positive included.
Shape
Notation.
Defined
Eq. (4).
Read it aloud
L N equals minus the average, over sets X, of the log of the positive's score divided by the sum of the scores of every candidate in the set.
With tiny numbers
One set with N = 3: the positive's score z·Wc = 2.0, two negatives 0.5 and −1.0 (illustrative scores, real arithmetic).
Exponentiate the scores.
The positive's share: a softmax over the set.
Cross-entropy with the positive as the label. Averaged over many sets in practice.
The paper's bound (unnumbered display, p. 4): the estimate can never exceed log N, so more negatives raise the ceiling.
Traps
It is ordinary softmax cross-entropy where the classes are the candidates in the set; CLIP's loss is the same thing applied in both directions over a batch.
The subscript under names the random thing. here; elsewhere reads "average over x drawn from p".
is the set size, not the dataset size; and are a time step and how far ahead, not a temperature or a key.
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: average over three random things
Meaning
t uniform from 1 to T, an image x0 from the data, noise ε from a standard Gaussian. Each training step draws one of each per example.
Shape
Notation.
Defined
§3.4, p. 5: "t is uniform between 1 and T".
: a clean data sample
Meaning
A real image, scaled to [−1, 1].
Shape
Same shape as the image: for CIFAR-10; here 2 numbers.
Defined
§2 and §3.3.
: the noise
Meaning
Gaussian noise, . Not a small constant: in Adam the same letter is.
Shape
Same shape as .
Defined
§3.2, p. 3: "for ε ∼ N(0, I)".
: the network's guess of the noise
Meaning
A neural network (a U-Net, §4) that sees the noisy input and t and predicts which noise was added.
Shape
Same shape as .
Defined
§3.2, Eq. (11), p. 4.
: cumulative signal kept (the bar)
Meaning
Here the bar is a product, not an average: with . It shrinks from about 1 to about 0 as t grows.
Shape
A number per t.
Defined
§2, p. 2, just before Eq. (4).
: noise level (time step)
Meaning
Which step of the forward noising process; T = 1000 in the paper.
Shape
An integer from 1 to T.
Defined
§4, p. 5.
: squared Euclidean norm
Meaning
Sum of squared differences over every pixel: a mean-squared-error, up to a constant factor.
Shape
A number.
Defined
Standard.
: defined as
Meaning
Introduces a new name for the expression on the right.
Shape
Notation.
Defined
Standard.
Read it aloud
L simple of theta is defined as the average, over a random step t, a data sample x zero and Gaussian noise epsilon, of the squared distance between the noise and the network's guess of the noise from the noised sample.
With tiny numbers
A 2-pixel "image"; t = 200 with the paper's linear schedule (β from 10⁻⁴ to 0.02 over T = 1000, §4). The network's guess is illustrative.
From the paper's schedule, computed in recompute.py.
The noised input the network sees.
Suppose this is the network's guess.
Sum over pixels. A mean over pixels (common in code) gives 0.025: the same loss up to a constant.
Traps
The bar on is a cumulative product. Elsewhere a bar often means a mean () or a complex conjugate. Look for the definition.
is the noise, bold because it is a vector; the predicted noise carries the parameters as a subscript, .
Three variables sit under the : all three are sampled every step. Dropping one (say, a fixed t) changes what is learned.
Ouyang et al. 2022, Training language models to follow instructions with human feedback (InstructGPT) · arXiv 2203.02155v1 · Eq. (2), PDF page 9 · §3.5
As printed (the paper breaks the line after the first expectation).
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: the policy's parameters
Meaning
What is being trained: the language model's weights. The objective is a function of φ.
Shape
All the policy's weights.
Defined
§3.5, p. 9.
: the policy being trained
Meaning
The language model as a policy: is the probability of response y to prompt x (a product of token probabilities).
Shape
A probability per (prompt, response) pair.
Defined
p. 9: "the learned RL policy".
: the frozen reference
Meaning
The supervised fine-tuned model the policy started from; it stays fixed.
Shape
Same as the policy.
Defined
p. 9: "the supervised trained model".
: sampled from the policy itself
Meaning
Prompts x come from the dataset and responses y are generated by the current policy. The distribution depends on φ, which is why this needs RL (PPO) rather than plain backprop through the expectation.
Shape
Notation.
Defined
Eq. (2), p. 9.
: the reward model
Meaning
A separate network that scores a response. Here θ is the reward model's parameters, not the policy's.
Shape
A number per (x, y).
Defined
§3.5, p. 8-9; trained with Eq. (1).
: KL reward coefficient
Meaning
How strongly drifting from the SFT model is penalised. 0.02 in the paper.
Shape
A number.
Defined
p. 9; value in Appendix C.4, p. 42.
: pretraining-mix coefficient
Meaning
Weight on keeping pretraining likelihood high ("PPO-ptx"). 0 for plain PPO; 27.8 worked across sizes.
Shape
A number.
Defined
p. 9; value in Appendix E.6, p. 53.
: pretraining distribution
Meaning
Ordinary text; here is the probability of that text itself.
Shape
Notation.
Defined
p. 9.
Read it aloud
The objective, as a function of the policy's weights phi, is the average over prompts and the policy's own responses of the reward minus beta times the log of how much more likely the policy makes the response than the SFT model did; plus gamma times the average log-likelihood of pretraining text.
With tiny numbers
One prompt and one sampled response. Reward, probabilities and the pretraining log-likelihood are illustrative; β = 0.02 and γ = 27.8 are the paper's.
The policy now makes this response twice as likely as the SFT model.
The penalised reward this sample contributes.
Pretraining term for one text, taking −2.0 as its log-likelihood (illustrative, per token). Large in size, but what matters is its gradient.
Traps
For one sample, can be negative; only its average over , the KL divergence, is guaranteed to be at least 0.
Two parameter letters: for the policy, for the reward model. In DPO and GRPO the policy is . Never assume θ means the model being trained.
This is an objective to maximise, written without a minus sign. Code minimises its negative.
of a whole response is a product over tokens, so its log is a sum of token log-probabilities.
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: empirical average over time steps
Meaning
The hat means it is computed from samples: "the empirical average over a finite batch of samples". Not a true expectation.
Shape
Notation.
Defined
§2.1, p. 2.
: probability ratio
Meaning
: how much more likely the new policy makes the action that was taken. Equals 1 before any update.
Shape
A positive number per time step.
Defined
§3, p. 3.
: advantage estimate
Meaning
How much better the action was than expected; the hat says it is an estimate (computed with GAE in the paper, Eq. 11).
Shape
A number per time step.
Defined
§2.1, p. 2; Eq. (11), p. 5.
: clip range
Meaning
How far the ratio may move before the objective stops rewarding the move. The paper: "say, ε = 0.2".
Shape
A number.
Defined
§3, p. 3.
: clip
Meaning
pins r into the interval [0.8, 1.2].
Shape
A function.
Defined
§3, p. 3.
: the smaller of the two
Meaning
Takes the more pessimistic value, so the clip only ever removes gains, never hides losses ("a lower bound ... on the unclipped objective").
Shape
A function.
Defined
§3, p. 3.
: policy parameters
Meaning
Being trained; θ_old are the parameters that generated the samples.
Shape
All weights.
Defined
§2.1.
Read it aloud
L clip of theta is the batch average, over time steps, of the smaller of: the ratio times the advantage, and the ratio clipped to between one minus epsilon and one plus epsilon, times the advantage.
With tiny numbers
ε = 0.2 (the paper's example value); three time steps with illustrative ratios and advantages.
Good action already made much likelier: the gain is capped.
Bad action already made much rarer: credit for pushing it further is capped too.
Bad action made likelier: the full penalty stays. This is why it is a pessimistic bound.
The empirical average over the three steps (to be maximised).
Traps
here is a probability ratio, not a reward (rewards are in most RL papers, including later in this one). Read the definition line.
The superscript CLIP is a label. here is maximised, despite the letter usually meaning a loss.
is a sample average. A hat on an expectation, an advantage or a gradient () means estimated from data.
The DeepSeekMath version (GRPO's paper, Eq. 1) also divides by the response length , averaging over tokens: a per-token form for language models.
Rafailov et al. 2023, Direct Preference Optimization: Your Language Model is Secretly a Reward Model · arXiv 2305.18290v3 · Eq. (7), PDF page 4 · §4
As printed in §4.
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: the policy being trained
Meaning
The language model; π(y | x) is the probability of a whole response.
Shape
A probability per (x, y).
Defined
§3-4.
: frozen reference model
Meaning
Usually the SFT model; it is not updated.
Shape
Same as the policy.
Defined
§3, Eq. (3), p. 3.
: preferred and dispreferred responses
Meaning
w for win, l for lose: a human (or model) preferred y_w over y_l for prompt x.
Shape
Two token sequences.
Defined
§3, p. 2-3.
: the preference dataset
Meaning
A fixed set of (prompt, preferred, dispreferred) triples. Offline: nothing is sampled from the policy during training.
Shape
Notation.
Defined
§3, p. 3.
: logistic sigmoid
Meaning
, the Bradley-Terry probability that y_w beats y_l. Not a standard deviation.
Shape
A number in (0, 1).
Defined
§3, Eq. (2), p. 3.
: KL strength
Meaning
Same role as β in the RLHF objective: how far the policy may move from the reference. The paper uses 0.1 by default and 0.5 for TL;DR summarisation.
Shape
A number.
Defined
Eq. (3), p. 3; values in Appendix B, p. 20.
: semicolon
Meaning
The loss is a function of π_θ, with π_ref held fixed as a setting.
Shape
Notation.
Defined
Eq. (7).
Read it aloud
The DPO loss is minus the average, over preference triples, of the log-sigmoid of: beta times how much more the policy likes the winner than the reference did, minus beta times the same for the loser.
With tiny numbers
One pair; summed token log-probabilities (illustrative), β = 0.1.
Whole-response log-probabilities: sums over tokens.
The policy raised the winner and lowered the loser, relative to the reference.
The implicit reward margin and its Bradley-Terry probability.
Below log 2 means the policy already prefers the winner more than the reference does.
Traps
is the sigmoid here; in LayerNorm and statistics it is a standard deviation. Context: a function applied to something in brackets.
is a probability of a whole response; implementations sum token log-probabilities (not average them), which is why longer responses get larger log-ratios.
is fixed data, unlike RLHF's , which samples from the policy. That one subscript is the online versus offline difference.
As printed inline in §4.1.2 (outcome supervision).
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: advantage of token t in output i
Meaning
Every token of output i gets the same value (outcome supervision): one score for the whole answer.
Shape
A number per token; here outputs.
Defined
§4.1.2, p. 14.
: normalised reward (the tilde)
Meaning
The tilde marks a transformed version of r_i: here centred and scaled within the group.
Shape
A number per output.
Defined
§4.1.2, p. 14.
: reward of output i
Meaning
The reward model's (or a checker's) score for the i-th sampled answer.
Shape
A number.
Defined
§4.1.2, p. 14.
: all G rewards for this question
Meaning
Bold: the vector for one question's group of outputs.
Shape
numbers.
Defined
§4.1.2, p. 14.
: group average
Meaning
Average over this question's G outputs: the baseline that replaces PPO's value network.
Shape
A number.
Defined
§4.1.2.
: group standard deviation
Meaning
The paper does not say whether it divides by G or G − 1. TRL's implementation divides by G − 1 and adds 10⁻⁴ to the denominator.
Shape
A number.
Defined
§4.1.2 (not specified further).
Read it aloud
The advantage of every token in output i equals output i's normalised reward: its reward minus the group's mean reward, divided by the group's standard deviation.
With tiny numbers
G = 4 answers to one maths question, checked right (1) or wrong (0).
Half the group is right.
Right answers get +1 for every token, wrong ones −1.
The same group under the other convention: every advantage is about 13% smaller.
All right (or all wrong): the formula has no value; with TRL's 10⁻⁴ every advantage is 0, so the question teaches nothing.
Traps
is ambiguous: divide by or ? The paper does not say. With small groups the difference is visible (here 0.5 against 0.577). TRL divides by (nanstd) and adds (grpo_trainer.py).
The subscript pair means output i, token t; the value does not depend on t under outcome supervision.
Tilde, hat, bold: transformed, estimated, a vector. Three marks on one line, three meanings.
As printed (the paper writes || between the two distributions).
Tap a symbol
Tap any symbol in the equation (the shaded parts; a wide equation scrolls sideways) or a chip above: its name, meaning, shape with concrete sizes, and where the paper defines it.
: KL divergence (here: its estimate)
Meaning
Written like the true KL, but the right side is a single-token estimate (Schulman 2020): averaged over tokens sampled from , it equals the KL.
Shape
A number per token.
Defined
Eq. (4), p. 14.
: "from": the order matters
Meaning
averages over P. KL is not symmetric: and are different numbers.
Shape
Notation.
Defined
Standard.
: token t of output i
Meaning
The token actually sampled.
Shape
A token id.
Defined
§4.1.1.
: the question and the tokens before t
Meaning
Subscript means all positions before t.
Shape
A token sequence.
Defined
§4.1.1.
: the question (prompt)
Meaning
The input the group of outputs answers.
Shape
A token sequence.
Defined
§4.1.1, p. 13.
: reference model
Meaning
Frozen copy of the policy, reset at each outer iteration (Algorithm 1, line 3).
Shape
A probability per token.
Defined
Algorithm 1, p. 14.
: the policy being trained
Meaning
Probability the current policy gives the sampled token.
Shape
A probability per token.
Defined
§4.1.1.
Read it aloud
The KL from the policy to the reference, for one sampled token, is estimated as the ratio of the reference's probability to the policy's, minus the log of that ratio, minus one.
With tiny numbers
A 3-token vocabulary; policy π_θ = (0.5, 0.3, 0.2), reference π_ref = (0.4, 0.4, 0.2) at one position (illustrative).
The ratio for each possible token.
The estimate if that token is the one sampled. Never negative: x − log x − 1 ≥ 0, equal to 0 only at x = 1.
Averaged over tokens drawn from π_θ it equals the true KL exactly: unbiased.
Also unbiased, but it is negative for the second token: a single sample can say KL < 0.
Traps
The left side looks like the full KL; the right side is a per-token sample. Names in papers are sometimes the target, not what is computed.
"Guaranteed to be positive" (the paper) is strictly "non-negative": it is 0 when the two models agree on the token.
The order: this is KL from to with samples from , the mode-seeking direction RLHF uses.
Habits that papers rarely state. Each comes with a tiny example; "Seen in" opens the equation above where it appears. When a paper defines its notation (often in a short section or a footnote), its definition wins over any of these.
Vectors are columns
A bold lower-case letter is a column vector unless the paper says otherwise, so is a single number (a dot product) and is a matrix (an outer product).
Seen in:
Data matrices: one row per example
Stacked data puts examples in rows, so a layer is applied as with of shape . The same layer on one column vector is or, with stored the other way, . Check which a paper uses before multiplying.
Seen in:
Shapes multiply by the inner sizes
means rows and columns of real numbers. A product needs the inner sizes to match and keeps the outer ones. Writing the shape under every symbol catches most misreadings.
Seen in:
Transpose and Hermitian marks
, and a prime all mean transpose. , and mean conjugate transpose, which matters only for complex numbers (Fourier features, the complex form of RoPE); for real matrices it equals the transpose. Careful: can also mean \"optimal\" () or convolution.
Seen in:
Numerator versus denominator layout
Each entry is the same partial derivative, (nudge by 0.01 and moves by ); the layouts only disagree on how to arrange them. Denominator layout gives the derivative the shape of the thing you differentiate by (, like ); numerator layout gives the transposed, Jacobian-style shape (; for a vector , a row). Autograd always returns a gradient with the parameter's own shape, so a paper written in numerator layout hands you the transpose of W.grad. Authors mix the two (Wikipedia, Matrix calculus). Rule: if a derived gradient's shape does not match the parameter, transpose and check one entry.
Seen in:
and
is one partial derivative; collects all of them, one per parameter. The subscript says which variables move; everything else is held fixed.
Seen in:
versus
returns the best value; returns where it is (which token, which parameters). Greedy decoding is an ; in an RL objective means \"choose the policy that makes this largest\".
Seen in:
: the subscript says what is random
Read as \"the average of the bracket when x is drawn from p\". Several variables under the E () are all random. A hat, , or , means a sample average you actually compute. When the distribution depends on the parameters (RLHF), you cannot just differentiate inside.
Seen in:
means "drawn from"
Between two things, a tilde means \"is distributed as\" or \"is sampled from\". On top of a letter () it means a modified version. In between numbers, some authors mean \"roughly\".
Seen in:
is the natural log
ML papers mean base unless they say bits or write . Information theory books often default to base 2. A loss of 0.788 nats per token is 1.137 bits per token.
Seen in:
The indicator
Also written , or (the Iverson bracket). It turns a condition into 0 or 1, which is how one-hot labels pick out a single term of a sum.
Seen in:
Norms
No subscript usually means the Euclidean (L2) norm; is the Frobenius norm, the L2 norm of all a matrix's entries. A squared norm is a sum of squares, so is a squared error. Single bars mean absolute value, or the size of a set or sequence.
Seen in:
, versus
, and often introduce a definition: nothing to check, just a new name. claims two things are equal (worth checking). is an approximation; can also mean \"identically equal\" or congruence.
Seen in:
(proportional to)
Equal up to a factor that does not depend on the variable of interest. The missing factor is usually a normaliser you can compute later (dividing by the sum over j).
Seen in:
Hats, bars, tildes, stars
Hat: estimated or predicted (and in Adam, bias-corrected). Bar: a mean, but in DDPM a cumulative product, and in complex maths a conjugate. Tilde: a transformed or approximate version. Star: optimal. Each paper defines its own; these are only the usual readings.
Seen in:
: stop-gradient
VQ-VAE (van den Oord et al. 2017, Eq. 3, p. 4): \"identity at forward computation time and has zero partial derivatives\". In code, .detach(). PPO's plays the same role: a fixed number the gradient does not flow into.
Seen in:
: bar versus semicolon
The bar conditions on data (\"given x\"); the semicolon, or a subscript, names the parameters that define the distribution. Parameters are settings, not random events, in this notation.
Seen in:
, ,
multiplies entry by entry (the Hadamard product; some write ). is the Kronecker or outer product. between functions is composition, .
Seen in:
Sum and product indices
The subscript says what the index runs over: a range, or every member of a set. A bare means over all valid i. is the same for products. Capital is a product; lower-case is a policy or 3.14159.
Seen in:
Subscripts and superscripts
A superscript is a power only when nothing else makes sense: it is also a layer (often in brackets), a label, or a time step. A subscript is usually an index or a step; means every position before t.
Seen in:
Letters with two jobs
is a sigmoid when applied to an argument, a standard deviation when it stands alone. , , , and all change meaning between the papers on this tab.
Seen in:
Big-O
How cost grows with size, ignoring constant factors. Doubling the sequence length n quadruples the cost of the score matrix.
Seen in:
Sources: each equation was checked against the paper's PDF text (arXiv versions as linked, GPT-1 from OpenAI's PDF) and, where available, the LaTeX of the ar5iv rendering. Library behaviour: PyTorch 2.14 LayerNorm documentation; TRL at commit 14c8d70 for GRPO's standard deviation. Data: src/notation/equations.json (built by build_equations.py), numbers rechecked by recompute.py.
This tab is practice that spans several child pages, on the tiny model of the Reading tab: you compute a loss, derive its gradient by hand, check it against the computer, follow it backwards through the network, and watch what the learning rate does with it. Each panel names the child page that teaches its idea. Every number on this tab is computed live by the page and was checked against an independent script (numpy, sympy and PyTorch autograd).
The tiny model used everywhere on this tab
Vocabulary of three tokens: cat, dog, sat. After "the cat", the correct next token is sat. The context is turned into a vector of two numbers (its embedding) , the same as in the Reading. The Reading's one-matrix model and the two-layer network used in panel 2 both turn it into three scores, one per token, called logits: for (cat, dog, sat). The softmax turns logits into probabilities , and the loss is . The model gets it wrong: it bets on cat (66.5%) and gives the right answer only 9.0%. Training should move probability to sat.
The weights are illustrative, chosen so the logits come out exactly (2, 1, 0), the running example of the Reading. The two-layer network's weights and are shown in panel 2.
Words used throughout: a gradient is the list of slopes of the loss, one per input number: how much the loss changes per unit nudge of that number. An analytic gradient comes from a formula derived by hand; a numerical gradient is measured by nudging each number a tiny step up and down and timing how the loss moves. If the two disagree, the formula (or the code) is wrong. The derivative, the gradient and the finite-difference check are taught on Calculus and optimisation, section 1 and Matrix calculus and backprop, section 11.
Pick a loss, move the model's raw output with the sliders, and compare the gradient from the formula with the gradient measured by nudging. The striking fact to find: for the three standard pairings (a plain number with squared error, a sigmoid with binary cross-entropy, a softmax with cross-entropy) the gradient with respect to the raw output is the same expression, prediction minus target. The two extra losses show what happens when you change the recipe.
Mean squared error with an identity output. Use it when the target is a real number (a price, a temperature). The model's raw output is used directly as the prediction, (the "identity" output: nothing is applied). The loss is half the squared miss:
In words: square how far the prediction is from the target , then halve it (the half is a convention that makes the derivative tidy).
Chain rule: the loss depends on through , so multiply the two slopes:
Slope of is , so ; and has slope 1.
Multiply:
Without the half, and the gradient is . Averaged over a batch of examples, , each example's gradient is (the old page's "times " is this convention). Worked example: , : , gradient .
Binary cross-entropy with a sigmoid. Use it for a yes/no target (spam or not). The raw output is squashed into a probability by the sigmoid, and the loss is the negative log of the probability given to what actually happened:
In words: if the loss is ; if it is . Only one of the two terms is ever switched on.
Slope of the sigmoid. Write ; the chain rule gives
Slope of the loss in (slope of is ):
Multiply the two and simplify; the cancels the denominators:
Worked example: , : , , gradient (negative: raising lowers the loss).
Softmax cross-entropy. The loss of the tiny model: three logits , one per token, turned into probabilities by the softmax; the loss is minus the log of the probability of the correct token (here cat):
In words: exponentiate every score (all become positive), divide by the total (they now sum to 1), and pay of the share the right answer got. The second form comes from and .
Differentiate the second form with respect to one logit . The first term has slope if and 0 otherwise; write that as , where is the one-hot target (1 for the correct token, 0 elsewhere).
The second term: slope of is , times the slope of in , which is :
Add:
Worked example at the default: , sum 11.107, , nats (3.473 bits), gradient : push cat and dog down, sat up. The entries sum to zero, because both and sum to 1. The old page's "four hats" example uses the same logits with cat correct: nats (0.588 bits), gradient ; the button below the sliders loads it.
Label-smoothed cross-entropy (Szegedy et al. 2016, section 7). Replace the one-hot target by a softened one that gives a little probability to every token: with tokens,
The second form uses and .
Same steps as plain cross-entropy: the first term gives , the second gives .
Still prediction minus target, only the target is the smoothed . The loss can no longer reach zero: its floor is the entropy of . Worked example (, ): , , gradient .
Focal loss (Lin et al. 2017, written there for two classes; here the usual softmax form). It multiplies cross-entropy by so that examples the model already gets right count less:
Slope in (product rule on times ):
Slope of the softmax output in a logit : .
Multiply and collect:
The direction is still , but scaled by a weight that shrinks as the model gets confident ( at , which is plain cross-entropy). It is not one of the canonical pairs, so the tidy cancellation is gone. Worked example () at the default, where the correct token gets only : , , gradient . Here is above 1: on a badly wrong example focal loss pushes harder than plain cross-entropy; move the sat logit up and watch fall below 1.
Loss as you move one input (the dashed line is the analytic slope)
Error of the numerical gradient against the nudge size (log scales; the dot is your )
Numerical gradient: , where nudges only input . Its error has two parts: the formula's own error, which shrinks like , and rounding error from subtracting two nearly equal numbers, which grows like in the page's 64-bit arithmetic. The best sits between, near to here, matching the advice in CS231n's gradient-check notes.
Why three different losses end at the same gradient
Each standard pair is a probability distribution with its "canonical" output function: a Gaussian with the identity, a Bernoulli with the sigmoid, a categorical with the softmax. For every such pair the slope of the output function cancels the slope of the log-likelihood exactly, leaving prediction minus target (Stanford CS229's generalised linear models chapter, main notes). Practical reading: a softmax followed by cross-entropy should never be coded as two separate steps, since the combined gradient is both simpler and safer (see panels 5 and 6).
2. Backprop, step by step: the chain rule run backwards
Taught on:Matrix calculus and backprop, section 5 derives the backward pass of this same two-layer network by hand, with every gradient checked against PyTorch autograd, and its stage walks it one value at a time; its section 8 explains the factor of two in cost. This panel is practice: the tape on the right opens on the finished forward and backward pass; step back through it, switch the model, train the embedding, check the gradient or take a step.
Two versions of the model, both giving the same logits (2, 1, 0). The Reading's model is one matrix: , then softmax and the loss, with rows cat (1, 0), dog (0, 1), sat (1, ). Its backward pass is , , , and one step at learning rate 0.1 takes the loss from 2.408 to 1.773, as in the Reading. The two-layer network below adds a hidden layer with a relu, which shows what a nonlinearity does to the backward pass. Its chain has five simple steps. The forward pass computes each value from the one before. The backward pass then walks the chain in reverse, and at each step asks one question: "if this value moved a little, how much would the loss move?" That number is the value's gradient. Each backward step only needs the gradient of the step after it and the local slope of its own operation; this product is called a vector-Jacobian product (VJP), the Jacobian being the table of local slopes, which is never built in full.
: the embedding of "the cat" (2 numbers). : first weight matrix (3 rows, 2 columns), so has 3 numbers. element by element: negative values become 0. : second weight matrix (3 by 3). Gradients are written ("v-bar"), with the same shape as .
is the transpose (rows become columns), multiplies element by element, is 1 where is positive and 0 elsewhere. A matrix's gradient is always (gradient coming in) times (input that went in), transposed into the matrix's shape; an input's gradient is the matrix, transposed, times the gradient coming in. Each matrix product in the forward pass therefore becomes two in the backward pass.
Multiply-add count: a matrix with rows and columns costs multiply-adds to apply. The Reading's model: forward is 6; backward 6 and 6, total 12, twice forward (6 if the embedding is held fixed). Two layers: forward is 6, is 9, total 15. Backward: 9, 9, 6, 6, total 30, exactly twice; 24 if the input is not trained (the first layer then needs no input gradient). Softmax, relu and the loss are a handful of extra operations, not counted. This factor of two is why training compute is usually counted as per token for a model with parameters: forward and backward (Kaplan et al. 2020, section 2.1). The backward pass also needs the forward values (, , , ) kept in memory, which is why activations, not arithmetic, usually limit training memory.
3. Curvature and step size: why the learning rate has a ceiling
Taught on:Calculus and optimisation, section 4: its Fig. 4 runs gradient descent on a stretched bowl and owns the step limit (each step multiplies the distance along a direction of curvature by , so must stay below , and a large condition number makes the flat direction slow); momentum and Newton follow in its sections 4 and 5, with eight methods on four landscapes in its Optimisation lab. This panel is practice: one bowl, four optimisers, presets that land in each regime.
Close to a minimum, almost any loss looks like a bowl. With two parameters the bowl is
is the Hessian, the table of second derivatives. Its eigenvalues and are the curvatures along the bowl's steepest and flattest directions (the axes of the ellipses on the right), is the condition number and the learning rate. The path replays when you pick an optimiser or a preset.
The same limit on the tiny model: at the Reading's starting point the steepest curvature of the loss along the weights is (the largest eigenvalue of , times ), so the local limit is about . The learning rates 0.1, 0.3 and 1 in panel 2 all sit below it (one step each: loss 1.773, 0.778, 0.011). It is a local limit: the curvature changes as the weights move.
Momentum, Adam and Newton, in one line each
Momentum keeps a running velocity, , ( here): steps that agree add up along the flat direction, steps that flip sign cancel across the steep one. On a bowl it is stable up to (Goh 2017). Adam (Kingma and Ba 2014, defaults , ) divides each coordinate's averaged gradient by the root of its averaged square, so every coordinate moves by about per step whatever its curvature. Intuition only: that evens out a valley lined up with the axes, helps less when the valley is diagonal (try the rotation slider), and is a rough per-coordinate scale, not a curvature estimate. Newton's method uses the curvature itself: step , which on an exact bowl lands on the minimum in one step whatever is (Boyd and Vandenberghe, section 9.5); for a network with parameters, has entries, which is why it is not used directly.
Loss contours and the path from the start (dot) towards the minimum (cross)
Loss per step (log scale)
4. Bernoulli curvature: one number, three meanings
Take the binary cross-entropy of panel 1 and ask three different-sounding questions about it. The answer to all three is , where . The page computes each one by its own route (no shared formula), so the agreement below is a check, not a copy.
Curvature (Hessian): the second derivative of the loss in , measured by nudging both ways: . Done separately for and : the label does not matter.
Variance of the label: if the label really is a coin with , its spread around its mean is , summed over the two outcomes.
Fisher information: the average squared score, the score being the slope of the log-likelihood in (measured by nudging, for each outcome), averaged with weights and .
At all three are 0.25, the largest they get; at () all three are 0.09 (both values from the old page, recomputed). A confident prediction sits in a flat part of the loss: the gradient there barely changes as moves. That curvature equals Fisher information for every canonical pair (the label drops out of the second derivative) is why natural-gradient methods and K-FAC can use the Fisher as their curvature: for the whole network it equals the Gauss-Newton form of the Hessian (Martens 2020, section 9.2).
5. Overflow and the log-sum-exp trick
Taught on:Numerical computing, section 7 (the stable softmax, log-sum-exp and log-softmax, with the naive and stable versions animated side by side). This panel is practice.
Computers store numbers with a largest value. passes it at in 64-bit floats, in 32-bit floats and in 16-bit floats (each is of the format's largest number). Past it the computer returns infinity, and infinity divided by infinity is "not a number" (NaN). The fix uses a fact about the softmax: adding the same constant to every logit changes nothing, because (the cancels). Subtract the largest logit first, so the biggest exponent is :
32-bit results are emulated by rounding every intermediate to 32 bits (JavaScript's Math.fround). The libraries do this for you only if you call the fused function: PyTorch's CrossEntropyLoss takes "unnormalized logits" (its docstring), and BCEWithLogitsLoss is "more numerically stable than using a plain Sigmoid followed by a BCELoss" because it uses "the log-sum-exp trick" (same file). Error analysis: Blanchard, Higham and Higham 2021.
6. Spot the bug: eight real gradient bugs and the symptom each leaves
Debugging runs from the symptom back to the line. Each card shows a symptom, produced live by running the buggy code's maths on the tiny model, and a short piece of code (numpy or PyTorch style). Find the wrong line, then reveal it. The habits that catch all eight: run a gradient check on a tiny model, watch the first few loss values, and check shapes.
Sources for the library behaviour named on the cards
PyTorch: CrossEntropyLoss expects "unnormalized logits" and its default reduction is the mean (loss.py); "Gradients by default add up; to prevent double-counting, we explicitly zero them at each iteration" (optimisation tutorial); detach "Returns a new Tensor, detached from the current graph. The result will never require gradient" (tensor docs). The batch in bugs 4 and 8 is the example from scikit-learn's mean_squared_error page (answer 0.375). Broadcasting rules: numpy. Thresholds for a gradient check (relative error above "probably wrong", below usually fine with kinks such as relu): CS231n.
Every number on this tab is recomputed in src/grad/recompute.py (sympy for the derivations, numpy for the values, PyTorch autograd for the network and the softmax-twice bug), and the page's own JavaScript is compared against it by src/grad/check_js.mjs.
Further reading
Reading times for knowledge base pages are each page's own header (core reading, plus optional closed blocks) where it states one, otherwise estimated from the length of its Reading tab (about 230 words a minute). Times for outside resources are for the part recommended, checked on 5 October 2026. Every link opens in a new tab.
Fourteen landmark equations quoted exactly and decoded symbol by symbol, plus the conventions papers use without explaining them: Greek letters, subscripts, shapes, the two layouts for derivatives. Use it with step 1 of "How to read an equation".
Practice on the tiny model across the children: three losses and their gradients, backprop on the one-matrix and two-layer models, the curvature bowl with gradient descent, momentum, Adam and Newton, Bernoulli curvature, overflow and log-sum-exp, and eight real gradient bugs.
Products and shapes, rank, norms, least squares, eigenvalues, the SVD and conditioning; low rank measured on GPT-2's weights and real LoRA updates. Tab: Matrix playground.
Jacobians and layouts, vector-Jacobian products, forward and reverse mode, backprop through a two-layer network by hand (this page's Gradient lab network), layer gradients, cost, memory and gradient checking.
Distributions, the losses as likelihoods, proper scoring and calibration on three real models, priors, LLN and CLT by simulation, sampling and reparameterisation. Tab: Distribution explorer.
Taylor models, loss gradients, Hessians, gradient descent and its step limit, Newton and quasi-Newton, convexity, Lagrange and KKT, stochastic gradients, the edge of stability. Tab: Optimisation lab.
Entropy and codes, cross-entropy and KL, temperature, perplexity and bits per byte on real text, mutual information, InfoNCE, KL penalties and estimators. Tabs: Entropy and KL lab, Real text, measured.
IEEE 754, epsilon and rounding, the formats from float64 to FP8, cancellation, summation and determinism, the stable softmax, mixed precision, NaN hunting. Tab: Float explorer.
The ELBO three ways with its gap, mean-field and amortised inference, gradients through samples, and the closed derivations D1 to D8 the generative pages cite.
A reading path, from rusty to research
In order. Each step says when to read it; stop when your goal is met. The first two steps rebuild intuition, the next four rebuild technique, the last two take you to research depth.
16 short animated videos: vectors, matrices as maps, determinants, eigenvectors. When: first, before any book, if linear algebra feels shaky. About 3 h.
Cambridge University Press 2020, free PDF. Chapters 2 to 7 (linear algebra, analytic geometry, matrix decompositions, vector calculus, probability and distributions, continuous optimisation) cover the first five child pages in ML notation. When: the backbone text once the videos are done; read the chapter matching whichever child page you want deeper. About 20 to 30 h for chapters 2 to 7.
Jacobians, the vector chain rule and layout conventions, assuming only school calculus. When: before deriving your first backward pass by hand. About 1 h 30 min to 2 h 30 min, with a pencil.
Losses derived as maximum likelihood (generalised linear models), plus the short linear algebra review (Kolter, 26 pages) and probability review (Maleki and Do, 12 pages). When: the reviews as a checklist before interviews; the notes' first chapters to see every loss derived as a likelihood. About 1 h for the probability review, 2 to 3 h for the linear algebra review, about 5 h for the first chapters of the notes.
18.06: 34 recorded lectures, the classic course. 18.065 (2018, with the book Linear Algebra and Learning from Data, 2019): lectures 1 to 9 on least squares, the SVD, Eckart-Young and norms, and 21 to 27 on gradient descent, momentum, SGD and backprop. When: when you want the SVD and low-rank methods (LoRA, compression) properly, or a rigorous full course. About 12 h for the 18.065 lectures named; about 25 h for all of 18.06.
Free PDF. Chapters 2 to 5: convex sets, convex functions, convex problems, duality (Lagrange multipliers done properly). For a gentler start, the same authors' free Introduction to Applied Linear Algebra (2018). When: research on constrained objectives (KL-constrained updates, regularisation as a constraint); optional for most engineering work. About 10 h for chapters 2, 3 and 5.1 to 5.5; 20 to 30 h for all four.
Both free to read online. The 2024 book's chapters 2 (probabilities) and 7 (gradient descent) cover probability, optimisation and statistics at research depth; PRML chapters 1 and 2 are the classic treatment of probability for ML. When: when you start reading papers that assume Bayesian reasoning or new losses. About 4 to 6 h for the two 2024 chapters; 8 to 10 h for PRML chapters 1 and 2.
Free PDF. Chapters 1, 2, 4 and 8 (introduction; probability, entropy and inference; the source coding theorem; dependent random variables). When: after Olah, for research on estimators, bounds and compression. About 8 to 12 h.
Reference: The Matrix Cookbook (Petersen and Pedersen, version of 15 November 2012)
72 pages of matrix identities and derivatives. When: look things up while deriving; do not read it through. About 30 min to learn your way around.
The backward pass's memory at scale: activation checkpointing and sharding.
Paper pages
Attention Is All You Need (20 min, plus 2 in closed details; the equation read in five steps), LoRA (about 25 min; low rank), CLIP (about 27 min; InfoNCE at scale), DPO (about 24 min; KL and the Bradley-Terry likelihood), Scaling Laws for Neural Language Models (about 21 min; the 6N compute accounting).
Primary sources behind this page
The claims each source supports are now explained on the child page that owns them (named in brackets).
Kingma and Ba 2014, Adam: the second-moment estimate and its relation to the diagonal Fisher (section 5 of the paper; Calculus and optimisation). About 45 min.