Blog

How a language model predicts the next token

Markdown

Learn how next-token probabilities, cross-entropy, perplexity and temperature work, then run a simple character predictor locally in Python.

A text-generating language model can turn a prompt into a sequence of predictions. At each step, it assigns scores to possible next tokens, selects one, and adds it to the context. This guide explains the classification step, the training objective and temperature, then builds a tiny character predictor you can run locally.

From text to probabilities

A tokenizer maps text to token IDs. Depending on the tokenizer, a token might represent a word, part of a word, punctuation or another piece of text. The exact split is tokenizer-specific.

A causal model processes the available context and produces a vector of scores called logits. For a vocabulary of K tokens, the next-token head produces K logits. A simple linear head can be written as z = W h + b, where h represents the context, W maps it to vocabulary scores and b is a bias. Architectures differ in how they produce h and whether they use a bias.

Softmax converts the scores into a probability distribution. For token k:

p(k | context) = exp(z[k]) / sum(exp(z[j]) for j = 1..K)

Every probability is non-negative and the probabilities sum to one. Implementations commonly subtract the largest logit before exponentiation to avoid overflow; this leaves the probabilities unchanged. The official softmax definition describes the same normalization.

Learning from the next token

In next-token training, a sequence supplies both context and target: for “rain falls softly”, one example can use “rain” as context and “falls” as the target. The model does not need a separate person to label that particular next-token example, although preparing, filtering and evaluating training data still require work.

For N predicted positions, let p[t] be the probability assigned to the actual next token at position t. The average negative log-likelihood, using natural logarithms, is:

loss = -(1 / N) * sum(log(p[t]) for t = 1..N)

A higher probability for the observed target lowers its individual loss. For one target class, cross-entropy has this form. The official cross-entropy definition includes the general multi-class formulation. Training adjusts parameters across many examples; next-token prediction is a common pretraining objective, while deployed assistants can undergo additional training.

What perplexity measures

Perplexity is exp(loss) when the average loss above uses natural logarithms. If a model gives every observed target probability 0.25, its loss is -log(0.25) and its perplexity is 4. This is an effective count, not a claim that exactly four tokens were equally likely at every position.

Measure it on held-out text as well as training text. Comparisons require care: tokenization, evaluation text and how context windows are handled affect the result. The official evaluation guide explains these limitations for causal language models. Perplexity alone does not establish whether an answer is correct or useful.

From a prediction to text

Generation repeats three operations: compute scores for the current context, select a token, and append it before the next prediction. Greedy decoding selects a highest-scoring token at each step. Sampling instead draws from a probability distribution.

For positive temperature T, temperature sampling uses:

p_T(k) = exp(z[k] / T) / sum(exp(z[j] / T) for j = 1..K)

At T = 1 this is ordinary softmax. Higher T makes unequal probabilities more even; lower positive T makes them more concentrated. With a unique maximum, the distribution approaches that token as T approaches zero. T = 0 is not valid in the formula; greedy selection is a separate operation. Temperature changes selection, not the trained weights, and neither choice guarantees accuracy.

Try a small predictor on your computer

This example counts adjacent characters in a short, original training string. It applies add-one smoothing so every character has a nonzero probability. It is a bigram language model, not a neural model: it estimates probabilities from counts rather than training weights, and sees only the immediately preceding character.

Save the code as bigram.py and run python3 bigram.py in a terminal. It uses only the Python standard library; it does not need NumPy, a browser runtime, an API key or a network connection. Its measured loss is on the same tiny string used for fitting, so it is not a held-out quality estimate.

import math
import random

text = "blue birds build bright bridges beside broad bays"
vocab = sorted(set(text))
counts = {a: {b: 1 for b in vocab} for a in vocab}
for a, b in zip(text, text[1:]):
    counts[a][b] += 1

prob = {
    a: {b: counts[a][b] / sum(counts[a].values()) for b in vocab}
    for a in vocab
}
loss = -sum(math.log(prob[a][b]) for a, b in zip(text, text[1:])) / (len(text) - 1)
print(f"tokens={len(vocab)} pairs={len(text) - 1}")
print(f"training loss={loss:.4f} perplexity={math.exp(loss):.4f}")
print(f"P('r' | 'b')={prob['b']['r']:.4f}")

rng = random.Random(7)
current = "b"
output = current
for _ in range(80):
    current = rng.choices(vocab, weights=[prob[current][c] for c in vocab], k=1)[0]
    output += current
print("sample:", output)

The sample illustrates the mechanism, not a benchmark. Add-one smoothing gives unseen pairs some probability, and a one-character context cannot preserve a full sentence's meaning. Modern language models use richer context representations and learned parameters; this example only exposes the probability and sampling loop.

When this distinction helps

The next-token view is useful when you assess outputs: a fluent continuation can still contain a false claim, and changing sampling settings does not verify it. Test on representative inputs, check important facts against reliable sources and evaluate the complete application, not just one metric.

Discover Ailoot’s LLM API. One Ailoot-issued API key gives you 1,284 models and variants across 15 categories. That catalogue puts Ailoot among the world’s largest AI routers by model count. The catalogue covers text with GPT or Claude, images with FLUX, video with Kling, voice with Eleven v4, music with Suno, 3D assets with Tripo3D and ranking with Cohere Rerank.

Use Mercury Decide, Jev or Clef through Ailoot to add structured decisions to your workflow. Pair them with models that analyze documents and generate text.

Build your classification and routing features into an app with the Ailoot API. Monitor model usage across projects and manage company spend through one workspace.

One subscription covers the full Ailoot catalogue, with day-one access to new flagship models through the same key. Subscriptions and promo codes offer savings of up to 50% compared with official provider API prices. Get your key at https://ailoot.ai/ and check your account for a promo code.