Language Models: Next-Token Prediction Explained
Strip away the chat interface and a large language model is a function that reads a list of integers and returns a probability distribution over the next integer. Everything users experience â summaries, code, refusal to answer â emerges from that one prediction repeated many times. This lesson builds the picture from the bottom: how text becomes integers, how the model learns the distribution, how the quality of that distribution is measured, and how a distribution becomes a sentence.
A Probability Distribution Over Continuations
Formally the model estimates the conditional probability of each token given every token before it, and the chain rule turns those conditionals into a joint distribution over whole sequences. Multiply the per-step probabilities and you get the likelihood the model assigns to any document, which is exactly the quantity minimized during training. Because each factorization is exact, nothing is lost by predicting one token at a time â the model is not approximating sequence probability, it is defining it step by step.
This framing explains two everyday observations. First, the model can score text as well as generate it, which powers perplexity evaluation and likelihood-based reranking. Second, generation is search over a distribution the model already defines, so every decoding strategy is a policy for choosing among plausible continuations rather than a change to the model itself. When output quality is poor, the fault lies either in the distribution â training data and objective â or in the policy you imposed on top.
Where the Vocabulary Comes From
You cannot index a probability distribution over raw characters without making the prediction task needlessly long, and you cannot index it over whole words without an enormous sparse vocabulary. Subword tokenizers resolve the trade-off by merging frequent character sequences into single tokens, keeping rare words splittable. Byte-pair encoding starts from bytes and merges the most frequent adjacent pair repeatedly; WordPiece does the same with a likelihood-based criterion; unigram tokenization samples a subset of pieces that maximizes corpus likelihood.
The choice has downstream consequences that surprise teams. A tokenizer trained mostly on English spends many tokens per Chinese or emoji character, silently raising cost for those users. A tokenizer with aggressive merging produces fewer, longer tokens, which speeds prefill but makes each prediction coarser. Numbers are split digit-wise by many vocabularies, so arithmetic prompts consume disproportionate context. Always inspect token counts for your real prompts before estimating latency or price.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("gpt2")
samples = [
"The transformer stack processes every position at once.",
"supercalifragilisticexpialidocious",
"def tokenize(text): return text.split()",
]
for text in samples:
ids = tok.encode(text)
pieces = tok.convert_ids_to_tokens(ids)
print(f"{len(ids):>3} tokens {pieces}")
print("round-trip ok:", tok.decode(tok.encode(samples[0])) == samples[0])
print("vocab size:", tok.vocab_size, " special ids:", tok.pad_token_id, tok.eos_token_id)
Watch how the long coinage shreds into familiar fragments: the model never sees a word it has literally never seen, only a novel arrangement of pieces it has.
Training on Shifted Windows
Self-supervised training needs no labels, because the labels are the input. Take a sequence of tokens, shift it by one position, and ask the network to predict the shifted version from the original. Cross-entropy at each position is the loss; gradients flow through every layer at every index simultaneously. Real training packs documents into fixed-length windows, separates them with an end-of-sequence marker, and discards attention across document boundaries so the model does not learn false continuity.
import torch
import torch.nn as nn
class TinyLM(nn.Module):
def __init__(self, vocab=256, width=128, layers=2, heads=4, max_len=128):
super().__init__()
self.tok = nn.Embedding(vocab, width)
self.pos = nn.Embedding(max_len, width)
layer = nn.TransformerEncoderLayer(width, heads, 4 * width,
dropout=0.1, batch_first=True)
self.stack = nn.TransformerEncoder(layer, layers)
self.head = nn.Linear(width, vocab)
def forward(self, ids):
b, t = ids.shape
pos = torch.arange(t, device=ids.device)
x = self.tok(ids) + self.pos(pos)
mask = torch.triu(torch.full((t, t), float("-inf"), device=ids.device), diagonal=1)
return self.head(self.stack(x, mask=mask))
def batch_loss(model, window):
x, y = window[:, :-1], window[:, 1:]
logits = model(x)
return nn.functional.cross_entropy(logits.reshape(-1, logits.size(-1)), y.reshape(-1))
model = TinyLM()
data = torch.randint(0, 256, (4, 128))
print("initial loss:", round(float(batch_loss(model, data)), 3))
print("uniform baseline:", round(torch.log(torch.tensor(256.0)).item(), 3))
A fresh model sits near the uniform baseline of the log vocabulary size; a trained one drops several nats below it, and that drop is the clearest signal that language structure has been captured.
How Well Is the Distribution?
Loss is measured in nats or bits per token, and perplexity exponentiates it back into a more intuitive quantity: the effective number of equally likely candidates the model was choosing among at each step. If perplexity is 20, the model is roughly as uncertain as picking uniformly from twenty options. Comparing perplexity across models is only fair with the same tokenizer, because a coarser vocabulary makes the task easier and the number lower by construction.
| Metric | What it measures | Good direction | Common trap |
|---|---|---|---|
| Cross-entropy loss | Average nats per predicted token | Lower | Depends on tokenizer and domain mix |
| Perplexity | Exponent of loss, effective branching factor | Lower | Not comparable across vocabularies |
| Bits per byte | Compression normalized to raw bytes | Lower | Requires detokenization care |
| Pass@k on code | Fraction of problems solved in k tries | Higher | Sensitive to prompt scaffolding |
| Preference win rate | Human or judge preference vs baseline | Higher | Judges drift and can be gamed |
Perplexity correlates only loosely with downstream usefulness: a model can be fluent and still fail at instruction following, which is why the later lessons on evaluation pair intrinsic metrics with task-based ones.
From Distributions to Sentences
Decoding is where most perceived quality differences appear. Greedy decoding always takes the argmax, which is fast and deterministic but prone to loops, because a repetitive continuation often has the highest conditional probability. Beam search keeps several partial hypotheses and is strong for translation, though it tends to flatten diversity. Sampling injects randomness from the full distribution, and it becomes controlled when you filter first: top-k restricts candidates to a fixed set, top-p takes the smallest set covering probability p, and temperature rescales logits before either filter runs.
The interaction matters more than any single knob. Low temperature with a wide nucleus still surprises; high temperature with a tight nucleus does not, because the filter removes the risky tail before temperature amplifies it. Production systems usually run temperature near zero for extraction tasks, moderate values for dialogue, and always record the settings with the output so results can be reproduced later.
Why Prediction Alone Produces Behavior
The most counterintuitive fact about language models is that a objective this narrow yields planning, translation, and code. The explanation is partly scale: when the corpus contains millions of examples of reasoning traces, arithmetic long-division, and question-answer pairs, predicting the next token well requires internalizing the procedure that produced them. A model that wants to continue a worked example must effectively compute the next step. Prediction pressure is also a regularizer â the model has no room to learn spurious shortcuts that do not generalize to the next token.
The other half is that the pretraining objective leaves behavior unspecified. The model learned to continue text in the voice of its source, not to be helpful, so the instruction-following and refusal behaviors seen in assistants are added later through supervised tuning and preference optimization. Understanding that separation prevents a whole category of confusion: base models are continuers, and products are base models plus additional training.
â ī¸Check your loss definition
Common Mistakes
Comparing perplexity across models with different tokenizers
Fix: Report bits per byte or evaluate both models on identical text with a shared tokenizer
Evaluating with greedy decoding and calling the model incapable
Fix: Retry with sampling and multiple seeds before concluding that a capability is missing
Feeding raw text with no document boundaries
Fix: Insert an end-of-sequence token between documents so continuity is not learned across unrelated files
Judging training health by loss alone
Fix: Track downstream task checks periodically; loss can fall while instruction following stalls
Key Takeaways
- A language model factorizes sequence probability into per-token conditionals via the chain rule
- Subword tokenization sets the granularity of prediction and silently affects cost per language
- Training shifts the input by one and applies cross-entropy at every position at once
- Perplexity is the exponentiated loss and is only comparable under a shared tokenizer
- Decoding choices â greedy, beam, top-k, top-p, temperature â shape output far more than the fixed weights