TExcelTAD
Home › Math for Deep Learning & LLMs › Language Modeling as Next-Token Prediction

Language Modeling as Next-Token Prediction

A language model assigns a probability to every sequence of tokens. By the chain rule of probability this is the same as predicting each token from the ones before it, so training an LLM reduces to one very large classification problem: given a prefix, output a distribution over the vocabulary for the next token, and minimize the cross-entropy against the token that actually came next.

The factorization

For a token sequence x1,…,xTx_1, \ldots, x_T:

pθ(x1,…,xT)=∏t=1Tpθ(xt∣x<t),pθ(⋅∣x<t)=softmax⁡(zt)p_{\boldsymbol{\theta}}(x_1, \ldots, x_T) = \prod_{t=1}^{T}p_{\boldsymbol{\theta}}(x_t \mid x_{<t}), \qquad p_{\boldsymbol{\theta}}(\cdot \mid x_{<t}) = \operatorname{softmax}(\mathbf{z}_t)

where zt∈RV\mathbf{z}_t \in \mathbb{R}^V are the logits a causal transformer produces at position t−1t - 1 (Causal Masking). The factorization is exact (Probability for Deep Learning); all modeling choices are in how pθ(xt∣x<t)p_{\boldsymbol{\theta}}(x_t \mid x_{<t}) is computed.

The training objective

Maximum likelihood over a corpus is the average next-token cross-entropy (Maximum Likelihood and Cross-Entropy):

L(θ)=−1T∑t=1Tlog⁡pθ(xt∣x<t)\mathcal{L}(\boldsymbol{\theta}) = -\frac{1}{T}\sum_{t=1}^{T}\log p_{\boldsymbol{\theta}}(x_t \mid x_{<t})

In code: run the model on tokens x1,…,xT−1x_1, \ldots, x_{T-1}, take the logits at every position, and compare with the targets x2,…,xTx_2, \ldots, x_T, the inputs shifted by one.

python · try it yourself
import numpy as np

text = "the cat sat on the mat. the cat ate."
vocab = sorted(set(text)); stoi = {c: i for i, c in enumerate(vocab)}; V = len(vocab)
ids = np.array([stoi[c] for c in text])
inputs, targets = ids[:-1], ids[1:]                       # shift by one
# The simplest language model: a bigram table of counts, p(next | current)
counts = np.ones((V, V))                                  # add-one smoothing
for a, b in zip(inputs, targets):
    counts[a, b] += 1
P = counts / counts.sum(axis=1, keepdims=True)
nll = -np.mean(np.log(P[inputs, targets]))
print("vocabulary size:", V, " training positions:", len(inputs))
print(f"bigram model loss {nll:.4f} nats/char vs uniform ln V = {np.log(V):.4f}")
top = np.argsort(P[stoi["a"]])[::-1][:3]
print("most likely after 'a':", [(vocab[i], round(float(P[stoi['a'], i]), 3)) for i in top])
vocabulary size: 11  training positions: 35
bigram model loss 1.6221 nats/char vs uniform ln V = 2.3979
most likely after 'a': [('t', 0.375), ('s', 0.062), ('o', 0.062)]

A bigram table is a language model with context length 1. A transformer replaces the table lookup by a network that reads the whole prefix.

A neural bigram, trained by gradient descent

The count table is exactly the maximum-likelihood solution for a model whose logits are a free V×VV \times V matrix WW indexed by the current token. Gradient descent on the cross-entropy finds the same probabilities:

python · try it yourself
import numpy as np

text = "the cat sat on the mat. the cat ate."
vocab = sorted(set(text)); stoi = {c: i for i, c in enumerate(vocab)}; V = len(vocab)
ids = np.array([stoi[c] for c in text]); x, y = ids[:-1], ids[1:]
W = np.zeros((V, V))                                      # logits for next char given current char
for step in range(501):
    Z = W[x]; Z = Z - Z.max(1, keepdims=True)
    P = np.exp(Z); P /= P.sum(1, keepdims=True)
    loss = -np.mean(np.log(P[np.arange(len(y)), y]))
    G = P.copy(); G[np.arange(len(y)), y] -= 1; G /= len(y)   # softmax CE gradient
    dW = np.zeros_like(W); np.add.at(dW, x, G)                 # embedding-style scatter
    W -= 10.0 * dW
    if step % 100 == 0:
        print(f"step {step}: loss {loss:.4f}")
counts = np.zeros((V, V)); np.add.at(counts, (x, y), 1)
mle = counts / np.maximum(counts.sum(1, keepdims=True), 1)
print(f"count-based (unsmoothed) loss: {-np.mean(np.log(mle[x, y])):.4f}")
step 0: loss 2.3979
step 100: loss 0.7626
step 200: loss 0.7547
step 300: loss 0.7522
step 400: loss 0.7509
step 500: loss 0.7502
count-based (unsmoothed) loss: 0.7473

The loss falls toward the count-based value from above: normalized counts are the exact maximum-likelihood solution for this model, and gradient descent approaches it as the logits grow.

What the loss means

  • The loss is the average number of nats of surprise per token; eLe^{\mathcal{L}} is the perplexity.
  • The lowest achievable loss is the entropy rate of the data: text is not deterministic, so even a perfect model has loss above zero.
  • Pre-training on trillions of tokens minimizes this single objective; abilities such as translation or summarization emerge because predicting text well requires them.

From pre-training to assistants

Fine-tuning keeps the same loss on curated conversations, often computed only on the assistant's tokens (a mask on the loss). Preference optimization then changes the objective (Policy Gradients and RLHF). At inference the model is used by repeatedly sampling the next token and appending it.

In software

  • Hugging Face causal LMs compute exactly this loss when called with labels=input_ids (the shift happens inside); -100 marks positions to ignore.
  • A batch of documents is usually packed into fixed-length sequences separated by end-of-text tokens.
  • Loss curves are logged in nats per token; divide by ln⁡2\ln 2 for bits.

Exercises

Exercise 1: Sequence probability

A model gives the tokens of a 3-token sequence probabilities 0.50.5, 0.20.2 and 0.90.9. What is the sequence's probability and the average loss?

Answer

0.090.09; about 0.8030.803 nats per token.

Solution

0.5⋅0.2⋅0.9=0.090.5 \cdot 0.2 \cdot 0.9 = 0.09. Loss =−13(ln⁡0.5+ln⁡0.2+ln⁡0.9)=13(0.693+1.609+0.105)=0.803= -\frac{1}{3}(\ln 0.5 + \ln 0.2 + \ln 0.9) = \frac{1}{3}(0.693 + 1.609 + 0.105) = 0.803.

Exercise 2: Number of predictions

A batch has 8 sequences of 2048 tokens. How many next-token predictions does one training step score?

Answer

16,376.

Solution

Each sequence of 2048 tokens yields 2047 input-target pairs: 8⋅2047=16,3768 \cdot 2047 = 16{,}376 (16,384 if each sequence carries one extra token for the shift).

Exercise 3: Shift by one (code)

For the token ids [5, 9, 2, 7], print the input and target arrays used for training.

Answer

Inputs [5, 9, 2], targets [9, 2, 7].

Solution
python · try it yourself
ids = [5, 9, 2, 7]
print(ids[:-1], ids[1:])
[5, 9, 2] [9, 2, 7]

Test yourself

An autoregressive language model is trained to…

  1. classify whole documents
  2. predict each token from the tokens before it
  3. reconstruct masked images
  4. sort tokens

The targets of next-token training are…

  1. the inputs reversed
  2. the inputs shifted by one position
  3. random tokens
  4. the same as the inputs

The language-modeling loss is the average of…

  1. −log⁡p(xt∣x<t)-\log p(x_t \mid x_{<t}) over positions
  2. squared errors of token ids
  3. attention weights
  4. token counts