How an LLM Writes: One Sampled Token at a Time
Follow the loop that turns a prompt into an answer: tokens in, a probability for every possible next token out, one token sampled and appended. See how pretraining and instruction tuning shape that loop, what temperature, top-k and top-p change, and why the same loop produces run-to-run variation, hallucinations and a knowledge cutoff.
Contentsand lesson path
On this page
- Why it matters
- Tokens in, one token out
- From text predictor to assistant
- Temperature, top-k and top-p
- What sampling explains
- Check your understanding
- Apply it
- Review prompt
Lessons of Tokens & Context
- How an LLM Writes: One Sampled Token at a Time Concept · 20 min
- Tokenizers in Practice: Counting Tokens and Cost Worked example · 15 min
- Context Engineering: What Goes In and How Much Concept · 15 min
- Lab: Trim a Conversation to Fit a Budget Lab · 25 min
- Long Inputs and Context Failure Modes Concept · 15 min
- Check: Generation and Context Budget Scenarios Knowledge check · 8 questions
What you will learn
- Explain how a pretrained, instruction-tuned LLM generates text by sampling one token at a time, how temperature, top-p and top-k change that sampling, and why this produces hallucinations, knowledge cutoffs and run-to-run variation.
- Count tokens for a prompt and response with a tokenizer and estimate the cost of a request.
01. Why it matters
When you call a large language model (LLM), you send text and get text back, so it is tempting to treat the model as a function that looks up answers. It is not. The model produces its reply one small piece at a time, and at every step it chooses the next piece from a list of candidates, each with a probability. Most of the behaviour that surprises new AI engineers follows from that design:
- the same prompt gives a different answer on the next run;
- a fluent, confident answer turns out to be invented;
- the model knows nothing about last month, and may not know what day it is;
- long answers are slower and cost more than long prompts.
This lesson builds the mental model the rest of the skill relies on. You will run a small sampler in Python to see what temperature, top-k and top-p do. Counting and pricing tokens comes in the next lesson.
02. Tokens in, one token out
Models do not read characters or words. A tokenizer splits the text into tokens, often whole common words ( order, with its leading space), parts of rarer words, digits or punctuation, and maps each one to an integer id. The set of all pieces is the vocabulary: about 200,000 entries for o200k_base, the encoding that tiktoken uses for OpenAI models from GPT-4o to the GPT-5 family. Every provider trains its own tokenizer, so the same text splits differently from model to model.
Given the ids of everything in its context, the model computes one score, called a logit, for every token in the vocabulary. A softmax turns the scores into probabilities that add up to 1. The decoder picks one token, appends it to the context, and the calculation runs again on the longer sequence, until the model emits an end-of-turn token or reaches the output limit you set.
context: [system] Be brief. [user] Capital of France? [assistant]
step 1 candidates: 'The' 0.48 | 'Paris' 0.41 | 'France' 0.06 ...
sampled 'Paris' -> appended to the context
step 2 candidates: '.' 0.71 | ' is' 0.18 | ',' 0.05 ...
sampled '.'
step 3 candidates: <end of turn> 0.93 | ' It' 0.04 ...
sampled <end of turn> -> generation stopsTwo practical consequences follow. First, the prompt can be processed in one parallel pass (often called prefill), but the answer has to be produced one token per pass (decode). That is why output tokens are slower than input tokens and why providers usually charge several times more for them. Second, every token the model writes becomes input for the next step. The model cannot go back and revise a token it has already emitted; it can only continue from it.
03. From text predictor to assistant
The loop is the same for every model. What differs is the set of weights that produce the scores, and those come from training in stages:
- Pretraining. The model learns to predict the next token on a very large collection of text and code. The result, a base model, is an excellent continuer of documents and nothing more. It has no notion of a question that deserves an answer.
- Instruction tuning. The base model is trained further on examples of instructions paired with good responses, written in a chat template: special tokens that mark where the system, user and assistant parts start and end. The model learns that text after the assistant marker should be a helpful reply that ends with an end-of-turn token.
- Preference tuning. People, or models trained on their judgements, compare alternative answers, and methods such as reinforcement learning from human feedback (RLHF) nudge the model towards the preferred ones. This shapes tone, helpfulness and refusals. Many recent models are also trained to write reasoning (thinking) tokens before the final answer.
Chat APIs render your messages into the template for you. Compare how the two kinds of model treat the same text:
Prompt: Write a haiku about rain.
Base model continues the document:
Write a haiku about snow.
Write a haiku about the sea.
Write a limerick about
Instruction-tuned model answers it:
Soft rain on the roof /
a kettle hums somewhere near /
grey street turns to glassInstruction tuning does not add a fact database or a truth checker. It changes which continuations are likely, so that the likely continuation of a question is an answer. Keep that in mind when we get to hallucinations.
04. Temperature, top-k and top-p
If the decoder always took the most likely token (greedy decoding), the output would be repeatable but often flat and repetitive. Most chat products therefore sample: they draw the next token at random, in proportion to the probabilities. Three settings reshape the distribution before the draw:
- Temperature divides every logit by a number T before the softmax. T below 1 widens the gaps, so likely tokens become more likely; T above 1 narrows them, so unlikely tokens get a real chance. As T approaches 0, sampling approaches greedy decoding.
- Top-k keeps only the k most likely tokens, sets the rest to zero and rescales the survivors so that they sum to 1.
- Top-p (nucleus sampling) keeps the smallest group of most likely tokens whose probabilities add up to at least p, then rescales. When the model is confident that group is tiny; when it is unsure the group grows.
The script below applies each setting to six invented logits for the token after "The best way to learn Python is". It needs Python 3.12 or later and NumPy (python -m pip install numpy); it was run with NumPy 2.5.
import numpy as np
# Invented scores (logits) for the token after "The best way to learn Python is"
TOKENS = [' to', ' by', ' practice', ' doing', ' reading', ' slowly']
LOGITS = np.array([3.2, 2.9, 2.0, 1.6, 0.8, -1.0])
def softmax(logits: np.ndarray, temperature: float = 1.0) -> np.ndarray:
scaled = logits / temperature
exp = np.exp(scaled - scaled.max()) # subtract the max for numerical stability
return exp / exp.sum()
def filter_top_k(probs: np.ndarray, k: int) -> np.ndarray:
keep = np.argsort(probs)[::-1][:k]
out = np.zeros_like(probs)
out[keep] = probs[keep]
return out / out.sum()
def filter_top_p(probs: np.ndarray, p: float) -> np.ndarray:
order = np.argsort(probs)[::-1]
cumulative = np.cumsum(probs[order])
cutoff = np.searchsorted(cumulative, p) + 1 # smallest set that reaches p
out = np.zeros_like(probs)
out[order[:cutoff]] = probs[order[:cutoff]]
return out / out.sum()
def show(label: str, probs: np.ndarray) -> None:
cells = [f'{t.strip()}={pr:.2f}' for t, pr in zip(TOKENS, probs) if pr > 0]
print(f'{label:<15}', ' '.join(cells))
if __name__ == '__main__':
show('T=1.0', softmax(LOGITS))
show('T=0.5', softmax(LOGITS, 0.5))
show('T=1.5', softmax(LOGITS, 1.5))
show('T=1.0 top-k=3', filter_top_k(softmax(LOGITS), 3))
show('T=1.0 top-p=0.9', filter_top_p(softmax(LOGITS), 0.9))
print('greedy picks:', TOKENS[int(np.argmax(LOGITS))].strip())python sampling.pyT=1.0 to=0.43 by=0.32 practice=0.13 doing=0.09 reading=0.04 slowly=0.01
T=0.5 to=0.59 by=0.32 practice=0.05 doing=0.02 reading=0.00 slowly=0.00
T=1.5 to=0.35 by=0.28 practice=0.16 doing=0.12 reading=0.07 slowly=0.02
T=1.0 top-k=3 to=0.49 by=0.36 practice=0.15
T=1.0 top-p=0.9 to=0.45 by=0.33 practice=0.13 doing=0.09
greedy picks: toAt T=0.5 the top two tokens take 91% of the probability and reading and slowly are practically gone; at T=1.5 the top two lose ground and every other token gains. Top-k=3 keeps three tokens, and top-p=0.9 keeps four, because the top three reach only about 0.87. Libraries usually apply temperature first and then the filters, but the order and defaults vary.
Whether you can set these values depends on the model. Local runtimes and many APIs expose them, with ranges that differ between providers. Some current hosted models, especially reasoning models, do not: recent Claude models, for example, reject a request that sets temperature, top_p or top_k, and you steer them with instructions instead. Check the model's parameter list first.
05. What sampling explains
This randomness explains run-to-run variation. Because each token is drawn at random, two runs can differ at any step, and once one token differs, every later token is computed from a different context. The next script shows this with a toy model, a table of next-token scores in place of a neural network. It generates ten answers at a low and a high temperature and counts the distinct ones. Save it next to sampling.py, whose softmax it reuses.
import numpy as np
from sampling import softmax
# A toy "model": scores for the next token, given only the previous token.
NEXT = {
'<start>': {'Write': 3.0, 'Build': 2.2, 'Read': 1.4},
'Write': {'small': 2.6, 'code': 1.9, 'tests': 1.2},
'Build': {'small': 2.4, 'a': 1.8},
'Read': {'code': 2.0, 'books': 1.5},
'small': {'scripts': 2.5, 'projects': 1.7},
'a': {'project': 2.6, 'game': 1.4},
'code': {'daily': 2.1, '<end>': 1.3},
'tests': {'first': 2.0, '<end>': 1.1},
'books': {'<end>': 1.0},
}
def generate(rng: np.random.Generator, temperature: float) -> str:
words, token = [], '<start>'
while token in NEXT: # tokens not in the table end the answer
candidates = list(NEXT[token])
probs = softmax(np.array(list(NEXT[token].values())), temperature)
token = str(rng.choice(candidates, p=probs))
if token != '<end>':
words.append(token)
return ' '.join(words)
rng = np.random.default_rng(seed=7)
for temperature in (0.2, 1.2):
answers = [generate(rng, temperature) for _ in range(10)]
print(f'T={temperature}: {len(set(answers))} distinct of 10')
for answer in sorted(set(answers)):
print(f' {answers.count(answer)} x {answer}')T=0.2: 2 distinct of 10
2 x Write code daily
8 x Write small scripts
T=1.2: 5 distinct of 10
2 x Build small scripts
1 x Write code daily
3 x Write small projects
1 x Write small scripts
3 x Write tests firstAt T=0.2 the toy model gives two distinct answers in ten runs; at T=1.2 it gives five, and two runs start with the less likely first token Build. A low temperature reduces variation but does not promise identical output from a hosted API: batching, GPU arithmetic and silent model updates can all change a token. Design for variation, and test with several runs rather than one.
A model can also hallucinate: state something false, fluently and with confidence. Training rewards a plausible continuation, not a true one, and the model has no separate store of facts to check against. When it knows a fact well, the true continuation is also the most probable. When it does not, the most probable continuation is still fluent and specific: a realistic paper title, a believable version number. Sampling can also pick a less likely wrong token, and because the model never revises what it has emitted, the tokens after it build a consistent story around the mistake.
The knowledge cutoff adds a second limit. The weights are frozen when training ends, so the model knows only what its training data contained up to a cutoff date, and the last months before it are usually thin. It does not know today's date unless you tell it. Asked about later events, it can only produce a plausible continuation: a hallucination by another route. The remedy for both is to put the facts the answer needs into the context, from your data, retrieval or tools. The rest of this skill is about doing that within a token budget.
06. Check your understanding
07. Apply it
Start the second half of this skill's practice project, the temperature experiment: first with the toy model, then with a real one.
- Run
generate.pywith three different seeds and record the number of distinct answers at T=0.2 and T=1.2 for each. Then applyfilter_top_pfromsampling.pyinsidegenerateand see how p=0.5 changes the counts at T=1.2. - Choose a model that accepts a temperature setting, such as an open-weight model run locally with Ollama or llama.cpp, or a hosted model whose documentation lists the parameter. Keep any API key in an environment variable.
- Send one open-ended prompt, for example "Suggest a name for a bakery that only sells bread. Reply with the name only.", ten times at 0.2 and ten times at 1.0.
- Normalise the answers (strip punctuation, lower-case), count the distinct ones for each setting, and record the model, the settings and the counts.
If you have not called a model from code yet, do step 1 now and steps 2 to 4 after the next skill, which covers it.
08. Review prompt
Without looking back, draw the generation loop as a cycle with four labelled steps, from tokens in to a token appended. Then explain in one sentence each what temperature, top-k and top-p do to the candidate list, and what a base model does with a question that an instruction-tuned model would answer. Finish with one cause each for run-to-run variation, hallucination and the knowledge cutoff.
References
- Hugging Face LLM Course: Deep dive into text generation inference with LLMs
- Hugging Face LLM Course: Tokenizers
- Hugging Face blog: How to generate text with different decoding methods
- Hugging Face Transformers: Generation strategies
- The Curious Case of Neural Text Degeneration (Holtzman et al., nucleus sampling)
- Training language models to follow instructions with human feedback (Ouyang et al.)
- Ollama: Modelfile parameters (temperature, top_k, top_p)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.