How language models generate text: sampling and temperature
Run autoregressive generation with different temperatures and sampling settings and explain why models produce unsupported claims.
By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.
In short
A language model writes text one token at a time: it scores every possible next token, a decoding rule picks one, and the choice is appended and fed back in. Settings such as temperature, top-k and top-p change how that pick is made, trading predictability for variety. Because the model only predicts likely text, it can produce fluent claims that nothing supports.
Think of it like this: It is like a very well-read friend finishing your sentence: usually sensible, sometimes confidently wrong, and with no notes to check against.
Explained simply
A language model does one thing over and over: it looks at the text so far and guesses the next token. A token is a word or a piece of a word. After picking a token, it adds it to the text and guesses again, until it reaches a stop signal or a length limit.
For each guess the model gives every token in its vocabulary a score. Those scores become probabilities. The rule that turns probabilities into an actual choice is called decoding, and it has a big effect on how the text reads.
Temperature is the best-known setting. Low temperature makes the model stick to its safest choices, which suits factual or structured tasks. Higher temperature lets less likely tokens through, which gives more variety for brainstorming but also more mistakes.
The model has no built-in fact checker. It learned patterns of language, not a database of truths, so it can write a confident sentence about a book that does not exist. Knowing why this happens helps you design around it.
Press Play on a diagram to walk through it one step at a time.
- 1Context
Prompt plus tokens generated so far
- 2Forward pass
Model outputs a score (logit) per vocabulary token
- 3Shape the distribution
Apply temperature, then top-k or top-p filtering
- 4Pick a token
Greedy takes the best; sampling draws at random
- 5Append
Stop at an end token or max_new_tokens
- Back to step 1
- Always the most likely token
- Same output every time
- Can loop or repeat itself
- Sample from the k best tokens
- Fixed shortlist size
- k=1 equals greedy
- Smallest set whose probability sums to p
- Shortlist size adapts
- p around 0.9 is common
- Extraction or classification
- Greedy or temperature near 0
- Short max_new_tokens
- Validate against a schema
- Factual question answering
- Low temperature
- Supply sources in the prompt
- Allow I do not know
- Creative writing or ideas
- Temperature 0.7 to 1.0
- top_p around 0.9
- Generate several options
- Code
- Low temperature
- Run tests on the output
In depth
From logits to a chosen token
At each step the model outputs a vector of logits, one raw score per vocabulary entry; GPT-2 has 50,257 of them. Softmax turns logits into probabilities that sum to 1. Greedy decoding takes the highest probability. Sampling draws a token at random in proportion to the probabilities, so likely tokens win most of the time but not always.
Greedy decoding is repeatable and good for short, constrained answers, but on longer text it tends to fall into loops such as repeating the same sentence. Beam search keeps several candidate sequences and picks the best overall; it is common for translation and summarisation but less so for open-ended chat. In Hugging Face Transformers, generate() is greedy unless you pass do_sample=True or the model's saved generation config turns sampling on.
- Greedy: do_sample=False
- Sampling: do_sample=True with temperature, top_k, top_p
- Beam search: num_beams greater than 1
- Always set max_new_tokens to cap output length
Temperature, top-k and top-p together
Temperature divides every logit before softmax. With temperature 0.5 the gaps between scores double, so the top token dominates. With 1.0 nothing changes. With 1.5 the distribution flattens and unlikely tokens get a real chance.
Top-k keeps only the k highest tokens and renormalises; in Transformers the default top_k is 50 when sampling. Top-p, or nucleus sampling, sorts tokens by probability and keeps the smallest set whose total reaches p, such as 0.9. When the model is confident that set may be two tokens; when it is unsure it may be hundreds. These filters cut off the long tail of odd tokens that cause nonsense. Common starting points are temperature 0.7 with top_p 0.9 for creative text, and greedy or a low temperature for extraction and classification.
- 1Logits
One score per vocabulary token
- 2Temperature
Divide every logit by T
- 3Top-k and top-p
Drop tokens outside the shortlist
- 4Softmax
Renormalise what is left
- 5Draw
Random pick weighted by probability
Working within the context window
The context window is the maximum number of tokens the model can attend to, counting both the prompt and the generated output. GPT-2 has 1,024; current hosted models range from tens of thousands to around a million or more. Text beyond the window is simply not seen. Libraries may truncate silently or raise an error.
Even within the window, longer prompts cost more time and money, and models can make less use of details buried in the middle of very long inputs. Practical habits: measure prompts with the model's own tokeniser, reserve room for the answer, put the instruction and the most important material where it is easy to find, and retrieve only the relevant passages instead of pasting whole documents.
Why models produce unsupported claims
A language model is trained to continue text in a way that looks like its training data. It stores patterns, not a list of checked facts with sources. When a question touches something rare, recent, private or ambiguous, the most fluent continuation may simply be invented, such as a plausible but fake citation, product number or quote.
Several things make it worse: questions about events after the training data was collected, prompts that assume a false premise, high temperature, and asking for precise details such as numbers and names. Defences live outside the model. Supply the source text and ask the model to answer only from it, let it say I do not know, ask for quotes you can check, and test with questions whose answers you already have.
- Ground answers in supplied documents
- Allow and reward abstaining
- Lower temperature for factual tasks
- Verify names, numbers and citations automatically or by hand
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Follow autoregressive decoding~35m
- 2Compare greedy, top-k and top-p sampling~35m
- 3Adjust temperature~35m
- 4Work within the context window~35m
- 5Explain unsupported claims~35m
Key points
- The model outputs a probability for every token; decoding decides which one to use.
- Temperature divides the logits: below 1 sharpens choices, above 1 flattens them.
- The context window caps prompt plus output tokens; anything beyond it is invisible to the model.
- Fluent output is not evidence: models predict plausible text, not checked facts.
- Ground answers in supplied sources and evaluate them when accuracy matters.
Key terms
Tap a card to flip it. 0/6 known
Examples
import torch
logits = torch.tensor([2.0, 1.0, 0.5, -1.0])
for t in [0.5, 1.0, 2.0]:
probs = torch.softmax(logits / t, dim=-1)
print(t, probs.round(decimals=2).tolist())Lower temperature piles probability on the top token; higher temperature spreads it out.
Comparing decoding settings with GPT-2 on a CPU
Prerequisites: pip install torch transformers. GPT-2 small has about 124 million parameters, a download of roughly 500 MB, and runs on a laptop CPU. Step 1: load the model and tokeniser. Step 2: generate 30 new tokens greedily, then with sampling at temperatures 0.7 and 1.5. Step 3: run the sampling lines twice. Expected evidence: greedy output is identical every run and may repeat itself; temperature 0.7 varies but stays on topic; 1.5 drifts into odd words. Cleanup: remove the model from the Hugging Face cache folder if you need the disk space.
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
inputs = tok("The best way to learn statistics is", return_tensors="pt")
set_seed(0)
for kw in [dict(do_sample=False), dict(do_sample=True, temperature=0.7, top_p=0.9),
dict(do_sample=True, temperature=1.5)]:
out = model.generate(**inputs, max_new_tokens=30, pad_token_id=tok.eos_token_id, **kw)
print(kw, tok.decode(out[0], skip_special_tokens=True), sep="\n")Catching an invented citation
A support assistant was asked for the regulation that requires a 14-day refund window and answered with a confident but non-existent clause number. Step 1: the team collected 40 questions with known answers, including 10 where the honest answer is that no such rule exists. Step 2: they added the policy text to the prompt with an instruction to answer only from it and to reply not covered when it was silent. Step 3: they lowered temperature to 0.2. Step 4: an automatic check compared any quoted text with the policy. Invented references disappeared on the test set, and the remaining errors were logged for review.
Quick reference
- Generation loop: score all tokens, shape the distribution, pick one, append, repeat
- Temperature below 1 sharpens, above 1 flattens; near 0 behaves like greedy
- top_k keeps k tokens; top_p keeps the smallest set reaching probability p
- Greedy is repeatable, not more truthful
- Context window = prompt tokens + output tokens
- Always set max_new_tokens; GPT-2 can see at most 1,024 tokens
- Reduce unsupported claims with sources, abstention and checks, not with settings alone
Common mistakes
- Using high temperature for tasks with one right answer, such as extraction or classification.
- Expecting temperature 0 or greedy decoding to make answers correct; it only makes them repeatable.
- Pasting long documents past the context window and assuming the model saw all of them.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Given logits [2.0, 1.0, 0.1], print the softmax probabilities at temperatures 0.2, 1.0 and 3.0 and describe the trend.
- Exercise 2medium
Implement top-p filtering by hand: given a probability vector and p, keep the smallest set of tokens reaching p, renormalise, and sample one token.
- Exercise 3hard
Write a small factuality check: 10 questions with known answers (5 answerable from a short text you supply, 5 not). Run GPT-2 or any local model greedily with and without the text in the prompt and count answers that contain the expected string or the word unknown.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What temperature should I use?
- For extraction, classification and code, use 0 or close to it. For creative writing or brainstorming, 0.7 to 1.0 is a common start. Test on your own examples, because the best value differs between models.
- Does temperature 0 make a model accurate?
- No. It makes output more repeatable by always picking the most likely token, but the most likely token can still be wrong.
- Why do I get different answers to the same prompt?
- Sampling draws tokens at random, so each run can differ. Hosted services may also vary slightly even at temperature 0 because of how they batch and compute requests.
- Are hallucinations a bug that will be fixed?
- They follow from how language models work, so they are reduced rather than eliminated. Better models make fewer, but grounding, abstention and checks remain necessary.