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 :
where are the logits a causal transformer produces at position (Causal Masking). The factorization is exact (Probability for Deep Learning); all modeling choices are in how is computed.
The training objective
Maximum likelihood over a corpus is the average next-token cross-entropy (Maximum Likelihood and Cross-Entropy):
In code: run the model on tokens , take the logits at every position, and compare with the targets , the inputs shifted by one.
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 matrix indexed by the current token. Gradient descent on the cross-entropy finds the same probabilities:
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; 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);-100marks 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 for bits.
Exercises
Exercise 1: Sequence probability
A model gives the tokens of a 3-token sequence probabilities , and . What is the sequence's probability and the average loss?
Answer
; about nats per token.
Solution
. Loss .
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: (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
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…
- classify whole documents
- predict each token from the tokens before it
- reconstruct masked images
- sort tokens
The targets of next-token training are…
- the inputs reversed
- the inputs shifted by one position
- random tokens
- the same as the inputs
The language-modeling loss is the average of…
- over positions
- squared errors of token ids
- attention weights
- token counts