Reading the Math in AI Papers · Part 1 of 1

How to read the math in arXiv AI papers: a practical guide

Reading the mathematics in an AI paper is a useful skill for engineers who need to understand a model, reproduce a method or assess an experimental claim. This guide explains how to decode the notation, check an equation on small numbers and connect it to the surrounding paper and implementation. It assumes you can read code, but does not assume that research notation is already familiar.

An equation compresses several decisions into one line: the objects being manipulated, their dimensions, which values are sampled, and what is learned or held fixed. Recovering those details is a good first step. Explaining why a method works and implementing it faithfully take further work.

Start with the attention walkthrough: it connects one equation to array shapes, small numbers and runnable Python. The notation reference explains the expressions you will meet in other papers. The rest of this series applies the same method to equations from specific papers: architecture equations such as RoPE, MLA and LoRA; training objectives such as DPO and GRPO; and generative models and metrics such as the ELBO, diffusion and pass@k. Those parts come out on 4, 5 and 6 November; until then, the walkthroughs this part refers to are not linked. For a longer treatment of the foundations, Tianhua Chen’s The Little Book of Generative AI Foundations develops the linear algebra and probability behind generative models.

Attention, read one symbol at a time

Attention produces an output vector by taking a weighted average of value vectors. It obtains the weights by comparing a query vector for the output position with a key vector for each available input position. The matrices QQ, KK and VV collect those query, key and value vectors. Scaled dot-product attention combines these steps in equation (1) of §3.2.1 (§ means “section”) in Attention Is All You Need:

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk)V.\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.

The definitions are in the text, not in the equation. The paragraph before equation (1) says that queries and keys have dimension dkd_k and values have dimension dvd_v. The method takes the dot product of each query with all keys, divides each by dk\sqrt{d_k} and applies a softmax “to obtain the weights on the values”. Queries are “packed together into a matrix QQ”, and keys and values into KK and VV. So each row of these matrices is one token’s vector, and the softmax produces one set of weights per query. The learned matrices that turn token vectors into QQ, KK and VV appear later, in §3.2.2.

Shapes and roles. An attention head performs one such calculation with its own query, key and value vectors. Write down their shapes before reading the operators. For one head with nn queries and mm keys:

SymbolShapeWhat it isWhere it comes from
QQn×dkn\times d_kone query row per output positiontoken vectors times a learned matrix
KKm×dkm\times d_kone key row per position that can be attended totoken vectors times a learned matrix
VVm×dvm\times d_vone value row per keytoken vectors times a learned matrix
K⊤K^\topdk×md_k\times mKK transposed: rows become columnsthe same numbers as KK
dkd_ka numberthe width of each query and keya fixed setting: 64 in the base Transformer

Papers give a shape by naming the set the matrix belongs to: Q∈Rn×dkQ\in\mathbb R^{n\times d_k} means a matrix of real numbers with nn rows and dkd_k columns, an array of shape [n, dk].

Read from the inside out.

  1. QK⊤QK^\top multiplies an n×dkn\times d_k matrix by a dk×md_k\times m matrix. The shared dkd_k is summed away, so the result is an n×mn\times m table of scores. Entry (i,j)(i,j) is the dot product of query ii and key jj: multiply corresponding entries, then add the products. For fixed vector lengths, this score is larger when their directions are more similar.

  2. Dividing by dk\sqrt{d_k} stops the scores from growing with the vector width. Footnote 4 of the paper shows why unscaled dot products grow. Suppose the components of a query and a key are independent of one another (knowing some of them tells you nothing about the others), each with mean 0 and variance 1 (the average squared distance from the mean). Then:

    one product qiki:variance 1q⊤k=∑i=1dkqiki:variance dk, standard deviation dkq⊤k/dk:standard deviation 1\begin{aligned} \text{one product }q_ik_i:&\quad\text{variance }1\\ q^\top k=\textstyle\sum_{i=1}^{d_k}q_ik_i:&\quad\text{variance }d_k,\ \text{standard deviation }\sqrt{d_k}\\ q^\top k/\sqrt{d_k}:&\quad\text{standard deviation }1 \end{aligned}

    The lines use two rules about independent numbers. First, the product of two independent numbers that each have mean 0 and variance 1 also has variance 1. Second, when independent numbers are added, their variances add, so the dkd_k products give variance dkd_k. The standard deviation is the square root of the variance, dk\sqrt{d_k}. Dividing every score by dk\sqrt{d_k} shrinks the spread by the same factor, back to 1.

    Why the two rules hold

    Variance when the mean is 0. Variance is the average squared distance from the mean. When the mean is 0, the squared distance from the mean is just the square of the number, so the variance is the average of the square. A component qiq_i with mean 0 and variance 1 therefore has qi2q_i^2 averaging 1.

    The average of a product. For independent numbers, the average of a product is the product of the averages. Take a number aa that is 1 or 3 with equal chance, so it averages 2, and a number bb that is 1 or 5, also with equal chance, so it averages 3. Independent means that bb takes each of its values equally often whatever aa turned out to be, so all four pairs are equally likely. When a=1a=1, the products are 1 and 5, which average 3=1×33=1\times3. When a=3a=3, they are 3 and 15, which average 9=3×39=3\times3. Either way the average is a×3a\times3, so over both values of aa it is (3+9)/2=6(3+9)/2=6, which is 2×32\times3. Without independence the rule fails: if bb were 5 whenever aa is 3, and 1 whenever aa is 1, only the products 1 and 15 would occur, and they average 8. Wikipedia states the rule for any independent random variables, with “expected value” for the average: independence and expectation.

    Rule 1: one product has variance 1. Take one product qikiq_ik_i. Its mean is the product of the averages, 0×0=00\times0=0, so its variance is the average of (qiki)2=qi2ki2(q_ik_i)^2=q_i^2k_i^2. The squares are independent because qiq_i and kik_i are, and each averages 1, so the variance is 1×1=11\times1=1. The general formula is the variance of a product of independent variables.

    Rule 2: the variances of independent terms add. Call the products xi=qikix_i=q_ik_i, so the dot product is the sum x1+⋯+xdkx_1+\cdots+x_{d_k}. The terms are independent because each uses different components, and each has mean 0 and variance 1. The sum has mean 0 too, so its variance is the average of its square. Multiplying the sum by itself gives one product xixjx_ix_j for every pair of terms, a dk×dkd_k\times d_k grid:

    A four by four grid for the square of x1 + x2 + x3 + x4, with one cell for each product of two terms. The four diagonal cells, x1 squared to x4 squared, are highlighted: each averages 1, so together they add 4. The twelve other cells multiply two different independent terms and each averages 0 times 0, so they add 0. The square of the sum averages 4: variance 4, standard deviation 2. With 64 terms, the same count gives variance 64 and standard deviation 8.A four by four grid for the square of x1 + x2 + x3 + x4, with one cell for each product of two terms. The four diagonal cells, x1 squared to x4 squared, are highlighted: each averages 1, so together they add 4. The twelve other cells multiply two different independent terms and each averages 0 times 0, so they add 0. The square of the sum averages 4: variance 4, standard deviation 2. With 64 terms, the same count gives variance 64 and standard deviation 8.

    The diagonal cells are the squares xi2x_i^2, and each averages 1. Every other cell multiplies two different, independent terms, so its average is the product of their averages, 0×0=00\times0=0: its positive and negative values cancel. Only the dkd_k diagonal cells are left, so the variance of the sum is dkd_k and its standard deviation is dk\sqrt{d_k}. The spread grows with the square root of the width because most of the grid cancels out. Wikipedia gives the general statement as the variance of a sum of uncorrelated variables; independent variables are always uncorrelated, so the rule covers them.

    With dk=64d_k=64, raw scores typically spread over about ±8\pm8; scaled, over about ±1\pm1, at any width.

    Widely spread scores saturate softmax (step 3), and its gradients vanish. If one score in a row is far above the others, softmax gives that key a weight near 1 and every other key a weight near 0. A small change to any score then barely moves the weights, so the gradient that reaches the queries and keys is close to zero, and training has almost nothing to adjust them with. The paper offers this as the likely explanation of an earlier result: without the scaling, dot-product attention did worse than additive attention, an older form that scores a query and a key with a small network, at large dkd_k (Britz et al., 2017). The paper does not measure the gradients itself.

  3. Softmax turns each row of scores into weights. Let z=(z1,…,zm)z=(z_1,\ldots,z_m) be one row of the scaled scores. The exponential eae^a, also written exp⁡(a)\exp(a), uses the constant e≈2.718e\approx2.718. Then softmax⁡(z)j=ezj/∑j′ezj′\operatorname{softmax}(z)_j=e^{z_j}/\sum_{j'}e^{z_{j'}}, where j′j' is just a second index name, so the sum runs over every key in the row. The weights are positive and each row sums to 1.

  4. Multiplying the n×mn\times m weights by the m×dvm\times d_v values sums away the key axis. Row ii of the n×dvn\times d_v output is a weighted average of the value rows, weighted by how well each key matched query ii.

One attention head drawn as grids of numbers, with three queries, four keys, key width two and value width three. Q, three by two, times K transposed, two by four, gives a three by four score table. Softmax keeps that shape and makes each row sum to one. The weights, three by four, times V, four by three, give a three by three output, and output row two is a weighted average of the value rows using weight row two.One attention head drawn as grids of numbers, with three queries, four keys, key width two and value width three. Q, three by two, times K transposed, two by four, gives a three by four score table. Softmax keeps that shape and makes each row sum to one. The weights, three by four, times V, four by three, give a three by three output, and output row two is a weighted average of the value rows using weight row two.

Count the squares in the figure: each product removes the axis its two grids share.

Check it with two numbers. Take one query and two keys whose scaled scores are (0,log⁡3)(0,\log3), chosen so that the exponentials come out as 1 and 3, and values v1=(2,0)v_1=(2,0) and v2=(0,4)v_2=(0,4). The figure works through it one operation per column:

A table with one row per key. Key 1: scaled score 0, exponential 1, weight 1/4, value (2, 0), weighted value (0.5, 0). Key 2: scaled score log 3, exponential 3, weight 3/4, value (0, 4), weighted value (0, 3). The exponentials sum to 4, the weights to 1, and the weighted values to the output (0.5, 3).A table with one row per key. Key 1: scaled score 0, exponential 1, weight 1/4, value (2, 0), weighted value (0.5, 0). Key 2: scaled score log 3, exponential 3, weight 3/4, value (0, 4), weighted value (0, 3). The exponentials sum to 4, the weights to 1, and the weighted values to the output (0.5, 3).

Attention blended both values; it did not pick the better-matching token.

Compare it with code. The NumPy function below implements one head. k.T is the transpose. axis=1 is the key axis, so each query’s row is normalized separately. The row maximum is subtracted before np.exp: adding the same number to every score in a row cancels in the softmax ratio, so the result is unchanged, but large scores no longer overflow. The optional mask sets blocked scores to −∞-\infty, which makes their weights exactly zero. A decoder uses such a mask to stop each token from attending to later tokens (§3.2.3 of the paper).

Save the block as attention_example.py and run uv run --with numpy python attention_example.py. The checks pass silently.

import numpy as np

def attention(q, k, v, allowed=None):
    """One head. q: [n, dk], k: [m, dk], v: [m, dv], allowed: bool [n, m]."""
    scores = q @ k.T / np.sqrt(q.shape[1])  # [n, m]
    if allowed is not None:
        if not allowed.any(axis=1).all():
            raise ValueError("every query needs at least one allowed key")
        scores = np.where(allowed, scores, -np.inf)
    scores = scores - scores.max(axis=1, keepdims=True)
    weights = np.exp(scores)
    weights = weights / weights.sum(axis=1, keepdims=True)  # rows sum to 1
    return weights @ v, weights  # [n, dv], [n, m]

# The two-key example from the text.
out, w = attention(
    np.array([[1.0]]),
    np.array([[0.0], [np.log(3.0)]]),
    np.array([[2.0, 0.0], [0.0, 4.0]]),
)
np.testing.assert_allclose(w, [[0.25, 0.75]])
np.testing.assert_allclose(out, [[0.5, 3.0]])

# A causal mask: query i may attend only to keys 0..i.
x = np.random.default_rng(0).normal(size=(3, 4))
out, w = attention(x, x, x, allowed=np.tril(np.ones((3, 3), dtype=bool)))
assert out.shape == (3, 4)
np.testing.assert_allclose(w.sum(axis=1), 1.0)
assert np.all(w[np.triu_indices(3, k=1)] == 0)

A query whose keys are all blocked is a case the equation leaves open: every weight in its row would be 0/00/0. The function raises an error instead of returning NaN.

From one head to several. The base Transformer runs eight heads in parallel, each with its own learned matrices for producing QQ, KK and VV, and each with dk=dv=64d_k=d_v=64. It concatenates their outputs and multiplies the result by another learned matrix, WOW^O (Attention Is All You Need, §3.2.2).

An implementation can also process a batch: several input sequences together. For example, PyTorch’s scaled dot-product attention accepts a query tensor Q with shape [batch, heads, n, d_k]. The first two dimensions select a sequence and a head; Q[b, h] is the [n, d_k] matrix for that pair. The attention formula applies separately to each pair. The NumPy function here handles only one such pair: its .T and axis=1 operations assume two-dimensional inputs.

Six questions for any equation

QuestionAnswer for attention
What does the equation return, and with what shape?An n×dvn\times d_v matrix: one output row per query
Is each symbol data, a trained weight, a frozen model, a setting or a sample?QQ, KK and VV are computed from tokens by learned matrices; dkd_k is a fixed setting; nothing is sampled
Over which index or axis does each operation run?Softmax runs over the mm keys in each query’s row; the product of the weights with VV sums over keys
Where are the definitions?The paragraph before equation (1), footnote 4, and §3.2.2 for the learned projections
What does a check with two or three numbers give?Weights (1/4,3/4)(1/4,3/4) and output (0.5,3)(0.5,3)
What did the code have to decide that the equation leaves open?Subtracting the row maximum, the value used for masked scores, a row with no allowed key

What kind of statement an equation makes

Attention is a computation: it says how to get an output from inputs. Papers also write equations that do other jobs:

KindExample in this seriesWhat to check
ComputationThe attention output; MLA’s compressed vectorThe shape of every intermediate result
DefinitionGRPO’s score relative to other answersWhat the new name stands for, so you can substitute it back
Objective: a loss to minimize or a score to maximizeThe DPO lossWhether it is minimized or maximized, and which data it averages
Update ruleGradient descent; Gated DeltaNet’s memoryWhat changes at each step and what stays fixed
Constraint, or a set of allowed valuesmHC’s allowed mixing matricesHow the paper produces a value that satisfies it
Bound: an upper or lower limit on a quantityThe evidence lower bound (ELBO)The difference between the two sides, and when it is zero
Estimator or metricpass@kWhat is counted, and from how many samples
Empirical fitDeepSeek LLM’s scaling lawThe range of data the curve was fitted on

A constraint states a property the result must have. For attention weights, that property is: every weight is nonnegative and each row sums to 1. Softmax is a computation that produces weights with that property. The requirement alone does not tell you to use softmax.

== asserts that two expressions are equal. :=:= means “is defined as”: it gives a name to an expression. A definition can name a metric, a loss or a set of allowed values, so seeing :=:= does not tell you which kind of equation in the table above you are reading.

For example, Evaluating Large Language Models Trained on Code, the paper that introduced the Codex code-generation model, uses :=:= to define its estimator for pass@k (equation 1). This metric measures the chance that at least one of kk generated programs passes the tests. In the DeepSeek-V4 technical report, equation (2) combines two statements: M:={…}\mathcal M:=\{\ldots\} defines a set of allowed matrices, and Bl∈MB_l\in\mathcal M requires the model’s mixing matrix BlB_l to belong to that set. The definition uses :=:=; the constraint uses ∈\in, meaning “belongs to”. The pass@k and mHC sections work through those examples.

Finding the new equation, its definitions and its code

A paper’s methods section describes how its model or training algorithm works. The heading may be “Method”, “Architecture” or something more specific. Authors often explain an existing method first, then show what they changed. To identify the claimed contribution, start with the introduction’s summary of what is new. For example, DeepSeekMath, §1.1 lists Group Relative Policy Optimization (GRPO), its method for training models from scored answers. Section and equation numbers here refer to the linked paper.

Then compare the proposed method with the earlier method it changes. Two papers illustrate this:

  • An architecture change. DeepSeek-V2 describes standard multi-head attention in §2.1.1 and introduces multi-head latent attention (MLA) in §2.1.2. Standard attention stores every earlier token’s keys and values. MLA stores a compressed vector from which they can be reconstructed. Comparing those equations reveals what the model stores differently; the MLA walkthrough derives the memory saving.
  • A training change. DeepSeekMath, §4.1.1 prints the objective of Proximal Policy Optimization (PPO) as equation (1) and GRPO as equation (3). Both use an advantage: a number that says whether an answer was better or worse than expected. PPO estimates it with a second learned network, the value model, which predicts the reward still to come from a partial answer. GRPO instead compares the answer’s reward with rewards for other answers to the same question. The GRPO walkthrough compares these terms using the whole-answer notation from DeepSeek-R1.

Find the definitions around the equation. Check the preceding paragraph, any “where …” sentence after it, footnotes and appendices. In Attention Is All You Need, the paragraph before equation (1) defines the dimensions, and footnote 4 explains the scale factor. DeepSeek-V3 defines most of its routing symbols right after equation (15), and the bias bib_i just before equation (16). DeepSeek-V2 develops MLA across equations (9)–(19), then collects the computation in Appendix C.

Check the algorithm and code. An algorithm box is a numbered pseudocode listing that gives the order of operations. DeepSeekMath’s Algorithm 1 shows when to generate answers and when to update the model. Algorithm 1 in Denoising Diffusion Probabilistic Models (DDPM) specifies how to sample the training image, noise level and noise. Implementations settle further details: by default, np.std divides the sum of squared deviations by nn, while torch.std divides by n−1n-1. The GRPO example shows how that choice changes the advantage values computed from the same rewards.

arXiv versions can move sections and repeat equations under new numbers, so cite the version. In DeepSeek-R1 v1, the GRPO objective is §2.2.1, equations (1)–(3). In v2, posted in January 2026, it is §2.1, and the same equations reappear as (11)–(13) in Supplementary A.3. A link without a version opens the latest one, so every arXiv link in this series includes the version it was checked against.

Checking your reading with an LLM

A chat model can draft the symbol table, the index of every sum and a small-number check, if you give it the definitions and ask it to flag what is missing. Text copied from a PDF flattens subscripts, superscripts and fractions into one line; the “HTML (experimental)” and “TeX Source” links on the arXiv abstract page give clean text to paste. Paste the equation and the paragraphs around it with a prompt like this:

Below is equation (N) from <paper title, arXiv ID and version>, followed by
the paragraphs that define its symbols.

1. Make a table with one row per symbol: shape or type, meaning, and whether
   it is input data, a trained weight, a frozen model, a fixed setting or a
   random sample. Quote the sentence that defines it.
2. List every symbol the pasted text does not define. Do not guess them.
3. For every sum, mean, softmax, min or expectation, name the index or the
   distribution it runs over.
4. Work through the equation with the smallest numbers that use every term.
5. Say which kind of statement it is: a computation, definition, objective,
   update rule, constraint, bound, estimator or empirical fit.

Without step 2, nothing stops the model from filling a missing definition with the letter’s usual meaning, such as reading σ\sigma in DPO as a standard deviation instead of the sigmoid. The quotes from step 1 make the table checkable: search the PDF for each one, and treat a row whose quote you cannot find as a guess.

The same procedure as agent skills. paper-math-skills packages this section and the notation reference below as two skills written for Claude Code; other agents that load SKILL.md files can use them too. read-paper-math fetches the pinned arXiv version, quotes the sentence that defines each symbol, reads the equation from the inside out and runs a small-number check. check-paper-math reviews such a reading against the paper: it searches for every quote, re-runs the numbers and flags claims stronger or weaker than the paper’s. paper-math-readings has the skills’ readings for Parts 2–4, one for each of the 15 sections with a Source: line.

Notation reference

If a Greek letter is unfamiliar, open this article’s Greek-letter reference (Appendix A) for its name and common meanings. For more practice with the mathematics, Stanford CS229 provides probability and linear algebra reviews with exercises; Dive into Deep Learning’s preliminaries explain the foundations with code.

Subscripts, marks and relation signs

Letters are local variable names: each paper defines its own. Subscripts are usually indices. xix_i may be coordinate ii of a vector or example ii in a dataset, and hth_t is the model’s vector for token tt, called its hidden state.

Superscripts in model papers are often labels. In ht(ℓ)h_t^{(\ell)}, the superscript in parentheses is usually a layer number, not a power; in DeepSeek-V3’s FFN⁡i(s)\operatorname{FFN}^{(s)}_i and FFN⁡i(r)\operatorname{FFN}^{(r)}_i it marks shared and routed experts, the ones every token uses and the ones a router picks (see the MoE routing example). In DeepSeek-V2, WDKVW^{DKV} and ktCk_t^C carry labels, not exponents; the MLA example defines those labels. W⊤W^\top is a transpose and x2x^2 is a square.

x1:Tx_{1:T} means positions 1 through TT, including TT, unlike a Python slice; papers usually count from 1. x<tx_{<t} means every position before tt. Xt,:X_{t,:} selects row tt, as in NumPy slicing.

Marks on a letter usually change its meaning in one of these ways:

MarkUsual readingExample or exception
y^\hat yA prediction or an estimateExample: A^i,t\hat A_{i,t} in DeepSeekMath estimates how much better an answer scored than expected
xˉ\bar xA meanException: in DDPM, αˉt\bar\alpha_t multiplies the noise schedule’s factors from step 1 through tt
x~\tilde xA perturbed or unconstrained versionExample: in DeepSeek-V4, B~l\tilde B_l is a matrix before normalization enforces its constraints
x∗x^\astThe optimumException: in DPO, r∗r^\ast is the true reward, which the method never observes
x′x'A new value or an intermediateExample: in DeepSeek-V3, gi,t′g'_{i,t} is an expert weight before normalization
A−1A^{-1}The matrix inverseNot the entrywise reciprocal: A−1A^{-1} undoes AA, A−1A=IA^{-1}A=I (the identity matrix), and (A−1)ij≠1/Aij(A^{-1})_{ij}\neq1/A_{ij} in general

Some symbols other than Greek letters also have several jobs:

SymbolMeanings
∣\midConditioning in p(y∣x)p(y\mid x); “such that” inside a set
∣x∣\vert x\vertAn absolute value; the length of a sequence, as in ∣oi∣\vert o_i\vert, the token count of GRPO’s answer oio_i; the size of a set
∼\sim”Is sampled from” in x∼px\sim p; “roughly” in informal text
TTA sequence length; a softmax temperature; the number of diffusion steps
qqA query vector (attention); a question (GRPO); the student model qθq_\theta (distillation); the encoder qϕq_\phi (ELBO)

Five signs say how two sides relate. :=:=, sometimes ≜\triangleq, defines a new name. ≈\approx marks an approximation, such as the sampled average in Expectations and where the samples come from. ∝\propto means “proportional to”, with a normalizing constant left out: pi∝ezip_i\propto e^{z_i} becomes a distribution only after dividing by ∑jezj\sum_j e^{z_j}. ≪\ll means “much smaller than”, as in DeepSeek-V2’s dc≪dhnhd_c\ll d_hn_h: the compressed width is much smaller than the total width of all heads. ←\leftarrow is an assignment, as in an update rule.

Sums, counts, intervals and logarithms

The large ∑\sum adds terms and ∏\prod multiplies them. The index below each operator starts at 1 here and runs through the upper limit NN:

∑i=1Nxi=x1+⋯+xN,∏i=1Nxi=x1⋯xN.\sum_{i=1}^{N}x_i=x_1+\cdots+x_N,\qquad\prod_{i=1}^{N}x_i=x_1\cdots x_N.

The index belongs to the operator, as a loop variable belongs to its loop. In yi=∑j=1dWijxjy_i=\sum_{j=1}^{d}W_{ij}x_j, the sum runs over jj, while ii identifies an output entry. The result is a vector with one entry per ii: the matrix-vector product WxWx written out. The indices on the left-hand side tell you the shape of the output.

The factor in front of a sum decides what gets equal weight. A batch with a 2-token answer and an 8-token answer, where ℓit\ell_{it} is the loss on token tt of answer ii (in GRPO, ℓ\ell is a term to maximize instead), can be averaged in two ways:

Lanswers=12(12∑t=12ℓ1t+18∑t=18ℓ2t)Ltokens=110(∑t=12ℓ1t+∑t=18ℓ2t)\begin{aligned} L_{\text{answers}}&=\frac12\left(\frac12\sum_{t=1}^{2}\ell_{1t}+\frac18\sum_{t=1}^{8}\ell_{2t}\right)\\ L_{\text{tokens}}&=\frac1{10}\left(\sum_{t=1}^{2}\ell_{1t}+\sum_{t=1}^{8}\ell_{2t}\right) \end{aligned}

In the first, each answer gets weight 12\tfrac12, shared among its tokens:

short answer, each token:12×12=14long answer, each token:12×18=116\begin{aligned} \text{short answer, each token:}&\quad\tfrac12\times\tfrac12=\tfrac14\\ \text{long answer, each token:}&\quad\tfrac12\times\tfrac18=\tfrac1{16} \end{aligned}

In the second, every token has weight 1/101/10. GRPO samples GG answers o1,…,oGo_1,\ldots,o_G to each question, and ∣oi∣\vert o_i\vert is the number of tokens in answer ii. The two averages then read as follows, for DeepSeekMath’s GRPO and for DAPO, a later variant of GRPO:

DeepSeekMath’s GRPO, per answer:1G∑i=1G1∣oi∣∑t=1∣oi∣ℓitDAPO, per token:1∑i∣oi∣∑i=1G∑t=1∣oi∣ℓit\begin{aligned} \text{DeepSeekMath's GRPO, per answer:}&\quad\frac1G\sum_{i=1}^{G}\frac1{\vert o_i\vert}\sum_{t=1}^{\vert o_i\vert}\ell_{it}\\ \text{DAPO, per token:}&\quad\frac1{\sum_i\vert o_i\vert}\sum_{i=1}^{G}\sum_{t=1}^{\vert o_i\vert}\ell_{it} \end{aligned}

With G=2G=2, these are LanswersL_{\text{answers}} and LtokensL_{\text{tokens}} above. DAPO switched to the per-token average (§3.3) because the per-answer average gave the tokens of long answers too little weight: the model learned too little from long good answers and did not penalize long, repetitive bad ones enough.

A sum can also count. Papers do this with an indicator: a bold one followed by a condition, 1[C]\mathbf 1[C], which equals 1 when the condition CC is true and 0 when it is false. Some papers put the condition in parentheses or print a double-struck one instead; the meaning is the same. Adding up indicators therefore counts how many times the condition holds. Accuracy is the usual example. If y^i\hat y_i is the predicted class and yiy_i the correct class for example ii, then ∑i1[y^i=yi]\sum_i\mathbf 1[\hat y_i=y_i] is the number of correct predictions. Predictions (cat, dog, dog) against correct labels (cat, cat, dog) give the indicators 1, 0 and 1, so the count is 2 and the accuracy 2/3. In a mixture-of-experts (MoE) layer, a router sends each token to a few of many feed-forward sub-networks, called experts. In DeepSeek-V3’s balance loss (equation 18), the indicator is 1 when an expert’s score for a token is among the KrK_r highest scores for that token, where KrK_r is how many experts each token is routed to. Its sum over the tokens of a sequence counts how often that happened. The score here leaves out the bias that routing adds, so the count can differ from the experts the router actually picks (MoE routing).

The binomial coefficient (nk)\binom nk, read ”nn choose kk”, counts the ways to choose kk distinct items from nn without regard to order. For integers 0≤k≤n0\leq k\leq n, it equals n!/(k! (n−k)!)n!/(k!\,(n-k)!). The exclamation mark means factorial: n!=1×2×⋯×nn!=1\times2\times\cdots\times n, with 0!=10!=1. For example, (52)=5!/(2! 3!)=10\binom52=5!/(2!\,3!)=10: five items have ten distinct pairs. DeepSeekMoE uses binomial coefficients to count expert combinations, and the pass@k estimator uses them to count sets of samples.

Intervals use brackets for included ends: [a,b][a,b] includes both, (a,b)(a,b) neither. In Gated DeltaNet, αt∈(0,1)\alpha_t\in(0,1) means strictly between 0 and 1. Elsewhere, (a,b)(a,b) is a pair.

The natural logarithm reverses exponentiation: log⁡(ea)=a\log(e^a)=a. Logarithms turn products into sums and ratios into differences: log⁡(ab)=log⁡a+log⁡b\log(ab)=\log a+\log b and log⁡(a/b)=log⁡a−log⁡b\log(a/b)=\log a-\log b, but log⁡(a+b)\log(a+b) does not split. That is why papers work with log-probabilities. The log of a product of token probabilities is a sum, and the log of a ratio of two models’ probabilities is a difference, the form used in the DPO and GRPO objectives. ML papers mean the natural log unless they say otherwise; the results are in nats, and base-2 logs give bits. For a probability p≤1p\leq1, −log⁡p≥0-\log p\geq0, and it grows without limit as pp approaches 0, so a confident wrong prediction is expensive.

Log-sum-exp means: exponentiate each score ziz_i, add the results, then take the logarithm. Computing log⁡∑iezi\log\sum_i e^{z_i} directly can overflow when a score is large. Instead, find the largest score and call it mm. The notation m=max⁡izim=\max_i z_i means “compare all entries ziz_i and take the largest one”; in NumPy, m = z.max().

Subtract mm from every score before exponentiating, then add it back after taking the logarithm:

log⁡∑iezi=m+log⁡∑iezi−m.\log\sum_i e^{z_i}=m+\log\sum_i e^{z_i-m}.

For z=(1000,1001)z=(1000,1001), the largest score is m=1001m=1001. The shifted scores are (−1,0)(-1,0), so the calculation becomes 1001+log⁡(e−1+1)≈1001.3131001+\log(e^{-1}+1)\approx1001.313. Neither exponential is larger than 1. The attention code uses the same subtraction before softmax; there the common factor cancels in the division, so nothing is added back.

Conditional probability and the probability of text

pθ(y∣x)p_\theta(y\mid x) is the probability that the model with parameters θ\theta assigns to output yy given input xx. The subscript names the parameters; some papers write p(y∣x;θ)p(y\mid x;\theta), where the semicolon also marks parameters rather than a condition. With a dot in place of the output, pθ(⋅∣x)p_\theta(\cdot\mid x) is the whole distribution over outputs rather than one number. RL papers write the same object as πθ(o∣q)\pi_\theta(o\mid q), the probability that the model writes answer oo to question qq, and call the model a policy.

Swapping the event and the condition gives a different number. Suppose 100 model responses: 60 are correct, 50 are valid JSON, and 40 are both. Then

P(correct∣valid JSON)=40/50=0.8,P(valid JSON∣correct)=40/60≈0.67.\begin{aligned} P(\text{correct}\mid\text{valid JSON})&=40/50=0.8,\\ P(\text{valid JSON}\mid\text{correct})&=40/60\approx0.67. \end{aligned}

Let AA mean “the response is correct” and BB mean “the response is valid JSON”. Conditional probability restricts the count to responses satisfying the condition: P(A∣B)=P(A∩B)/P(B)P(A\mid B)=P(A\cap B)/P(B), provided P(B)>0P(B)>0. The symbol ∩\cap means “both events happen”. Here the fraction is 0.4/0.5=0.80.4/0.5=0.8, the same as 40 correct responses among 50 valid-JSON responses.

Two events are independent when knowing that one happened does not change the probability of the other. That requires P(A∩B)=P(A)P(B)P(A\cap B)=P(A)P(B). In this sample, P(both)=0.4P(\text{both})=0.4, while P(correct)P(valid JSON)=0.6×0.5=0.3P(\text{correct})P(\text{valid JSON})=0.6\times0.5=0.3, so the observed proportions do not satisfy independence.

Bayes’ theorem, also called Bayes’ rule, relates the two directions of conditioning: P(A∣B)=P(B∣A)P(A)/P(B)P(A\mid B)=P(B\mid A)P(A)/P(B). It lets you compute the probability of AA given BB from the probability of BB given AA and the probabilities of the two events. The ELBO example uses it to find the probability of a hidden code given an observed image.

A language model scores a sequence one token at a time. By the chain rule of probability,

pθ(y1:T∣x)=∏t=1Tpθ(yt∣x,y<t)log⁡pθ(y1:T∣x)=∑t=1Tlog⁡pθ(yt∣x,y<t)\begin{aligned} p_\theta(y_{1:T}\mid x)&=\prod_{t=1}^{T}p_\theta(y_t\mid x,y_{<t})\\ \log p_\theta(y_{1:T}\mid x)&=\sum_{t=1}^{T}\log p_\theta(y_t\mid x,y_{<t}) \end{aligned}

Each factor conditions on every earlier token, so the formula does not assume tokens are independent. If three tokens have conditional probabilities 0.5, 0.2 and 0.1:

p=0.5×0.2×0.1=0.01log⁡p=log⁡0.5+log⁡0.2+log⁡0.1≈−0.693−1.609−2.303≈−4.61\begin{aligned} p&=0.5\times0.2\times0.1=0.01\\ \log p&=\log0.5+\log0.2+\log0.1\approx-0.693-1.609-2.303\approx-4.61 \end{aligned}

The usual training loss is the negative of this sum, divided by the length:

L(θ)=−1T∑t=1Tlog⁡pθ(yt∣x,y<t).\mathcal L(\theta)=-\frac1T\sum_{t=1}^{T}\log p_\theta(y_t\mid x,y_{<t}).

During training, the earlier tokens y<ty_{<t} come from the dataset. During generation, they are the model’s own earlier choices.

Expectations and where the samples come from

An expectation is a probability-weighted average:

Ex∼p[f(x)]=∑xp(x)f(x).\mathbb E_{x\sim p}[f(x)]=\sum_x p(x)f(x).

Read Ex∼p[f(x)]\mathbb E_{x\sim p}[f(x)] as “the average of f(x)f(x) when xx is drawn from pp”. The notation ∑x\sum_x sums over all possible discrete values of xx. Without a subscript, E[X]\mathbb E[X] averages a random variable XX over its own distribution: if XX is 1 with probability 0.75 and 3 with probability 0.25, then E[X]=1×0.75+3×0.25=1.5\mathbb E[X]=1\times0.75+3\times0.25=1.5.

When a variable has a density p(x)p(x), meaning probability per unit of xx, the weighted average is an integral, ∫f(x)p(x) dx\int f(x)p(x)\,dx. The dxdx identifies xx as the variable being integrated; with no limits written here, the integral covers its whole range. The density example explains probability per unit and shows an integral as an area under a curve.

Training code cannot sum over every possible input, so it samples and averages: Ex∼p[f(x)]≈1N∑i=1Nf(xi)\mathbb E_{x\sim p}[f(x)]\approx\frac1N\sum_{i=1}^{N}f(x_i), with each xix_i drawn independently from pp, which papers write as xi∼iidpx_i\overset{\text{iid}}{\sim}p. Papers call this a Monte Carlo estimate, and in code it is loss.mean() over a batch. The batch mean estimates the expectation only if the batch is drawn from the distribution in the E\mathbb E‘s subscript, so the subscript tells you how the training data is produced:

  • DPO averages over saved examples (x,yw,yl)∼D(x,y_w,y_l)\sim\mathcal D: a prompt, a preferred answer and a rejected answer. The answers are collected and labeled before this training stage; they may come from earlier model generation. At each training step, the model computes probabilities for those supplied answers and updates its weights. It does not sample fresh answers for that step.
  • GRPO in DeepSeek-R1: generate answers, then compare their rewards. Training draws a question from the dataset, generates several answers, and scores them with a reward function, such as checking a mathematical result or running unit tests. The update favors answers that scored above the group’s average. The notation q∼P(Q)q\sim P(Q) means “sample a question qq from the question distribution”. The notation {oi}∼πθold(O∣q)\{o_i\}\sim\pi_{\theta_{old}}(O\mid q) means “sample answers oio_i to that question from the model copy named πθold\pi_{\theta_{old}}”. The subscript old marks the copy that generated these answers; that copy stays fixed while the batch is used for updates. The GRPO walkthrough explains the reward comparison and updates.
  • On-policy distillation in MiniLLM and DeepSeek-V4: generate text, then learn from teacher probabilities. The model being trained is the student. It generates text; a frozen teacher supplies next-token probabilities for the same prefixes, and training adjusts the student’s probabilities toward the teacher’s. These probabilities provide the training signal, rather than GRPO’s reward score for an answer. MiniLLM writes student-sampled text as y∼qθy\sim q_\theta: yy is the text and qθq_\theta names the student model. DeepSeek-V4 calls its student πθ\pi_\theta and uses several specialist teachers. MiniLLM’s actual sampling procedure also mixes in tokens drawn from the teacher. The distillation walkthrough explains the objectives and that sampling distinction.

The order tells you what training optimizes. Suppose a model assigns probabilities 0.9 and 0.1 to the correct outputs of two equally weighted training examples. Averaging their log-probabilities means taking each log first, then averaging: np.log(probs).mean(). Taking the log of their average means np.log(probs.mean()). If XX is the probability assigned to a randomly chosen example’s correct output:

E[log⁡X]=12(log⁡0.9+log⁡0.1)≈−1.20log⁡E[X]=log⁡((0.9+0.1)/2)=log⁡0.5≈−0.69\begin{aligned} \mathbb E[\log X]&=\tfrac12(\log0.9+\log0.1)\approx-1.20\\ \log\mathbb E[X]&=\log\bigl((0.9+0.1)/2\bigr)=\log0.5\approx-0.69 \end{aligned}

Negating these scores gives losses of 1.20 and 0.69. A second model that assigns 0.5 to each correct output gets 0.69 under either calculation. Thus averaging probabilities before taking the log treats the two models as equally good, while the usual average negative log-probability penalizes the first model more for its low probability on the second correct output. When translating a loss into code, preserve the order of the log and the average.

Jensen’s inequality states the general relationship for positive XX: E[log⁡X]≤log⁡E[X]\mathbb E[\log X]\leq\log\mathbb E[X]. It also helps construct alternative training objectives. When a model’s data probability requires an expensive average over hidden variables, an average of log terms can provide a lower bound that is easier to estimate. The ELBO walkthrough explains that training problem; ELBO stands for evidence lower bound. Section 2.4 of Tianhua Chen’s The Little Book of Generative AI Foundations derives the bound using Jensen’s inequality.

Densities, variance and error bars

p(x)p(x) has two common meanings. For discrete outcomes such as tokens or classes, it gives the probability of outcome xx: a number from 0 to 1, with probabilities summing to 1 over all outcomes.

To understand the other meaning, suppose XX is chosen uniformly between 0 and 0.5. Equal-length intervals have equal probabilities. The interval from 0.1 to 0.2 occupies one fifth of the whole range, so

P(0.1≤X≤0.2)=0.2−0.10.5=0.2.P(0.1\leq X\leq0.2)=\frac{0.2-0.1}{0.5}=0.2.

Within this range, probability is the interval’s width multiplied by 2. That multiplier is the probability density: p(x)=2p(x)=2 for 0≤x≤0.50\leq x\leq0.5, and zero outside. Density describes probability per unit of the variable, not the probability of one exact value.

Zero probability for a point does not mean nothing is sampled. Narrow an interval around 0.15: its probability is twice its width, so it approaches zero as the width approaches zero. The single exact point therefore has probability zero. A draw still produces some value in [0,0.5][0,0.5], and that whole interval has probability 1. If you record the result rounded to two decimal places, a recorded value of 0.15 represents the interval from 0.145 to 0.155, whose probability is 2×0.01=0.022\times0.01=0.02.

For a nonuniform density, the multiplier varies with xx. The integral adds the contributions across the interval:

P(a≤X≤b)=∫abp(x) dx.P(a\leq X\leq b)=\int_a^bp(x)\,dx.

Geometrically, this is the area under the density curve between aa and bb; the area over the whole range is 1. For the uniform example, the area is simply height 2 times width 0.5. A density can therefore exceed 1, and its log can be positive, as log⁡2≈0.69\log2\approx0.69 is here. A probability never exceeds 1.

The Gaussian distribution used for noise in DDPM has a density of this kind. Not every continuous distribution has an ordinary density: the Cantor distribution is a mathematical counterexample, outside the models discussed here. Real-valued storage does not imply a continuous distribution either: a variable restricted to 0.0 and 1.0 still has two discrete outcomes.

Papers often use the same letter for probabilities and densities. Check how the paper defines the variable’s distribution and which variable is summed or integrated. An integral over a hidden variable zz, such as the latent code in Part 4’s ELBO, does not tell you whether an observed xx is discrete or continuous. Some papers write capital PP for probabilities and lowercase pp for densities, but many use pp for both.

To describe how much a distribution spreads around its mean, papers use variance: the average squared difference from the mean, Var⁡(X)=E[(X−μ)2]\operatorname{Var}(X)=\mathbb E[(X-\mu)^2], where μ=E[X]\mu=\mathbb E[X]. The standard deviation is its square root, so it has the same units as XX.

These quantities also appear in distribution names. The Gaussian distribution, also called the normal distribution, is written N(μ,σ2)\mathcal N(\mu,\sigma^2): μ\mu is its mean and σ2\sigma^2 its variance. For a vector, N(μ,Σ)\mathcal N(\mu,\Sigma) uses a covariance matrix Σ\Sigma: entry (i,j)(i,j) measures how coordinates ii and jj vary together, and the diagonal holds their variances. N(0,I)\mathcal N(0,I) describes a vector of independent standard normal numbers, each with mean 0 and variance 1; II is the identity matrix.

Benchmark tables often report an average score together with a measure of variation. The spread of individual runs differs from the uncertainty of their average: for NN independent runs with standard deviation σ\sigma, the standard error of the mean is σ/N\sigma/\sqrt N.

Before comparing two entries such as 82.3±0.482.3\pm0.4 and 81.5±0.481.5\pm0.4, find in the caption whether 0.4 is a standard deviation across runs, a standard error or the half-width of a confidence interval. To compare the means, compute an interval for their difference. A 95% confidence-interval procedure produces ranges that contain the true difference in 95% of repeated experiments under its assumptions.

For this example, assume four independent runs per model, approximately normal run scores, and equal population variances. If the runs are paired, such as two models evaluated on the same independently sampled tasks, analyze the differences within pairs instead. NIST’s two-sample guide explains these cases.

For independent means, the variance of their difference is the sum of their variances. A standard normal variable falls between −1.96-1.96 and 1.961.96 with probability about 0.95, which supplies the multiplier for a normal approximation to a 95% interval. If 0.4 is the standard deviation across four runs, that first calculation gives:

standard error of each mean=0.4/4=0.2standard error of the gap=0.22+0.22≈0.28gap=82.3−81.5=0.8normal approximation=0.8±1.96×0.28≈0.8±0.55=from 0.25 to 1.35\begin{aligned} \text{standard error of each mean}&=0.4/\sqrt4=0.2\\ \text{standard error of the gap}&=\sqrt{0.2^2+0.2^2}\approx0.28\\ \text{gap}&=82.3-81.5=0.8\\ \text{normal approximation}&=0.8\pm1.96\times0.28\approx0.8\pm0.55\\ &=\text{from }0.25\text{ to }1.35 \end{aligned}

That 1.96 multiplier treats the estimated spread as known. With only four runs per model, use Student’s t-distribution to account for uncertainty in the spread. Under the assumptions above, its degrees of freedom are 4+4−2=64+4-2=6 (eight runs minus two estimated means). scipy.stats.t.ppf(0.975, 6) gives about 2.447 instead of 1.96; 0.975 leaves 2.5% outside each end of a 95% interval. If the equal-variance assumption is unsuitable, use a Welch interval, whose degrees of freedom are computed differently.

Now consider the other reading of the caption: 0.4 is already each mean’s standard error, estimated from those four runs. Nothing is divided by 4\sqrt4, and the gap’s standard error is about 0.566. The t multiplier is still needed. The two readings give:

0.4 a standard deviation, t interval:0.8±2.4470.22+0.22≈0.8±0.69from 0.11 to 1.490.4 a standard error, t interval:0.8±2.4470.42+0.42≈0.8±1.38from −0.58 to 2.18\begin{aligned} \text{0.4 a standard deviation, t interval:}&\quad0.8\pm2.447\sqrt{0.2^2+0.2^2}\approx0.8\pm0.69\\ &\quad\text{from }0.11\text{ to }1.49\\ \text{0.4 a standard error, t interval:}&\quad0.8\pm2.447\sqrt{0.4^2+0.4^2}\approx0.8\pm1.38\\ &\quad\text{from }-0.58\text{ to }2.18 \end{aligned}

The figure compares the initial normal approximation with the two t intervals:

Three intervals for the same gap of 0.8, assuming four independent approximately normal runs per model and equal population variances. With 0.4 as a standard deviation, the normal approximation gives 0.25 to 1.35 and the t interval gives 0.11 to 1.49. With 0.4 as an estimated standard error, the t interval gives minus 0.58 to 2.18 and contains zero.Three intervals for the same gap of 0.8, assuming four independent approximately normal runs per model and equal population variances. With 0.4 as a standard deviation, the normal approximation gives 0.25 to 1.35 and the t interval gives 0.11 to 1.49. With 0.4 as an estimated standard error, the t interval gives minus 0.58 to 2.18 and contains zero.

When 0.4 is the standard deviation, the t interval excludes zero: under these assumptions, the results support a positive difference. When 0.4 is the estimated standard error, the interval contains zero, so the results do not establish which model has the higher mean score.

Cross-entropy and KL divergence

During training, a model needs a numerical loss that measures how well its predicted probabilities agree with the training target. The training algorithm changes the model’s parameters to reduce that loss. Cross-entropy supplies such a loss for labeled examples or a teacher model’s probabilities. Kullback–Leibler (KL) divergence measures the mismatch between two distributions. Papers use it to train a student to imitate a teacher or to penalize changes from a fixed reference model.

Here the outcomes are discrete, such as tokens or classes. Write the target distribution as pp and the model’s predicted distribution over the same outcomes as qq. Start with one observed outcome ii: when the model gave it probability qiq_i, its loss is −log⁡qi-\log q_i. It is 0 when qi=1q_i=1, about 0.69 when qi=0.5q_i=0.5, about 2.3 when qi=0.1q_i=0.1, and infinite when qi=0q_i=0.

Cross-entropy averages that loss over outcomes drawn from the target:

H(p,q)=Ei∼p[−log⁡qi]=−∑ipilog⁡qi.H(p,q)=\mathbb E_{i\sim p}[-\log q_i]=-\sum_i p_i\log q_i.

With a one-hot label pp, which is 1 on the correct class yy and 0 elsewhere, only the correct class counts, and H(p,q)=−log⁡qyH(p,q)=-\log q_y: the ordinary classification loss. PyTorch’s nn.CrossEntropyLoss computes this from raw model scores, called logits, and applies log-softmax internally; its input is not the probability vector qq. With a teacher model’s soft distribution as pp, every class counts in proportion to the teacher’s probability. Classical distillation trains a small model on a large model’s probabilities this way. For the target p=(0.9,0.1)p=(0.9,0.1), two models have these cross-entropies H(p,q)H(p,q):

q=(0.5,0.5):−0.9log⁡0.5−0.1log⁡0.5≈0.693q=(0.9,0.1):−0.9log⁡0.9−0.1log⁡0.1≈0.095+0.230=0.325\begin{aligned} q=(0.5,0.5):&\quad -0.9\log0.5-0.1\log0.5\approx0.693\\ q=(0.9,0.1):&\quad -0.9\log0.9-0.1\log0.1\approx0.095+0.230=0.325 \end{aligned}

The second model matches the target, and no model can do better. That minimum, 0.325 here, is H(p)=−∑ipilog⁡piH(p)=-\sum_ip_i\log p_i, the entropy of pp. It is 0 only for a one-hot target: when the target itself is uncertain, some loss remains that no model can remove.

KL divergence subtracts that minimum and keeps only the loss caused by qq differing from pp. It is written with a double bar ∥\Vert, which only separates the two arguments; it is neither the conditional-probability bar ∣\mid from Conditional probability and the probability of text nor the length bars ∥x∥\Vert x\Vert of the vectors reference. Papers use it instead of a comma to mark that the order matters: the average runs over outcomes drawn from the first argument.

DKL(p ∥ q)=H(p,q)−H(p)=∑ipilog⁡piqi=Ei∼p[log⁡piqi].D_{\mathrm{KL}}(p\,\Vert\,q)=H(p,q)-H(p)=\sum_i p_i\log\frac{p_i}{q_i}=\mathbb E_{i\sim p}\Bigl[\log\frac{p_i}{q_i}\Bigr].

For the first model above, 0.693−0.325≈0.370.693-0.325\approx0.37. KL is 0 when the two distributions match and positive otherwise.

The order changes which mismatches are penalized. A term with pi>0p_i>0 and qi=0q_i=0 is infinite, so DKL(p∥q)D_{\mathrm{KL}}(p\Vert q) penalizes qq for assigning zero probability to anything pp can produce. Outcomes with pi=0p_i=0 add nothing (by convention 0log⁡0=00\log0=0), so they contribute no direct penalty even if qi>0q_i>0. Reversing the arguments gives DKL(q∥p)D_{\mathrm{KL}}(q\Vert p), which is infinite wherever qi>0q_i>0 and pi=0p_i=0. Outcomes with qi=0q_i=0 now add nothing, even if pi>0p_i>0. With pp as the target, DKL(p∥q)D_{\mathrm{KL}}(p\Vert q) is called the forward KL and DKL(q∥p)D_{\mathrm{KL}}(q\Vert p) the reverse KL.

For p=(0.5,0.5)p=(0.5,0.5) and q=(1,0)q=(1,0), the forward KL is infinite, because qq misses an outcome pp produces, while the reverse KL is only 1×log⁡(1/0.5)+0=log⁡21\times\log(1/0.5)+0=\log2: the outcome qq skips adds nothing. For p=(0.9,0.1)p=(0.9,0.1) and q=(0.5,0.5)q=(0.5,0.5), the forward KL is the 0.37 found above, computed here term by term, and the reverse KL differs:

DKL(p∥q)=0.9log⁡0.90.5+0.1log⁡0.10.5≈0.53−0.16=0.37DKL(q∥p)=0.5log⁡0.50.9+0.5log⁡0.50.1≈−0.29+0.80=0.51\begin{aligned} D_{\mathrm{KL}}(p\Vert q)&=0.9\log\tfrac{0.9}{0.5}+0.1\log\tfrac{0.1}{0.5}\approx0.53-0.16=0.37\\ D_{\mathrm{KL}}(q\Vert p)&=0.5\log\tfrac{0.5}{0.9}+0.5\log\tfrac{0.5}{0.1}\approx-0.29+0.80=0.51 \end{aligned}

This asymmetry is why KL is called a divergence rather than a distance.

Because H(p,q)=H(p)+DKL(p∥q)H(p,q)=H(p)+D_{\mathrm{KL}}(p\Vert q), and a fixed teacher’s entropy H(p)H(p) does not depend on the student, cross-entropy against a fixed teacher gives the student the same gradients as DKL(p∥q)D_{\mathrm{KL}}(p\Vert q). Changing a student parameter changes both losses by the same amount, so their derivatives used for training are equal; Gradients and optimization explains that calculation. This lets classification and classical distillation code use cross-entropy. The swap works only with the teacher first. With the student first, DKL(q∥p)=H(q,p)−H(q)D_{\mathrm{KL}}(q\Vert p)=H(q,p)-H(q), and the student’s own entropy H(q)H(q) changes as it trains, so the two no longer give the same gradients.

Vectors and matrices

Architecture equations describe calculations on arrays of numbers. An array’s shape tells you how its numbers are arranged, which operations are valid, and what those operations produce. A vector is an ordered list of numbers. A matrix arranges numbers in rows and columns. In ML code, tensor is the general term for these numerical arrays, including arrays with more than two axes. An axis is a dimension along which you index the array: a matrix has a row axis and a column axis.

A token’s hidden state is a vector of numbers computed inside the model to represent that token. Suppose we process a batch of BB sequences together, each with TT token positions, and each hidden state contains dd numbers. The hidden-state array has shape [B, T, d], which papers also write as B×T×dB\times T\times d. Its three axes select the sequence, the token position, and the number within that token’s vector. For example, [2, 3, 4] holds two sequences, three token vectors per sequence, and four numbers per vector: 24 numbers in total. Here dd is the vector’s width. The shape lists the three sizes; multiplying them gives the number of entries.

Papers often write shapes as set membership: a∈Rda\in\mathbb R^d means that aa is a vector of dd real numbers, and A∈Rm×nA\in\mathbb R^{m\times n} means that AA is a matrix with mm rows and nn columns. Bold letters sometimes mark vectors or tensors, but the paper’s definition determines the shape.

In the table below, aa and bb are column vectors: their numbers are arranged vertically. The superscript ⊤\top means transpose: exchange rows and columns. Thus a⊤a^\top is a row containing the same numbers as column aa. The capital AA and BB here name matrices; BB no longer means batch size.

ExpressionValues it usesWhat the operation doesResult
a⊤ba^\top b — dot productTwo column vectors, each with dd entriesMultiply corresponding entries, then add the products: ∑iaibi\sum_i a_i b_iOne number
ab⊤ab^\top — outer productA column aa with mm entries and a column bb with nn entriesMultiply every entry of aa by every entry of bbAn m×nm\times n matrix; entry (i,j)(i,j) is aibja_i b_j
ABAB — matrix productAA with mm rows and kk columns; BB with kk rows and nn columnsFor entry (i,j)(i,j), multiply corresponding numbers in row ii of AA and column jj of BB, then addAn m×nm\times n matrix; AA‘s column count must equal BB‘s row count
A⊙BA\odot B — elementwise productTwo arrays of the same shapeMultiply entries at matching positions, without adding themAn array of the same shape
[a;b][a;b] — concatenationColumns aa and bb with mm and nn entriesPlace the entries of bb after those of aaOne column with m+nm+n entries; check the paper’s convention for the joining axis

For a concrete comparison, take a=(12)a=\begin{pmatrix}1\\2\end{pmatrix} and b=(34)b=\begin{pmatrix}3\\4\end{pmatrix}. Moving the transpose changes both the calculation and the result:

a⊤b=1×3+2×4=11ab⊤=(1×31×42×32×4)=(3468).\begin{aligned} a^\top b&=1\times3+2\times4=11\\ ab^\top&=\begin{pmatrix}1\times3&1\times4\\2\times3&2\times4\end{pmatrix}=\begin{pmatrix}3&4\\6&8\end{pmatrix}. \end{aligned}

The dot product gives one score, as in the query–key comparison in attention. The outer product keeps a separate value for every pair of entries; the Gated DeltaNet update uses it to construct a matrix update from two vectors.

A matrix product can be regrouped, (AB)C=A(BC)(AB)C=A(BC), but not reordered; the MLA derivation uses the regrouping to skip rebuilding keys. NumPy writes matrix multiplication as @ and the elementwise product as *. Papers do not inherit NumPy’s broadcasting rules: adding a vector to a matrix needs a stated axis. Papers also differ on whether a vector is a row or a column: attention stacks tokens as the rows of QQ, while MLA, Gated DeltaNet and LoRA write WhWh with column vectors, and PyTorch’s nn.Linear computes x @ W.T on rows.

An architecture equation may also describe a vector’s size, restrict which matrices are allowed, or rearrange a product:

NotationMeaning
∥x∥2=∑ixi2\Vert x\Vert_2=\sqrt{\sum_i x_i^2}The Euclidean length; ∥x∥2\Vert x\Vert^2, without the root, appears in DDPM’s loss
∥x∥1=∑i∣xi∣\Vert x\Vert_1=\sum_i\vert x_i\vertThe sum of absolute values
∥A∥2\Vert A\Vert_2The spectral norm: the largest factor by which AA increases a vector’s length; mHC keeps it at most 1
rank⁡(A)\operatorname{rank}(A)The number of independent columns; LoRA’s update has rank at most rr
det⁡A\det AThe determinant: ∣det⁡A∣\vert\det A\vert is the factor by which AA scales volume, and the sign records whether AA flips orientation; the change-of-variables example in this article’s Appendix B uses it
A≥0A\geq0Every entry is nonnegative, as in mHC; A⪰0A\succeq0 is a different condition, positive semidefinite: x⊤Ax≥0x^\top Ax\geq0 for every xx
II, 1n\mathbf 1_nThe identity matrix (1 on its diagonal, 0 elsewhere, so Ix=xIx=x); a vector of nn ones
(AB)⊤=B⊤A⊤(AB)^\top=B^\top A^\topTransposing a product reverses the order; Part 2’s RoPE and MLA sections use it

Gradients and optimization

Training uses derivatives to decide how to change the model’s parameters. Let L\mathcal L be one scalar loss and θ\theta the vector of all parameters; θi\theta_i is one entry in that vector.

The partial derivative ∂L/∂θi\partial\mathcal L/\partial\theta_i is one number, evaluated at the current parameter values. It measures the loss’s rate of change when only θi\theta_i changes and the other parameters stay fixed. Read it as “the partial derivative of the loss with respect to parameter θi\theta_i”.

The gradient ∇θL\nabla_\theta\mathcal L collects those numbers for every parameter into one vector. Its iith entry is ∂L/∂θi\partial\mathcal L/\partial\theta_i. The symbol ∇\nabla is called nabla; here it means “take the gradient”. With only one parameter, the gradient has one entry equal to the ordinary derivative.

For example, take L(θ1,θ2)=θ12+3θ22\mathcal L(\theta_1,\theta_2)=\theta_1^2+3\theta_2^2. At θ1=2\theta_1=2 and θ2=1\theta_2=1:

∂L∂θ1=2θ1=4∂L∂θ2=6θ2=6∇θL=(46).\begin{aligned} \frac{\partial\mathcal L}{\partial\theta_1}&=2\theta_1=4\\ \frac{\partial\mathcal L}{\partial\theta_2}&=6\theta_2=6\\ \nabla_\theta\mathcal L&=\begin{pmatrix}4\\6\end{pmatrix}. \end{aligned}

The first partial derivative, 4, means that increasing θ1\theta_1 by 0.01 raises the loss by approximately 0.04 while θ2\theta_2 stays fixed. The gradient contains this information for both parameters. Gradient descent subtracts each parameter’s derivative, multiplied by a positive learning rate η\eta that controls the step size:

θ←θ−η∇θL,η>0.\theta\leftarrow\theta-\eta\nabla_\theta\mathcal L,\qquad\eta>0.

With η=0.1\eta=0.1, the example changes from (2,1)(2,1) to (1.6,0.4)(1.6,0.4), and the loss falls from 7 to 3.04. For a differentiable loss with a nonzero gradient, a sufficiently small step lowers the loss. A zero gradient gives no update.

The subscript on ∇\nabla says what varies. ∇θlog⁡pθ(x)\nabla_\theta\log p_\theta(x) varies the parameters; ∇xlog⁡pθ(x)\nabla_x\log p_\theta(x) varies the input, and diffusion papers call it the score, which has nothing to do with a benchmark score.

A Jacobian records derivatives for several outputs. A neural-network layer can produce many numbers, such as the components of a token’s hidden state. To describe how every output responds to every input, collect the partial derivatives into a matrix called the Jacobian. For y=f(x)y=f(x) with nn input numbers and mm output numbers, its shape is m×nm\times n: rows correspond to outputs, columns to inputs, and entry Jij=∂yi/∂xjJ_{ij}=\partial y_i/\partial x_j measures how output ii changes when input jj changes.

For example, let a function take two numbers and return y1=x1+2x2y_1=x_1+2x_2 and y2=3x1−x2y_2=3x_1-x_2. Its Jacobian is

J=(∂y1/∂x1∂y1/∂x2∂y2/∂x1∂y2/∂x2)=(123−1).\begin{aligned} J&=\begin{pmatrix} \partial y_1/\partial x_1 & \partial y_1/\partial x_2\\ \partial y_2/\partial x_1 & \partial y_2/\partial x_2 \end{pmatrix}\\ &=\begin{pmatrix}1&2\\3&-1\end{pmatrix}. \end{aligned}

The second column says that increasing x2x_2 by 0.1 while holding x1x_1 fixed increases y1y_1 by 0.2 and decreases y2y_2 by 0.1. This example is linear, so its Jacobian is constant. For a nonlinear function, the entries can depend on the current input and describe small changes locally. With just one scalar output, the Jacobian has one row: the same derivatives as the gradient, transposed under our column-vector convention. Deep Learning, §4.3, gives the general definitions.

Backpropagation uses these derivatives to compute the loss gradient through successive layers. The change-of-variables example in this article’s Appendix B uses a different property: the absolute value of a square Jacobian’s determinant gives the local volume scaling factor, which is needed to adjust a probability density.

For training, derivatives describe local changes; an optimization objective states what the updates should minimize or maximize. Papers distinguish the best value of an objective from the parameters that achieve it: min⁡θf(θ)\min_\theta f(\theta) is the smallest value of ff, while arg min⁡θf(θ)\operatorname*{arg\,min}_\theta f(\theta) gives the parameter values that achieve it. For f(θ)=(θ−3)2f(\theta)=(\theta-3)^2, the minimum is 0 and the argmin is 3. An argmin specifies the desired result, but leaves the update algorithm open.

For example, MiniLLM writes its goal as θ=arg min⁡θDKL(qθ∥p)\theta=\operatorname*{arg\,min}_\theta D_{\mathrm{KL}}(q_\theta\Vert p) (equation 1), where qθq_\theta is the student model and pp the teacher it learns from. Section 2.2 then derives a gradient and modifies it to make training more stable; equation (7) is the gradient used for updates. The on-policy distillation example explains those changes. Reading only the argmin would miss them.

A stop-gradient, sg⁡(x)\operatorname{sg}(x), passes xx forward unchanged but blocks gradients through it, like .detach() in PyTorch. Two expressions with the same forward value can train differently if one of them is detached. In the GRPO example, Hugging Face TRL treats the old model’s log-probability as fixed. In the distillation shortcut discussed by DeepSeek-V4, a detached teacher–student log-ratio supplies a fixed weight for the update.

Sets and constraints

A constraint states which values are allowed. Papers often express constraints using sets: collections of distinct members, written in braces, such as {1,2,3}\{1,2,3\}. Order does not matter, so {3,1,2}\{3,1,2\} names the same set. Repeated entries count only once. By comparison, the parentheses in a vector such as (1,2,3)(1,2,3) describe an ordered list: (3,1,2)(3,1,2) is a different vector.

Once a paper defines a set, it can test membership, combine sets, count their members or state a condition on them. Take A={1,2,3}A=\{1,2,3\} and B={3,4}B=\{3,4\}:

NotationMeaningExample and how to read it
x∈Ax\in AMembership: xx belongs to AA2∈A2\in A: 2 is a member of AA
A∪BA\cup BUnion: include every member of either setA∪B={1,2,3,4}A\cup B=\{1,2,3,4\}; include 3 only once
A∩BA\cap BIntersection: keep only members shared by both setsA∩B={3}A\cap B=\{3\}
∣A∣\vert A\vertThe number of distinct members∣A∣=3\vert A\vert=3
∀\forall”For every”: a condition must hold for all the named members∀x∈A: x>0\forall x\in A:\ x>0: every member of AA is positive
∃\exists”There exists”: at least one member must satisfy the condition∃x∈A: x>2\exists x\in A:\ x>2: AA has a member greater than 2, namely 3

The shape notation from Vectors and matrices also names sets: Rd\mathbb R^d is the set of all vectors of dd real numbers, and Rn×d\mathbb R^{n\times d} the set of all real matrices with nn rows and dd columns. Thus Q∈Rn×dkQ\in\mathbb R^{n\times d_k} specifies which shape QQ must have.

Set-builder notation describes a set by a condition: {x∈S∣condition}\{x\in S\mid\text{condition}\} reads “the members of SS that satisfy the condition”, like the Python set comprehension {x for x in S if condition(x)}. The bar means “such that”, not conditional probability; some papers use a colon instead. Examples in this series include mHC’s allowed matrices, MoE’s selected experts and sparse attention’s selected tokens.

DAPO, a training method that filters groups of generated answers, keeps a question only when some answers are correct and some are wrong. For GG sampled answers o1,…,oGo_1,\ldots,o_G and reference answer aa, write the set of correct answer indices as

C={i∈{1,…,G}∣is_equivalent⁡(a,oi)}.C=\{i\in\{1,\ldots,G\}\mid\operatorname{is\_equivalent}(a,o_i)\}.

The filter is 0<∣C∣<G0<\vert C\vert<G. Using indices makes the counting explicit: two samples with identical text still count as two answers. DAPO’s paper writes the set over the answers oio_i instead; read literally as a set of texts, that form counts two identical answers once.

Exercises

  1. Shapes. QQ is 4×84\times8, KK is 6×86\times8 and VV is 6×36\times3. What are the shapes of the scores and of the output? Over which axis does softmax run?
  2. Softmax. Compute the softmax of (0,log⁡4)(0,\log4). Does adding 100 to both inputs change the result?
  3. Averages. One answer has a single token with loss 4; another has three tokens with loss 0. Compute the per-token average and the per-answer average.
  4. Conditioning. Of 200 responses, 120 are correct, 80 pass format validation and 60 do both. Find P(correct∣valid)P(\text{correct}\mid\text{valid}) and P(valid∣correct)P(\text{valid}\mid\text{correct}).
  5. KL. For a teacher p=(1,0)p=(1,0) and a student q=(0.5,0.5)q=(0.5,0.5), compute both KL directions.
  6. Sets. DAPO keeps a question only if 0<∣C∣<G0<\vert C\vert<G, where CC contains the indices of correct answers among GG samples. With G=4G=4, does it keep a question whose answers score (1,1,1,1)(1,1,1,1)? One whose answers score (1,0,1,1)(1,0,1,1)? Does the first answer change if all four samples contain identical correct text?

Answers:

  1. The scores are 4×64\times6 and the output is 4×34\times3. Softmax runs across the six keys in each query’s row.

  2. (1/5,4/5)(1/5,4/5). Adding the same number to every input leaves softmax unchanged, but computing e100e^{100} directly overflows in 32-bit floats.

  3. The two averages:

    per token:(4+0+0+0)/4=1per answer:(4/1+0/3)/2=(4+0)/2=2\begin{aligned} \text{per token:}&\quad(4+0+0+0)/4=1\\ \text{per answer:}&\quad(4/1+0/3)/2=(4+0)/2=2 \end{aligned}
  4. 60/80=0.7560/80=0.75 and 60/120=0.560/120=0.5.

  5. DKL(p∥q)=log⁡2≈0.69D_{\mathrm{KL}}(p\Vert q)=\log2\approx0.69, and DKL(q∥p)=∞D_{\mathrm{KL}}(q\Vert p)=\infty, because the student puts probability on an outcome the teacher rules out.

  6. No: C={1,2,3,4}C=\{1,2,3,4\} has four members, which equals GG. Yes: C={1,3,4}C=\{1,3,4\} has three members, between 0 and 4. Identical text does not change the first answer: these are four separate samples, so their four indices still count.

Appendix A. Greek letters

The roles are common examples; each paper still defines what its symbols mean.

LetterNameCommon roles in ML papers
α\alphaalphaA mixing weight or scale; a decay (Gated DeltaNet); a noise schedule (DDPM)
β\betabetaA penalty strength (DPO, GRPO); a writing strength (Gated DeltaNet); a noise schedule (DDPM)
γ\gammagammaA discount factor in RL; a step size (the bias update in DeepSeek-V3)
δ,Δ\delta,\DeltadeltaA difference or a change
ϵ,ε\epsilon,\varepsilonepsilonNoise (DDPM); a clipping range (GRPO); a small stabilizer
η\etaetaThe learning rate
θ,Θ\theta,\ThetathetaModel parameters; RoPE’s rotation angles
λ,Λ\lambda,\LambdalambdaA regularization weight; an eigenvalue
μ\mumuA mean; the number of gradient steps per batch in DeepSeekMath’s Algorithm 1
π,Π\pi,\PipiA policy; ∏\prod is the product operator
ρ\rhorhoA probability ratio, as in Part 3’s GRPO section; a correlation
σ,Σ\sigma,\SigmasigmaThe sigmoid (DPO); a standard deviation; a covariance; ∑\sum is the sum operator
τ\tautauA temperature; a threshold; a trajectory in RL
ϕ,φ,Φ\phi,\varphi,\PhiphiThe parameters of a second network, such as an encoder; features; an angle
ψ,Ψ\psi,\PsipsiThe parameters of another network, such as the value model VψV_\psi in DeepSeekMath’s PPO
ω,Ω\omega,\OmegaomegaA frequency; Ω\Omega is also a lower bound in complexity, or a set of outcomes

Variants such as ϕ/φ\phi/\varphi and ϵ/ε\epsilon/\varepsilon are usually the same letter in a different font, but a paper can use both for different variables.

Appendix B. Other equation families

Equation forms this series does not work through, with the definitions each needs:

Selective state-space models. A state-space model processes a sequence by updating a stored state at each step. An update of the form ht=Aˉtht−1+Bˉtxth_t=\bar A_th_{t-1}+\bar B_tx_t, yt=Cthty_t=C_th_t combines the previous state with the current input, then computes an output. Here xtx_t is the current input, hth_t the stored state and yty_t the output. The matrices Aˉt\bar A_t, Bˉt\bar B_t and CtC_t respectively transform the previous state, add the input’s contribution and produce the output. The bars mark parameters converted from a continuous-time model to discrete steps; they do not mean averages. In Mamba, the update parameters depend on the current input, which is what “selective” means.

Stochastic differential equations. dx/dt=f(x,t)dx/dt=f(x,t) describes how a state xx changes with time tt: ff is its rate of change. A stochastic differential equation (SDE) adds random changes, dXt=f(Xt,t) dt+g(Xt,t) dWtdX_t=f(X_t,t)\,dt+g(X_t,t)\,dW_t. Here ff describes the deterministic change, gg sets the noise scale, and dWtdW_t is an increment of Brownian motion. To approximate it in code, the Euler–Maruyama method uses a small time step Δt\Delta t and replaces dWtdW_t with Gaussian noise of variance Δt\Delta t. Section 5.1 of Tianhua Chen’s The Little Book of Generative AI Foundations gives such an update; §6.4 of the same book uses SDEs to describe diffusion models.

Change of variables. Transforming a random variable changes its density according to how the transformation changes local volume. Suppose y=f(x)y=f(x) maps between spaces of the same dimension, and both ff and its inverse f−1f^{-1} are differentiable. The densities before and after the transformation, pXp_X and pYp_Y, satisfy pY(y)=pX(f−1(y)) ∣det⁡Jf−1(y)∣p_Y(y)=p_X\bigl(f^{-1}(y)\bigr)\,\bigl\vert\det J_{f^{-1}}(y)\bigr\vert. The inverse f−1f^{-1} recovers xx from yy. Its Jacobian Jf−1J_{f^{-1}} is the square matrix of first derivatives; the absolute value of its determinant corrects for the local change in volume. For example, if y=2xy=2x in one dimension, the density becomes pY(y)=pX(y/2)/2p_Y(y)=p_X(y/2)/2: doubling the width halves the density. Normalizing flows use invertible transformations like this to model densities; Tianhua Chen’s book, §7.1, explains the method.

Min–max objectives. In generative adversarial networks (GANs), a generator GG produces examples and a discriminator DD tries to distinguish them from real data. The objective V(D,G)V(D,G) measures the discriminator’s success: DD maximizes it while GG minimizes it. The goal min⁡Gmax⁡DV(D,G)\min_G\max_DV(D,G) (equation 1) says: for each possible generator, consider the best discriminator against it, then choose the generator with the smallest resulting objective. Training does not solve that inner maximization exactly. The paper’s Algorithm 1 alternates kk gradient-ascent steps on DD with one gradient-descent step on GG; its experiments used k=1k=1.

The probability simplex. A probability vector has nonnegative entries that add up to 1. The set of all such vectors with KK entries is called the probability simplex, written ΔK−1={p∈RK∣pi≥0, ∑ipi=1}\Delta^{K-1}=\{p\in\mathbb R^K\mid p_i\geq0,\ \sum_ip_i=1\}. Every softmax output lies in it. Here Δ\Delta names a set, and the superscript K−1K-1 is its dimension, not a power: once K−1K-1 probabilities are chosen, the last must make the sum equal 1. With two choices, every distribution has the form (a,1−a)(a,1-a) for 0≤a≤10\leq a\leq1, so only one number is free.

Normalization. Normalization rescales values by the mean and spread of a chosen group. A common form is x^=(x−μ)/σ2+ϵ\hat x=(x-\mu)/\sqrt{\sigma^2+\epsilon}, where μ\mu is a mean, σ2\sigma^2 a variance, and ϵ\epsilon a small positive number that prevents division by zero. The equation alone does not say which entries are used to compute the mean and variance. For a batch of feature vectors, batch normalization computes them separately for each feature across examples. A Transformer’s layer normalization computes them separately for each token across its features. Check the specified axes when comparing implementations.

Sources and versions

Section and equation numbers refer to the versions linked here.

  1. Tianhua Chen. The Little Book of Generative AI Foundations: An Intuitive Mathematical Primer. 2026. Version 2; §2.4 and §3.2 cover Jensen’s inequality and the ELBO, §5.1 and §6.4 continuous-time noise.
  2. Vaswani et al. Attention Is All You Need. 2017. Version 7, §3.2.1, equation (1), and footnote 4.
  3. Dai et al. DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models. 2024. Fine-grained expert segmentation and the combination counts, §3.1; ablation, §4.4 and Figure 3.
  4. Shao et al. DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models. 2024. Version 3, §1.1, §4.1.1, equations (1)–(4), and Algorithm 1.
  5. DeepSeek-AI. DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model. 2024. Version 5, §2.1.1–2.1.3, equations (9)–(19), and Appendix C.
  6. DeepSeek-AI. DeepSeek-V3 Technical Report. 2024–2025. Version 2, §2.1.2, equations (12)–(18).
  7. DeepSeek-AI. DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning. 2025. Version 1: §2.2.1, equations (1)–(3). Version 2, 2026: §2.1 and Supplementary A.3.
  8. DeepSeek-AI. DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence. 2026. Version 1: §2.2, equations (1)–(8); §5.1.2, equation (29).
  9. Rafailov et al. Direct Preference Optimization: Your Language Model is Secretly a Reward Model. 2023–2024. Version 3, §4, equation (7).
  10. Gu et al. MiniLLM: Knowledge Distillation of Large Language Models. 2023–2024. Version 4, §2.1, equation (1), and §2.2, equations (2) and (7).
  11. Yu et al. DAPO: An Open-Source LLM Reinforcement Learning System at Scale. 2025. Version 2, §3.2–3.3, equations (11)–(12).
  12. Gu and Dao. Mamba: Linear-Time Sequence Modeling with Selective State Spaces. 2023–2024.
  13. Yang et al. Gated Delta Networks: Improving Mamba2 with Delta Rule. 2024–2025. Version 3, §3.1, equation (10), and §3.3–3.4.
  14. Ho, Jain and Abbeel. Denoising Diffusion Probabilistic Models. 2020. Version 2, §2, equations (4)–(5); §3.2, equation (12); §3.4, equation (14); and Algorithms 1–2.
  15. Goodfellow et al. Generative Adversarial Nets. 2014. Equation (1) and Algorithm 1.
  16. Chen et al. Evaluating Large Language Models Trained on Code. 2021. Version 2, §2.1, equation (1), and Figure 3.
  17. Hugging Face TRL. GRPOTrainer and GRPOConfig at commit c6eac19, October 2026.
  18. Stanford CS229. Probability Theory Review and Linear Algebra Review and Reference.
  19. Dive into Deep Learning. Preliminaries.
  20. Britz, Goldie, Luong and Le. Massive Exploration of Neural Machine Translation Architectures. 2017. Version 2, Table 5; cited by Attention Is All You Need for dot-product against additive attention.