Sub topic 1
How a model writes: predicting the next token
This chapter explains the basic mechanism behind every answer a language model gives. Once you see how text is produced one piece at a time, the later chapters on fabrication, red flags, and checking will make more sense. The key point is that the mechanism rewards text that sounds likely. Nothing in it looks up whether the text is true.
Prerequisites
This chapter assumes you have:
- Basic experience using a chat-based LLM assistant, such as asking questions and reading answers.
- Enough Python to read short functions, lists, and loops. The code is optional but runs as shown.
- A general idea that models are trained on large collections of text.
You do not need any math beyond adding, dividing, and the idea of a percentage.
The core idea: one token at a time
A large language model (LLM) is a program that, given some text, estimates what text is likely to come next. It does this over and over. Each time, it adds one small piece of text to the end and then predicts again.
That small piece is called a token. A token is a chunk of text that the model treats as one unit. It can be a whole common word like "the", part of a longer word like "un" and "believ" and "able", a punctuation mark, or a space plus a few letters. Different models split text differently, so the same sentence can have different token counts in different models.
The model never sees your text as letters or as ideas. It sees a sequence of token IDs, which are numbers that stand for tokens in a fixed vocabulary. Vocabularies usually have tens of thousands to a few hundred thousand entries.
Here is the loop in plain steps:
- The prompt is split into tokens.
- The model reads all the tokens so far and produces a score for every token in its vocabulary.
- Those scores are turned into probabilities.
- One token is chosen from those probabilities.
- The chosen token is added to the text, and the loop starts again at step 2.
- The loop stops when the model produces a special end-of-text token or reaches a length limit.
From scores to probabilities
The model's raw output for each candidate token is a number called a logit. A logit is an unnormalized score. A higher logit means the model considers that token a better continuation. Logits can be negative, and they do not add up to anything meaningful on their own.
To get probabilities, the scores go through a function called softmax. Softmax makes every value positive and scales the values so they sum to 1. The bigger a score is compared with the others, the larger its share.
The following example uses three candidate tokens. It also divides the logits by a temperature before softmax. Temperature is a setting that controls how sharply the probability concentrates on the top candidate. We cover it fully in a later chapter. For now, notice only that the model's output is a spread of probabilities, not a single answer.
import math
def softmax(logits, temperature=1.0):
scaled = [x / temperature for x in logits]
m = max(scaled)
exps = [math.exp(x - m) for x in scaled]
total = sum(exps)
return [e / total for e in exps]
logits = [2.0, 1.0, 0.5]
print(softmax(logits, temperature=1.0))
print(softmax(logits, temperature=0.5))Running it prints roughly [0.63, 0.23, 0.14] for temperature 1.0 and roughly [0.84, 0.11, 0.04] for temperature 0.5. The first candidate wins in both cases, but at the lower temperature it wins by more.
Two details in the code are worth knowing:
- Subtracting the maximum (
m) before callingmath.expdoes not change the result. It prevents overflow when scores are large. - Dividing by a temperature below 1 widens the gaps between scores. Dividing by a temperature above 1 narrows them.
A worked example
Suppose the prompt is "The capital of France is". A well-trained model might assign probabilities like these to the next token:
| Candidate token | Probability |
|---|---|
| " Paris" | 0.96 |
| " a" | 0.01 |
| " located" | 0.01 |
| " Lyon" | 0.004 |
| everything else combined | 0.016 |
The model picks " Paris" almost every time. This looks like "knowing" a fact, and in a practical sense it is. The training text contained that phrase pattern many times, so the pattern is strongly encoded in the model's parameters.
Now change the prompt to "The 2019 annual revenue of Brightwell Dental Supplies was". The model has probably seen little or nothing about this company. It still must produce a distribution over the next token. The distribution will be flatter, but it will still favor tokens that look like the start of a number, such as " $", " approximately", or " about". The model will continue with digits, because text of this shape is usually followed by digits. The result reads as a plausible revenue figure.
Nothing in the loop above has a step that says "stop, I don't have this fact." The loop always produces a next token.
What the model learned from
The probabilities come from the model's parameters, which are the numbers adjusted during training. Training works like this in outline:
- Take a huge collection of text.
- Show the model a stretch of text with the next token hidden.
- Compare the model's predicted probabilities with the real next token.
- Adjust the parameters slightly so the real token would have been more probable.
- Repeat across an enormous amount of text.
This stage is called pretraining. The goal it optimizes is predicting held-out text well. It is not "state only true things." Text in the training collection includes accurate encyclopedia entries, but also fiction, jokes, forum arguments, outdated pages, and mistakes. The model learns the patterns of all of it.
Many assistants then go through further training, often called fine-tuning or preference training. This stage teaches the model to follow instructions, hold a conversation, and prefer answers people rate as helpful. It improves behavior a great deal. It does not add a built-in fact checker. Later chapters explain how this stage can even encourage confident guessing.
Writing is a chain of choices
Because each token depends on all the tokens before it, early choices shape later ones. This has two consequences that matter for fabrication.
Commitment. Once a token is chosen, it becomes part of the context. The model then treats it as given. If the model writes "The study was published in 2015 by", the next tokens are conditioned on that "2015", even if it was a weak guess. The model does not go back and revise it. Later text tends to stay consistent with the earlier choice, which makes a wrong detail look more established as the answer grows.
Compounding. A small mistake early in an answer can pull the rest of the answer toward it. A made-up author name leads to a made-up title that fits that author, then a made-up journal that fits the title.
The following sketch simulates the loop with a tiny hand-written table. It is not a real model. It shows only the shape of the process: choose, append, repeat.
import random
# A toy "model": for each previous word, possible next words and weights.
table = {
"<start>": [("The", 1.0)],
"The": [("study", 0.6), ("report", 0.4)],
"study": [("found", 0.7), ("showed", 0.3)],
"report": [("found", 0.5), ("showed", 0.5)],
"found": [("that", 1.0)],
"showed": [("that", 1.0)],
"that": [("<end>", 1.0)],
}
def generate(seed=None):
rng = random.Random(seed)
word, out = "<start>", []
while True:
choices, weights = zip(*table[word])
word = rng.choices(choices, weights=weights)[0]
if word == "<end>":
return " ".join(out)
out.append(word)
for s in range(3):
print(generate(seed=s))Each line printed is a grammatical, sensible phrase. At no point does the program check whether any study found anything. A real model is vastly more complex, but the control flow has the same shape. It conditions on what came before and samples what comes next.
Common misunderstandings
These are mistakes intermediate users often make about the loop.
- "The model looks the answer up." A plain model does not search a database during generation. Whatever it appears to know is stored in its parameters as statistical patterns. Systems that do search are built around the model, and we cover them in a later chapter on grounding.
- "The model plans the whole answer first." Models can encode some information about likely continuations, but the visible output is produced one token at a time and cannot be edited afterward. This is why an answer can start confidently and then contradict itself.
- "A high-probability token is a true token." Probability measures how well a token fits the pattern of text seen in training. A false statement can be a very common pattern, such as a popular myth.
- "The model's confidence tone reflects its internal certainty." Tone is part of the generated text. A model can write "definitely" in front of a guess because that style fits the context. The next chapter takes this up in detail.
Why this matters for the rest of the tutorial
Everything that follows builds on the loop in this chapter:
- Because the model must always emit a token, it can produce an answer even when it has no basis for one.
- Because tokens are chosen by sampling from probabilities, the same prompt can give different answers on different runs. That variation is the basis of the self-consistency check.
- Because the model has no lookup step, supplying documents in the prompt can change what it produces. That is the idea behind grounding.
- Because the process has no internal truth test, verification must come from outside the model.
Exercise
A model is asked "Who won the 1987 regional chess tournament in the town of Marlow?" and replies with a full name and a score. Using the generation loop, explain why the model can produce a specific-sounding answer even if its training data never mentioned this tournament. Also name one thing in the loop that would not change this.
Show answer
At every step the model must output a probability distribution over its vocabulary and choose one token from it. The prompt pattern ("Who won ... tournament") makes name-like tokens likely, so the model picks plausible name tokens and then a plausible score format, one token at a time. The loop has no step that checks whether a supporting fact exists. A flatter distribution (lower certainty) would not stop this. The model still samples a token, and each chosen token becomes context that makes the following tokens fit the invented answer. Lowering the temperature would not fix it either, because that only makes the model more likely to pick its top guess.
Exercise
Run the softmax function with logits [3.0, 1.0, 0.2] at temperatures 2.0, 1.0, and 0.25. Describe how the top probability changes. Does a higher top probability mean the top token is correct?
Show answer
The top probability rises as temperature falls. At temperature 2.0 it is about 0.62, at 1.0 about 0.84, and at 0.25 it is above 0.99. A higher top probability does not mean the token is correct. It only means the model's scores favor that token more strongly after rescaling. Probability reflects fit to learned text patterns, and a wrong token can score highest.