Learning path: Prompt and Context Engineering · Step 1 of 8
Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
A model scores every next word, softmax turns the scores into probabilities and one word is drawn. See what temperature and top-p do to that draw with six words, plain numpy and 1000 draws.
What you will learn
- Turn next-word scores (logits) into probabilities with softmax
- Explain how temperature sharpens or flattens the probabilities before the draw
- Apply top-p to cut off the unlikely tail and rescale the words that survive
- Pick sampling settings for extraction, replies, creative work and evals
Before you start
- Basic Python and numpy
- What an LLM Can and Cannot Do
Send the same prompt to a model twice and you can get two different answers. Sometimes that's exactly what you want, and sometimes it breaks your app. To control it, you need to know where the difference comes from.
Picture a jar of coloured marbles, where each colour is a word. For the next word, the model fills the jar: lots of green marbles for coffee, fewer blue ones for beans, and just one or two for the rare words. Then one marble is drawn at random. This time it's blue, beans. Draw again and you might get coffee.
Temperature is like shaking up how many marbles of the rare colours there are. Top-p throws the rarest colours out of the jar before you draw. Same jar, different draw, different answer.
Everything below runs with plain numpy. No model, no API key.
The model scores every next word
Our prompt is "Our coffee shop tagline: Fresh ..." and we want the next word. For every possible next word, the model gives a score. These scores are called logits. Here we use six candidates with scores from 3.0 down to -0.5.
To be clear: these are hand-made scores for teaching, not from a real model. A real model scores every token it knows, tens of thousands of them. (If tokens are new to you, see LLM Tokens, Context Windows and Cost.)
"""Prompt: "Our coffee shop tagline: Fresh ..." - the next word.
Hand-made scores (logits) for six candidates, not from a model."""
import numpy as np
WORDS = ["coffee", "beans", "mornings", "brew", "starts", "ideas"]
LOGITS = np.array([3.0, 2.2, 1.6, 1.0, 0.2, -0.5])
def softmax(scores, temperature=1.0):
z = scores / temperature
e = np.exp(z - z.max()) # minus max: no overflow
return e / e.sum()
That's words.py. Read softmax line by line:
scores / temperaturedivides the scores by the temperature. Keep an eye on this line, because it is the whole trick of temperature.np.expmakes every score positive. Subtracting the max first just keeps the numbers from overflowing.- Dividing by the sum makes the results add up to 1. Now they are probabilities.
Scores in, probabilities out
"""Scores in, probabilities out."""
from words import WORDS, LOGITS, softmax
probs = softmax(LOGITS)
for word, score, p in zip(WORDS, LOGITS, probs):
print(f"{word:9} score {score:5.1f} prob {p:.3f}")
print("sum of probs:", round(probs.sum(), 3))
coffee score 3.0 prob 0.520
beans score 2.2 prob 0.234
mornings score 1.6 prob 0.128
brew score 1.0 prob 0.070
starts score 0.2 prob 0.032
ideas score -0.5 prob 0.016
sum of probs: 1.0
coffee gets 0.520, beans 0.234, and the rare words just a few hundredths. All six words still have a chance, and the probabilities add up to 1. This is the jar.
Temperature sharpens or flattens
Now we draw from the jar. The script below makes a random generator with a fixed seed, 42, so you get the same counts when you run it. It loops over three temperatures with the same scores, and for each one rng.choice draws 1000 words with exactly those probabilities.
"""Temperature reshapes the probabilities before we draw."""
import numpy as np
from words import WORDS, LOGITS, softmax
rng = np.random.default_rng(42)
for t in (0.2, 1.0, 1.5):
probs = softmax(LOGITS, temperature=t)
print(f"T={t}:", " ".join(f"{w} {p:.2f}" for w, p in
zip(WORDS, probs)))
draws = rng.choice(WORDS, size=1000, p=probs)
print(" 1000 draws, 'coffee':", (draws == "coffee").sum(),
" different words:", len(set(draws)))
T=0.2: coffee 0.98 beans 0.02 mornings 0.00 brew 0.00 starts 0.00 ideas 0.00
1000 draws, 'coffee': 979 different words: 3
T=1.0: coffee 0.52 beans 0.23 mornings 0.13 brew 0.07 starts 0.03 ideas 0.02
1000 draws, 'coffee': 521 different words: 6
T=1.5: coffee 0.40 beans 0.24 mornings 0.16 brew 0.11 starts 0.06 ideas 0.04
1000 draws, 'coffee': 406 different words: 6
Read the three runs:
- T = 0.2. Dividing by a small number stretches the scores apart. coffee jumps to 0.98 and came up 979 times in 1000 draws. Only three different words showed up at all.
- T = 1.0. Dividing by 1 changes nothing: the original 0.52. coffee came up 521 times.
- T = 1.5. The scores are squeezed together. coffee drops to 0.40, the rare words get a real share, and all six words appeared. coffee came up 406 times.
The prompt never changed. Only the shape of the jar did. Low temperature almost always gives the top word; high temperature gives the rare words a real chance.
Top-p keeps the likely words only
Top-p works differently. Put the probabilities end to end, most likely first, and keep a running total. Pick a value for p, here 0.9. Keep words until the running total reaches p, and drop everything after that.
"""Top-p: keep the smallest set of words that covers p."""
import numpy as np
from words import WORDS, LOGITS, softmax
probs = softmax(LOGITS)
order = np.argsort(-probs) # most likely first
running = np.cumsum(probs[order])
keep = order[: np.searchsorted(running, 0.9) + 1]
print("running total:", np.round(running, 3))
print("kept:", [WORDS[i] for i in keep])
kept = probs[keep] / probs[keep].sum() # renormalize
for i, p in zip(keep, kept):
print(f" {WORDS[i]:9} {p:.3f}")
running total: [0.52 0.754 0.882 0.953 0.984 1. ]
kept: ['coffee', 'beans', 'mornings', 'brew']
coffee 0.546
beans 0.245
mornings 0.135
brew 0.074
np.argsort(-probs)orders the words, most likely first.np.cumsumgives the running total: 0.52, 0.754, 0.882, 0.953 and so on.np.searchsortedfinds where the total crosses 0.9, and we keep everything up to there. 0.882 is not enough yet, so brew joins and the kept words cover 0.953.- Last, we rescale the survivors so they add up to 1 again. coffee goes from 0.520 to 0.546, and the draw happens from these four words only.
So top-p cuts off the long tail of unlikely words, but it keeps the variety among the good ones. Temperature changes the shape of the whole jar; top-p removes the rare marbles from it.
When do you want variety?
| Task | Setting | Why |
|---|---|---|
| Extract fields, classify a ticket | temperature 0 or close | one right answer: take the top word |
| Help-desk reply, summary | low to medium | natural wording, same facts |
| Taglines, ideas, names | higher, maybe top-p | you want different options |
| Tests and evals | fixed settings, many runs | measure the spread, not one lucky answer |
The last row matters more than it looks. If the output can change from run to run, one passing run proves very little. Keep the settings fixed and run each case several times, as in LLM Regression Testing in CI.
Change one knob at a time. If you move temperature and top-p together, you can't tell which one changed the output. Defaults and allowed ranges differ by provider, so check its documentation before you pick numbers.
Common mistakes
- Expecting the same answer twice with a medium or high temperature. Different draws are the model working as designed.
- Using a high temperature for extraction or classification. There is one right answer; extra variety only adds wrong ones.
- Judging a prompt on one run. At any temperature above zero you see one draw from the jar, not the jar.
- Turning both knobs at once, then guessing which one helped.
- Copying numbers from another provider. Ranges and defaults are not the same everywhere.
Quick recap
| Idea | What it does | In our example |
|---|---|---|
| Logits | one score per possible next word | 3.0 down to -0.5 for six words |
| Softmax | scores to probabilities that add up to 1 | coffee 0.520, beans 0.234 |
| Low temperature | sharpens: the top word almost always wins | T=0.2: coffee 979 of 1000, 3 words |
| High temperature | flattens: rare words get a real share | T=1.5: coffee 406 of 1000, 6 words |
| Top-p | keeps the words covering p, drops the tail | p=0.9 keeps 4 words, coffee rescaled to 0.546 |
Try it yourself
- In
02_temperature.py, add 0.01 and 5 to the temperatures. (Our smallsoftmaxdivides by the temperature, so 0.01 stands in for "close to zero".) - In
03_top_p.py, change 0.9 to 0.5. How many words survive? - In
words.py, give ideas a score of 3.5 and rerun all three scripts.
The three scripts, a README and sample prompts are in the StudyEasy AI Community, free to join.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.