The mathematics of language modeling
The chain rule, autoregressive factorization, and soft targets
This page does not reintroduce tokenization, the next-token distribution, or likelihood as foundational concepts: those have canonical lessons. It deepens two mathematical connections: the chain rule that justifies autoregressive factorization, and the relationship between soft-target cross-entropy and KL divergence.
By the end of this page, you will be able to: - derive autoregressive factorization from the probability chain rule; - distinguish a probabilistic identity from the parameterized model that approximates its conditionals; - briefly connect likelihood, log-likelihood, and the training objective; - derive the identity between cross-entropy, target entropy, and KL divergence; - state the assumptions, direction, and cases in which these quantities become infinite.
Practice: Mathematical foundations exercises for loss, soft-target and KL calculations.
1. From the chain rule to autoregressive factorization
The output probabilities lesson defines the conditional probability of the next token, \(P(x_t\mid x_{<t})\), and explains how the model constructs its distribution. Here, we use that quantity to derive the probability of a complete sequence.
For any joint distribution, the probability chain rule gives:
\[ P(x_1,\ldots,x_T) =P(x_1)P(x_2\mid x_1)\cdots P(x_T\mid x_1,\ldots,x_{T-1}). \]
Writing \(x_{<t}=(x_1,\ldots,x_{t-1})\), we obtain:
\[ \boxed{ P(x_{1:T})=\prod_{t=1}^{T}P(x_t\mid x_{<t}) } \]
This is the autoregressive factorization: the sequence probability is the product of the conditional probabilities of its tokens, in order.
The chain rule is a probabilistic identity, valid for any joint distribution. It does not by itself impose an architecture or a particular computation order. The autoregressive aspect comes from the model that represents and uses the conditionals in prefix order: at position \(t\), the token is predicted from preceding tokens, not future tokens.
For the first token, the prefix is empty. In practice, a beginning-of-sequence token (BOS) may be explicit, or an equivalent convention may be used.
2. From a parameterized model to the training objective
A model with parameters \(\theta\) approximates the conditionals:
\[ P_\theta(x_t\mid x_{<t}). \]
The factorization then implies:
\[ P_\theta(x_{1:T}) =\prod_{t=1}^{T}P_\theta(x_t\mid x_{<t}), \qquad \log P_\theta(x_{1:T}) =\sum_{t=1}^{T}\log P_\theta(x_t\mid x_{<t}). \]
Maximum likelihood seeks to increase the log-likelihood of observed sequences; its minimized form is negative log-likelihood (NLL). This equivalence does not determine reduction over tokens and examples, or how padding and ignored positions are handled. Those conventions belong to the canonical lessons on likelihood, cross-entropy, and aggregated loss.
Notation bridge. Probabilistic lessons often use \(P\) for an event probability or conditional distribution. Computational lessons use \(p_{b,t,v}\) for component \(v\) of the probability vector at example \(b\) and position \(t\). The target ID \(y_{b,t}\) selects \(p_{b,t,y_{b,t}}\). These are compatible levels of description, not different probabilistic objects.
3. Soft targets and KL divergence
One-hot targets place all mass on a single category. Some methods instead use a target distribution \(q\)—for example, label smoothing or a distribution supplied by a teacher model—over the \(V\) tokens.
For a target distribution \(q\) and predicted distribution \(p\), cross-entropy is:
\[ H(q,p)=-\sum_{i=1}^{V}q_i\log p_i. \]
Terms with \(q_i=0\) contribute zero. With a one-hot target, the sum reduces to \(-\log p_y\); with a soft target, multiple categories contribute. Assume \(q_i\geq 0\), \(\sum_i q_i=1\), and that \(p\) is also normalized. Unless stated otherwise, \(\log\) is the natural logarithm, so losses are measured in nats; using \(\log_2\) gives bits.
Define target entropy as \(H(q)=-\sum_i q_i\log q_i\). The identity
\[ H(q,p)=H(q)+D_{\mathrm{KL}}(q\Vert p) \]
explains why, for a fixed target \(q\), minimizing cross-entropy with respect to \(p\) is equivalent to minimizing KL divergence toward that target. For finite quantities, the identity follows directly from the definitions:
\[ \begin{aligned} D_{\mathrm{KL}}(q\Vert p) &=\sum_i q_i\log\frac{q_i}{p_i}\\ &=\sum_i q_i\log q_i-\sum_i q_i\log p_i\\ &=-H(q)+H(q,p). \end{aligned} \]
Thus \(H(q,p)=H(q)+D_{\mathrm{KL}}(q\Vert p)\).
Under the usual conditions, \(D_{\mathrm{KL}}(q\Vert p)\geq 0\), with equality if and only if \(q=p\). This does not mean that the entropy of language is one universal constant: it depends on the distribution, context, corpus, and tokenization under consideration.
Here, \(q\) and \(p\) are normalized distributions and zero-mass terms contribute zero. If \(q_i>0\) but \(p_i=0\), cross-entropy and \(D_{\mathrm{KL}}(q\Vert p)\) are infinite under the usual extended-value convention. KL divergence is directional; cross-entropy is neither symmetric nor a metric distance.
For example, with \(q=(1,0)\) and \(p=(0.9,0.1)\):
\[ D_{\mathrm{KL}}(q\Vert p)=-\log(0.9)\approx 0.105\text{ nats}, \qquad D_{\mathrm{KL}}(p\Vert q)=+\infty. \]
The second quantity is infinite because \(p\) assigns positive mass to a category to which \(q\) assigns zero mass. In numerical computation, a stable log-softmax implementation helps avoid accidental underflow; it does not change this mathematical condition.
A non-degenerate example makes the three terms in the identity explicit. Take \(q=(0.5,0.5)\) and \(p=(0.75,0.25)\):
- \(H(q)=-(0.5\ln0.5+0.5\ln0.5)\approx0.693\) nats;
- \(H(q,p)=-(0.5\ln0.75+0.5\ln0.25)\approx0.837\) nats;
- \(D_{\mathrm{KL}}(q\Vert p)=H(q,p)-H(q)\approx0.144\) nats.
Thus \(0.837\approx0.693+0.144\). With base-2 logarithms, the same quantities are measured in bits. This complements the one-hot example above: both categories contribute to cross-entropy for this target.
The Cross-entropy lesson remains the canonical home for per-token loss, the one-hot case, masks, and reduction conventions. This advanced page focuses on the derivation and the general soft-target case.
4. Why the logarithm? A justification under explicit assumptions
The loss \(-\log p(y)\) is not chosen only because it strongly penalizes low probabilities. Its form can be recovered by requiring a stronger property: the average loss should be minimized when the predicted distribution matches the data distribution.
Consider a finite alphabet. Data follow a distribution \(q=(q_i)\), while the model predicts \(p=(p_i)\). Suppose the contribution of event \(i\) is a separable function \(F(p_i)\) and the average loss is:
\[ \mathcal L(p;q)=\sum_i q_i F(p_i), \qquad \sum_i p_i=1. \]
We seek an interior minimum at \(p=q\), for every strictly positive distribution \(q\). Introduce a Lagrange multiplier \(\lambda\) for the normalization constraint:
\[ \frac{\partial}{\partial p_i} \left[\sum_j q_jF(p_j)+\lambda(\sum_jp_j-1)\right] =q_iF'(p_i)+\lambda=0. \]
At \(p=q\), this requires \(q_iF'(q_i)=-\lambda\), the same constant for every category. Since the condition must hold for every interior distribution, \(xF'(x)\) is constant: \(F'(x)=c/x\). Integrating gives \(F(x)=c\log x+d\). For the stationary point to be a minimum, \(c<0\); up to a positive scale and an additive constant, we therefore recover:
\[ F(x)=-\log x. \]
Scope of the argument. This result assumes an additive, event-separable loss, a normalized distribution, differentiability, and the requirement that the data distribution be the minimizer for every interior distribution. It does not prove that log loss is the only useful objective for every machine-learning task: other objectives may target other properties (calibration, robustness, decisions under asymmetric costs, and so on). The video presents this as an optional Lagrange-multiplier derivation, not as a universal theorem about all losses.
5. From probabilistic coding to distillation
Cross-entropy has an operational interpretation: data follow \(q\), but the coder uses ideal lengths derived from \(p\). Each event \(i\) then costs \(-\log_2 p_i\) ideal bits, and its weight in the average is its frequency under \(q\):
\[ H(q,p)=-\sum_i q_i\log_2 p_i. \]
For example, a coder is initially tuned to \(p=(1/2,1/4,1/8,1/8)\), but the data now follow \(q=(1/8,1/8,1/4,1/2)\). Using the original code lengths \((1,2,3,3)\), the average cost becomes:
\[ H(q,p)=\tfrac18(1)+\tfrac18(2)+\tfrac14(3)+\tfrac12(3) =2.625\text{ bits}. \]
The new source entropy is \(H(q)=1.75\) bits, so the excess cost is \(D_{\mathrm{KL}}(q\Vert p)=0.875\) bit per symbol. Argument order matters: swapping the distributions generally changes the result.
Notation warning. In the video, \(P\) denotes the distribution actually observed and \(Q\) the model used to build the code; the sum is therefore weighted by \(P\) and contains \(-\log Q\). This project uses the convention \(q\) for the target/data distribution and \(p\) for the predicted distribution. The quantity is the same, but the letters are reversed relative to the video. Always identify the roles of the distributions rather than relying on their labels.
From an observed target to a teacher distribution
In standard pretraining, each position supplies one observed token: the target is one-hot and cross-entropy reduces to that token’s NLL. In knowledge distillation, a teacher model instead supplies a target distribution \(q_T(\cdot\mid x_{<t})\) over the vocabulary; the student model produces \(p_S(\cdot\mid x_{<t})\). The loss can compare these two distributions:
\[ \mathcal L_{\mathrm{KD}} =H\!\left(q_T(\cdot\mid x_{<t}),p_S(\cdot\mid x_{<t})\right). \]
The soft target carries more information than the single observed token: several possible continuations receive weights, not just one winning class. This can provide a richer training signal per example, but the teacher’s distribution is not ground truth: it can transfer the teacher’s errors, biases, and uncertainty. Distillation is a form of model compression (a more compact student), distinct from predictive compression of text using a coder.
For the cross-entropy/KL identity and computation conventions, see the previous section and the canonical Cross-entropy lesson. For the distinction between model compression and predictive compression, see LLM evolution.
What this formalization does not determine
- The tokenizer: text segmentation and vocabulary are covered in text and data and tokenization strategies.
- The architecture: probabilistic factorization alone does not imply a Transformer.
- Truth of outputs: a high probability is not factual validation.
- Generation strategy: sampling and greedy selection occur after the distribution is computed (generation).
References and further study
- Output probabilities: the conditional next-token distribution.
- Likelihood: probability of observed tokens and log-likelihood.
- Cross-entropy: per-token loss and training conventions.
- The mathematical chain of LLM training: a compact map from logits to gradients.
- Bishop, Pattern Recognition and Machine Learning, Chapters 1–2, for probabilistic foundations.
Canonical lesson: LLM overview. This page deepens its probabilistic formalization; it complements the learning route without being a prerequisite.