- Explain tokenisation and estimate token counts from word counts.
- Compute next-token probabilities from logits with softmax at different temperatures, and apply top-p filtering.
- Explain the cross-entropy training objective and interpret perplexity.
- Describe the attention formula and work a small numeric attention example by hand.
- Describe the stages that turn a pretrained base model into a chat assistant, and explain why hallucinations occur.
Before this: How Machines Learn
Why this matters
Chat assistants are the AI most people use every day. Knowing how they produce text explains their strengths, why the same question can get different answers, and why they sometimes invent facts with complete confidence.
A large language model (LLM) is a neural network, trained on a very large amount of text, whose core job is to predict what text comes next.
Step 1: text becomes tokens
Models don't read letters or whole words. They read tokens: chunks of text from a fixed vocabulary, typically tens of thousands to a few hundred thousand entries. Common words are usually one token; rare or long words are split into pieces; spaces and punctuation are often attached to or counted as tokens too. Each token is then turned into a number the network can work with.
An illustrative example (invented for teaching, not the output of any real tokenizer). The sentence:
The weather is unbelievably nice today.
might be split roughly like this:
The · weather · is · un · believ · ably · nice · today · .
That is 6 words but about 9 tokens, because the long word was split into three pieces and the full stop is its own token. Exact splits differ between models, so treat this as a sketch rather than the output of a specific tokenizer.
A useful rule of thumb for English, as published by OpenAI: one token is about four characters or about three-quarters of a word, so 100 tokens is roughly 75 words. Other languages often use more tokens per word. Tokens matter because models have limits on how many they can handle at once, and services charge by the token.
Step 2: predict the next token
Given a sequence of tokens, the model outputs a probability for every token in its vocabulary being the next one. An illustrative example with made-up numbers, for the text "The sky is":
| Possible next token | Probability |
|---|---|
| blue | 62% |
| clear | 11% |
| falling | 4% |
| the | 3% |
| everything else | 20% |
One token is chosen, appended to the text, and the whole process repeats. A long answer is just this loop run hundreds or thousands of times. Nothing is written in advance; the reply is built one token at a time.
Step 3: the transformer and attention
Almost all modern LLMs use an architecture called the transformer, introduced in the 2017 research paper "Attention Is All You Need".
Its key idea is attention. When processing each token, the model looks back over all the earlier tokens and decides how much each one matters for the current step. In "The trophy didn't fit in the suitcase because it was too big", attention helps the model link "it" to "trophy". In plain words: attention lets every word consult every other relevant word, rather than reading strictly left to right and forgetting.
A transformer stacks many layers of attention plus ordinary neural-network layers. Earlier layers tend to capture simple patterns like grammar; later layers capture more abstract relationships. This is a simplification, but a fair one. Transformers also process all the tokens of a training passage in parallel, which made it practical to train on vast amounts of text using many graphics processors (GPUs).
Step 4: how a chatbot is trained, in stages
Pretraining. The model reads a huge collection of text, such as web pages, books and code, and learns to predict the next token. This is where it absorbs grammar, facts, styles and reasoning patterns. The result is a base model: knowledgeable, but it just continues text. Ask it a question and it might write three more questions.
Instruction tuning. The base model is trained further on many examples of instructions paired with good responses, written or curated by people. It learns to behave like an assistant that answers rather than rambles.
Preference training. People compare pairs of model responses and pick the better one. Those choices train the model further toward answers people prefer: more helpful, more honest, less harmful. The best-known version is reinforcement learning from human feedback (RLHF): OpenAI described using it for ChatGPT, training a separate reward model from human rankings and then optimising the chatbot against it. Developers also use variations, including feedback generated with the help of other AI models.
Why the same prompt gives different answers
At each step the model produces probabilities, not a single answer. The software then samples: it picks a token at random, weighted by those probabilities. In the "sky" example, "blue" wins about 62% of the time, but "clear" will sometimes be picked, and the rest of the sentence then follows a different path.
Temperature is a setting that controls how adventurous that sampling is. At low temperature the most likely tokens dominate, giving focused, repeatable answers. At higher temperature the probabilities are flattened, giving more varied and creative, but also more error-prone, text. At a temperature of zero, many systems always pick the top token, though small differences can still creep in for technical reasons.
Why LLMs hallucinate
A hallucination is a fluent, confident statement that is false, such as a made-up citation or a wrong date. It happens for understandable reasons:
- The model is trained to produce plausible text, and a plausible-sounding falsehood can score well.
- Facts are stored diffusely across billions of parameters, not in a lookup table, so rare facts are fuzzy.
- Unless it is connected to search or documents, the model has no way to check a source.
- Training has often rewarded giving an answer over admitting uncertainty, though developers now actively train against this.
Developers work hard to reduce hallucinations, but no current model is free of them.
Going deeper
This section puts numbers on three ideas from above: how scores become probabilities, what the model is trained to minimise, and what attention computes. All numbers are small and illustrative; real models do the same arithmetic with vocabularies of tens of thousands of tokens and vectors with thousands of entries.
From scores to probabilities: softmax and temperature
The network's last layer produces one raw score, called a logit, for every token in the vocabulary. A function called softmax turns logits into probabilities that are positive and add up to 1. With temperature :
Here is the logit of token , , and the sum in the denominator runs over every token in the vocabulary.
Worked example. Suppose that after "The sky is" only three tokens matter, with logits blue , clear , falling .
At : , , . The total is , so the probabilities are , and .
Changing the temperature divides every logit by before the softmax:
| Temperature | blue | clear | falling |
|---|---|---|---|
| 0.5 | 0.946 | 0.047 | 0.006 |
| 1.0 | 0.766 | 0.171 | 0.063 |
| 2.0 | 0.569 | 0.269 | 0.163 |
Low temperature sharpens the distribution toward the top token; high temperature flattens it. As approaches 0, sampling becomes greedy decoding: always pick the highest-scoring token.
Many systems also apply top-p (nucleus) sampling: keep only the smallest set of top tokens whose probabilities add up to at least , then renormalise. With at , "blue" alone () is not enough, so "clear" is added (). "Falling" is dropped, and the survivors become and . This cuts off the long tail of unlikely tokens that can derail a sentence.
The training objective: cross-entropy
During pretraining the correct next token is known, because it is simply the next token in the text. The loss for one position is the cross-entropy, the negative log of the probability the model gave the correct token:
If the correct token was "blue" and the model gave it 0.766, the loss is . Had the model given it only 0.01, the loss would be . Confident mistakes are punished hard. Pretraining minimises the average of this loss over an enormous number of positions, using exactly the gradient descent described in the previous lesson.
A related number you will see in papers is perplexity, raised to the average cross-entropy. An average loss of 1.2 gives a perplexity of : on average the model is about as uncertain as if it were choosing evenly among 3.3 tokens. Lower is better.
Attention in one formula
Each token's vector is projected into three new vectors: a query (what this position is looking for), a key (what this position offers) and a value (the information it passes on). Stacking these for all positions into matrices , and , attention is
where is the length of the key vectors. Dividing by keeps the scores from growing so large that the softmax becomes all-or-nothing.
Worked example (made-up two-number vectors). The query for "it" is . The keys are trophy and suitcase , so .
- Dot products: and .
- Divide by : scores and .
- Softmax: and , giving weights and .
- If the values are trophy and suitcase , the output is .
The new representation of "it" is about three-quarters "trophy". In a language model each position may only attend to itself and earlier positions (a causal mask), because it must not peek at the tokens it is trying to predict. Real transformers run many of these attention calculations side by side (multi-head attention), each free to track a different kind of relationship.
Sampling in code
import numpy as np
def softmax(logits, temperature=1.0):
z = np.asarray(logits, dtype=float) / temperature
z = z - z.max() # subtract the max for numerical stability
e = np.exp(z)
return e / e.sum()
tokens = ["blue", "clear", "falling"]
logits = [2.0, 0.5, -0.5]
for T in (0.5, 1.0, 2.0):
p = softmax(logits, T)
print(f"T={T}: " + ", ".join(f"{t} {q:.3f}" for t, q in zip(tokens, p)))
rng = np.random.default_rng(0)
draws = rng.choice(tokens, size=1000, p=softmax(logits))
print({t: int((draws == t).sum()) for t in tokens})
The loop reproduces the temperature table. The last two lines draw 1,000 tokens at ; the counts come out close to 766, 171 and 63 (here 752, 188 and 60), which is why the same prompt gives different continuations.
Common pitfalls
- Expecting temperature 0 to mean "correct". It makes the choice more repeatable, not more accurate. The most likely token can still be wrong.
- Comparing token counts across models. Different tokenizers split the same text differently, so prices and limits per token are not directly comparable.
- Reading confident wording as calibrated confidence. The tone of a reply tells you little about the probability that it is right.
- Asking letter-level questions without tools. Because models see tokens rather than letters, counting characters or reversing words is surprisingly error-prone.
- Assuming everything in a long prompt is used equally well. Quality can drop when key facts are buried in very long contexts; put the important material clearly and close to the question.
- Using a base model as an assistant. Without instruction tuning it continues text rather than following instructions.
In practice
- Expect variation: if an answer matters, ask again or ask the model to check its own work.
- Use lower-temperature settings, where available, for factual or technical tasks, and higher for brainstorming.
- Give the model the source material (paste the document) instead of relying on its memory; it is far more accurate that way.
- Verify names, numbers, quotes and citations independently before you rely on them.
Key takeaways
- LLMs read and write tokens, word pieces that average about three-quarters of an English word.
- A model generates text one token at a time by predicting probabilities for the next token and choosing one.
- The transformer's attention mechanism lets each token draw on every relevant earlier token.
- Chatbots are built in stages: pretraining on large text collections, instruction tuning, then preference training such as RLHF.
- Sampling and temperature explain varied answers, and training for plausible text explains why models can hallucinate.
Terms in this lesson
- Large language model (LLM)
- A large neural network trained on text to predict the next token, used to understand and generate language.
- Token
- A chunk of text, often a word or part of a word, that a language model reads and writes.
- Tokenizer
- The component that splits text into tokens and converts them to numbers.
- Transformer
- The neural network design behind most modern language models, built around attention.
- Attention
- A mechanism that lets the model weigh how relevant each earlier token is when processing the current one.
- Pretraining
- The first, largest training stage, where a model learns to predict the next token over a huge body of text.
- Instruction tuning
- Further training on example instructions and good responses so the model behaves like an assistant.
- RLHF
- Reinforcement learning from human feedback: training a model toward responses that people ranked as better.
- Temperature
- A setting that controls how random the choice of the next token is.
- Sampling
- Choosing the next token at random according to the model's predicted probabilities.
- Logit
- The raw, unnormalised score a model assigns to each possible next token before softmax turns the scores into probabilities.
- Softmax
- A function that exponentiates a list of scores and divides by their sum, producing positive probabilities that add up to 1.
- Cross-entropy loss
- The negative logarithm of the probability a model assigned to the correct answer, averaged over examples; the standard training loss for language models.
Check your understanding
- 1.
Roughly how many tokens would a 750-word English article use?
- 2.
Why can the exact same prompt produce two different answers?
- 3.
What does a base model that has only been pretrained typically do when given a question?
- 4.
Two candidate tokens have logits 2 and 0. At temperature 1, roughly what probability does softmax give the first token?
- 5.
What happens to the next-token distribution when you raise the temperature from 0.5 to 2.0?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
You want a model to summarise a 3,000-word English report in about 600 words. Using the rule of thumb of about three-quarters of a word per token, estimate the input tokens, the output tokens and the total. Would it fit in an 8,000-token context window?
Show solution
Tokens ≈ words ÷ 0.75. Input: tokens. Output: tokens. Total ≈ 4,800 tokens (plus a few for instructions), which fits within 8,000. This is an estimate: technical text, code or other languages usually need more tokens per word.
- Exercise 2Core
Three tokens have logits . Compute their softmax probabilities at and at .
Show solution
At : , , ; total . Probabilities: , , .
At the logits become : , , ; total . Probabilities: , , .
Lowering the temperature moves probability away from the weaker token but cannot separate the two tied tokens; ties stay ties.
- Exercise 3Core
Coding. Write a function
top_p_sample(probs, p)that keeps the smallest set of most-likely tokens whose probabilities sum to at leastp, renormalises them and samples one. Test it on the probabilities[0.766, 0.171, 0.063]withp = 0.9.Show solution
import numpy as np def top_p_sample(probs, p=0.9, rng=None): rng = rng or np.random.default_rng() probs = np.asarray(probs, dtype=float) order = np.argsort(probs)[::-1] # most likely first cumulative = np.cumsum(probs[order]) cutoff = np.searchsorted(cumulative, p) + 1 # smallest set reaching p keep = order[:cutoff] kept = probs[keep] / probs[keep].sum() # renormalise return int(rng.choice(keep, p=kept)), keep, kept probs = [0.766, 0.171, 0.063] # blue, clear, falling idx, keep, kept = top_p_sample(probs, p=0.9, rng=np.random.default_rng(1)) print("kept tokens:", keep.tolist(), "renormalised:", kept.round(3).tolist())It prints
kept tokens: [0, 1] renormalised: [0.818, 0.182]. Sorting puts tokens in descending order; the cumulative sums are 0.766, 0.937, 1.0;searchsortedfinds the first position where the sum reaches 0.9 (index 1), and adding 1 converts that position into a count of tokens to keep. - Exercise 4Challenge
A query attends over three positions with keys , , and values equal to the keys. With , compute the attention weights and the output vector. Then explain in one or two sentences why the scaling by matters more as vectors get longer.
Show solution
Dot products: , , . Divide by : , , . Exponentials: , , ; total . Weights: , , (to three decimals).
Output (using unrounded weights ).
Scaling: if the entries of and are roughly independent with variance 1, their dot product has variance , so with long vectors (for example 128 entries) raw scores become large. Softmax of large scores puts nearly all weight on one position and its gradients become tiny, which makes training slow and unstable. Dividing by brings the variance back to about 1.
Further reading
- paperAshish Vaswani et al., Attention Is All You Need (2017)
- paperTom B. Brown et al., Language Models are Few-Shot Learners (2020)
- paperLong Ouyang et al., Training language models to follow instructions with human feedback (2022)
- bookDaniel Jurafsky and James H. Martin, Speech and Language Processing (3rd ed. draft)
Go further
Sources
Fact-checked and last reviewed 2026-11-05