Predicting the next word
Type “see you” on your phone’s keyboard and three suggestions appear above the letters: “tomorrow”, “later”, “tonight”. The phone knows nothing about your plans: it has simply learnt which words tend to follow “see you”. It is a small language model.
An LLM does exactly the same thing, only far better. In the two previous parts we saw how text becomes a sequence of tokens and how each token becomes a vector, an embedding. Now we reach the task all of this exists for: predicting the next token. It sounds trivial, yet it is the heart of everything an LLM can do.
One word at a time
A language model is a function that, given a sequence of tokens, assigns a probability to every possible next token. After “The cat is sleeping on the” the model might say: “sofa” 31%, “bed” 22%, “table” 9%, “roof” 6%, and so on for every other entry in the vocabulary, each with its own probability, however tiny. As a formula: P(next token | previous tokens).
So how is a whole text generated? One token at a time. The model computes the distribution, one token is chosen from it, it is appended to the sequence and the process starts again, with a context one token longer. This way of working is called autoregressive: each step depends on all the steps already taken. The reply you read in a chat is built like this, piece by piece, until a special end-of-text token or a length limit is reached.
How does the model produce those numbers? The last layer of the network returns a raw score for each token in the vocabulary (tens of thousands of entries), called a logit. To turn them into probabilities we use the softmax: take the exponential of each logit and divide it by the sum of all the exponentials. The result is a set of positive numbers that add up to 1, and the highest logit becomes the highest probability.
From n-grams to neural networks
The idea is much older than LLMs. In 1948 Claude Shannon, in the paper that founded information theory, built “artificial” sentences by choosing each letter, and then each word, based on the previous ones, using frequencies taken from real texts. With letters chosen at random he got gibberish; taking the previous letters, and then the previous word, into account, the result began to resemble English. It was a Markov chain: a process in which the next step depends only on a fixed number of previous steps.
This is where n-gram models come from, used for decades in speech recognition and translation. An n-gram is a sequence of n tokens. A trigram model looks at the last two words and counts how many times, in a large corpus, each word has followed them: if “sofa” follows “on the” 31 times out of 100, the estimated probability is 0.31.
The limitation is obvious. The longer the context, the rarer the combinations become: almost every five-word sequence we write appears in no text at all, however huge. When the context has never been seen, the model uses backoff, falling back on a shorter context. And the model has no idea that “cat” and “kitty” are similar: to it they are two different symbols.
Neural networks overcome both problems. As early as 2003, Bengio and colleagues represented words as vectors, so that similar contexts gave similar predictions even without ever having been seen. Then came recurrent networks and, from 2017, the Transformer. The task, though, has not changed: given the context, a distribution over the next token. What changes, enormously, is the quality of the estimate.
Choosing the token: greedy, temperature, top-k, top-p
Having the distribution is not enough: we have to decide which token to take. This stage is called decoding and there are four main strategies.
- Greedy: always take the most likely token. It is deterministic and looks like the most sensible choice, but it often leads to flat texts that fall into a loop and repeat the same sentence.
- Temperature: before the softmax, the logits are divided by a number T. With T < 1 the differences are amplified and the most likely token dominates: predictable, repetitive, “safe” text. With T > 1 the distribution flattens and rare tokens get a chance too: the text becomes more creative and, beyond a certain point, nonsense. With T close to zero we are back to greedy.
- Top-k: keep only the k most likely tokens, renormalise and sample among them. This cuts off the long tail of unlikely tokens.
- Top-p or nucleus sampling (Holtzman et al., 2019): keep the smallest group of tokens whose cumulative probability exceeds p, for example 0.9. The number of candidates adapts: few when the model is confident, many when the choice is genuinely open.
Plausible does not mean true
Now it is easier to see why an LLM sometimes “hallucinates”, that is, confidently states things that are false. The model does not consult an archive of checked facts: it produces the most plausible continuation given the text it has seen. If you ask it for the biography of a little-known person, the shape of a biography is very easy to predict; the right details much less so. And sampling always picks a token, even when no candidate is truly reliable.
Training explains why. How good the model is at predicting is measured with cross-entropy: for every position in a text, take the probability assigned to the token that was actually there and compute its negative logarithm; the average over the whole text is the loss. Perplexity is the exponential of this average and can be read as “how many tokens, on average, the model is torn between”. During training the loss is minimised with gradient descent and its relatives, such as Adam (I cover them in the article on optimisers). Note that what gets rewarded is predicting the text well, not telling the truth. Later training stages soften the problem, but do not eliminate it.
The demo below is a toy n-gram model, trained in the browser on a few KB of simple sentences: at each step it shows the distribution the token is drawn from.
What to try in the demo
- Press Greedy several times: it soon falls into a loop and repeats the same sentences.
- Set the temperature to 0.1 and then to 2: watch the bars pile up on one candidate or flatten out, and see how the text changes with Generate 20.
- Lower top-k to 3 or top-p to 0.6: the excluded candidates turn into dashed grey bars and can no longer be drawn.
- With words, go from order 1 to order 3. At order 1 you get a salad of frequent words; at order 3 the text flows, but the Copied counter rises: the model copies whole chunks of the training text. This is memorisation, the flip side of a long context with little data.
- Switch to characters with order 2 and then 6: first plausible syllables appear, then real words.
- Type a beginning that is not in the text, such as “the dragon”: the “order used” drops and backoff appears.
In Python
With Hugging Face’s transformers library we can look at the same thing in a real model, small and historic: GPT-2.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
inputs = tok("The computer", return_tensors="pt")
# the 5 most likely tokens after the prompt
with torch.no_grad():
logits = model(**inputs).logits
top = torch.softmax(logits[0, -1], dim=-1).topk(5)
for p, i in zip(top.values, top.indices):
print(f"{tok.decode(int(i))!r:>12} {p.item():.3f}")
# generation with two different temperatures
for t in (0.3, 1.5):
torch.manual_seed(0)
out = model.generate(**inputs, do_sample=True, temperature=t, top_k=50,
max_new_tokens=30, pad_token_id=tok.eos_token_id)
print(f"T={t}:", tok.decode(out[0], skip_special_tokens=True))
The program first prints the five most likely tokens after “The computer”, each with its probability (the leading space is part of the token). Then it prints two continuations: the one at temperature 0.3 is more conventional and tends to repeat itself, the one at 1.5 is more varied and often wanders off in odd directions. The exact values depend on the library version.
Predicting the next word looks like a modest task, but doing it well on any text requires, to some extent, grasping grammar, facts, style and reasoning. To me this is the most surprising discovery of recent years: such a simple objective, with enough data and a large enough network, produces abilities that nobody programmed explicitly. What remains is to understand how the model decides which tokens in the context really matter for the prediction: that is the job of attention, the subject of the next part. Recurrent networks, natural language and generative models are covered in chapters 8–10 of my book Deep Learning con Keras e Tensorflow (in Italian).