g↗genai/ learner
How GenAI works / Lesson 09

Temperature and sampling

Ask the same question twice and you can get two different answers. A setting called temperature controls how much room the model gives to its less likely choices. It does not control whether the answer is right.

Concept + interactive labBeginner friendly

The model scores choices; sampling picks one.

At each step, a language model produces a score for every possible next token, and those scores become a probability for each candidate, as in the lesson on predicting the next token. The model does not hand back one word. The application then has to choose a token from that spread, and that choice is called sampling.

There are two simple ways to choose. Greedy decoding always takes the highest-probability token, so the same prompt tends to give the same text. Random sampling draws a token in proportion to its probability, so a 40 percent candidate is picked about four times in ten and a 2 percent candidate sometimes appears. Temperature is a dial between the two.

Key idea: temperature reshapes the spread of probabilities before a token is drawn. A lower value concentrates probability on the top choices, and a higher value flattens it. The model’s underlying scores are the same either way.
A prompt flows through a fixed network to token scores, then temperature reshapes probabilities, top-k or top-p filters candidates, and a sampler picks a token. Lower panels compare temperature, top-k, and top-p, with a ranked-menu analogy and key takeaways.
Overview of how sampling settings shape a next-token choice.

Where temperature sits: after the network, before the pick.

To see what temperature changes, it helps to see where it acts. A language model is a neural network. Given the text so far, its layers turn it into a final set of numbers: one raw score for every token in the model’s vocabulary, which can run to tens of thousands of tokens or more. Those raw scores are called logits. They are not probabilities: they can be negative, and they do not add up to anything in particular.

Everything up to the logits is the trained network, and its weights are fixed while you use it. Temperature is not part of that network. It is a step applied to the logits afterwards, at generation time: divide every logit by the temperature, then turn the results into probabilities with softmax, then optionally trim and pick. Because the network is untouched, you can change the setting on every request without retraining anything, and it does not change how much work the network does.

Inside the network (trained, weights fixed)

  1. Your text becomes tokens
  2. Layers of the network process the tokens
  3. The final layer outputs one logit per vocabulary token

Sampling step (settings you choose)

  1. Temperature: divide each logit by T
  2. Softmax: turn the scaled logits into probabilities
  3. Top-k / top-p: optionally drop candidates
  4. Pick one token at random from what is left

The chosen token is added to the text, and the network produces a fresh set of logits for the next position, conditioned on everything so far. Implementations typically reuse earlier computation rather than reprocess all the text. This repeats for every token generated.

Here are the lab’s invented logits for the prompt “The capital of Australia is …” at two temperatures. The ranking never changes. Dividing by a smaller temperature stretches the gaps between logits, and softmax turns bigger gaps into more lopsided probabilities.

Invented logits, scaled logits and probabilities at temperature 1 and temperature 0.5
CandidateLogitChance at T = 1Logit ÷ 0.5Chance at T = 0.5
Sydney2.651.0%5.266.9%
Canberra2.234.2%4.430.1%
Melbourne1.010.3%2.02.7%
Perth-0.23.1%-0.40.2%
Auckland-1.01.4%-2.0<0.1%

The logits are invented for teaching. Real logits come from a trained network, and their scale and spread differ between models and prompts, so a given temperature does not mean the same thing across models.

Key idea: temperature is a post-processing step on the network’s output scores. It does not make the network know more or less. It only changes how the same scores are turned into a choice.

Three settings, three different jobs.

Picture the model’s next-token probabilities as a row of bars: the taller the bar, the more likely that token. Three common settings change how a token is picked from that row. One reshapes every bar, and the other two remove bars. The pictures are schematic, so the bars show the idea and are not real model data.

Temperature: reshape every bar

Think of a dial between cautious and adventurous. Turn it down and the tall bar gets taller while the short ones shrink, so the favourite wins almost every time. Turn it up and the bars even out, so underdogs get a real chance. Nothing is removed: at any setting above zero, every candidate keeps some probability, even if it is tiny.

Three panels showing the same six probability bars. At low temperature one bar is very tall and the other five are tiny. At medium temperature the bars slope gently down from left to right. At high temperature all six bars are almost the same height.
Same candidates, three temperatures. Schematic, not real data.

Top-k: keep a fixed number of candidates

Sort the candidates from most to least likely, keep the first k, drop the rest, and rescale the survivors so they add up to 100 percent again. It cuts off the long tail of strange options. Because it counts by rank, k = 3 keeps three candidates even if the third is very unlikely, and even if the first is already close to certain.

Eight probability bars sorted from tallest to shortest. The first three are solid and labelled kept. The last five are faded and labelled dropped. A dashed line between the third and fourth bars is tagged k equals 3.
Top-k with k = 3: the first three are kept, the rest are dropped. Schematic.

Top-p: keep enough candidates to cover a share

Also called nucleus sampling. Start from the most likely candidate and keep adding candidates until their probabilities add up to at least p, for example 80 percent. Drop the rest and rescale. The number kept adapts to the situation: when the model is confident, a couple of candidates already cover 80 percent, and when it is unsure, many are needed. In the lab at temperature 1, an 80 percent top-p keeps 2 of 5 candidates for the factual prompt and 4 of 8 for the story line, while top-k with k = 3 keeps 3 either way.

Eight probability bars sorted from tallest to shortest. A strip above fills from the left to a marker labelled 80 percent, reached after the fourth bar. The first four bars are solid and labelled kept. The last four are faded and labelled dropped, separated by a dashed line.
Top-p with p = 80%: bars are added until the running total reaches the target. Schematic.
Key idea: temperature changes how big each bar is. Top-k and top-p change which bars are allowed to be picked at all.

Turn the temperature dial.

Start with the story line and move the temperature from 0 to 2. Watch the bars and the twenty draws. Then switch to the factual prompt, drop the temperature to 0.2, and see which answer becomes nearly certain. Finally try the top-k and top-p options to see choices removed from the list.

01 / Change how adventurous the pick isSIMULATION
Prompt

The lighthouse keeper opened the …

Several continuations are fine here. There is no single right word.

Then trim the list
Probability of each candidate next word, and how many of the 20 draws picked it
CandidateInvented logitChance of being pickedOf 20 draws
door2.040%7
lantern1.421.9%7
window1.014.7%2
logbook0.69.9%1
hatch0.26.6%0
storm-0.34%1
ocean-0.92.2%1
sandwich-2.00.7%1

Choices that actually get picked: 7 of 8.

Everything here is invented: the candidate words, their scores, and the idea that the model ranks a common mix-up just above the correct answer. The “draws” come from a seeded random generator, so they repeat until you press Draw again. The arithmetic is the real part: dividing scores by the temperature, converting them to probabilities with softmax, then optionally trimming with top-k or top-p, is how common sampling settings are described. This is a toy, not a live model, and no provider’s exact implementation. Names, ranges and defaults for these settings differ between providers and models.

What the dial does to the scores.

  1. Divide. Each candidate’s raw score (its logit) is divided by the temperature. Below 1 this stretches the gaps between scores. Above 1 it shrinks them.
  2. Convert. A function called softmax turns the adjusted scores into probabilities that add up to 100 percent. The ranking never changes: the candidate with the top score stays on top at every temperature, and only the gaps change.
  3. Optionally trim. Top-k keeps only the k most likely candidates. Top-p (also called nucleus sampling) keeps the smallest group whose probabilities add up to p. The rest are dropped and the survivors are rescaled to add up to 100 percent again.
  4. Draw. One token is picked at random using the remaining probabilities, then the process repeats for the next position.

A temperature of exactly 0 cannot be divided by, so systems treat it as greedy decoding. In practice, low temperatures make output more consistent, though identical results on every run are often not guaranteed, because other details of how a service runs the model can differ. High temperatures give rarer tokens a real chance. Because each token is conditioned on the ones before it, one unlikely pick can send the rest of the text somewhere unusual. The lab draws single tokens, so it shows how a rare choice like “sandwich” becomes possible, not how it carries forward.

Which values are allowed, which defaults apply, and whether you can change these settings at all vary between providers and models, so read the documentation for the one you use.

Real systems often mix them.

These settings are not alternatives you must pick between. Many libraries and APIs let you set temperature together with top-k, top-p, or both, and the steps then run one after another, roughly as in the picture: scores, then temperature, then the trims, then one random pick.

A left-to-right pipeline of five cards joined by arrows: Scores, Temperature, Top-k, Top-p and Pick one. Each card shows a small bar chart. The temperature card flattens the bars, the top-k and top-p cards fade the right-hand bars, and the last card shows a die landing on one bar. A caption reads: Settings can be combined.
One possible pipeline. Real systems differ in which steps exist and in their order. Schematic.
  • Order matters. Top-p adds up probabilities, so applying temperature first changes how many candidates are needed to reach p: a lower temperature concentrates probability and keeps fewer. The lab applies temperature first and then the trim. That is a simplification, not any provider’s documented pipeline.
  • Systems differ. Some offer top-p but not top-k, or the reverse. Defaults, allowed ranges and whether several settings can be used together vary, and some documentation suggests changing only one at a time because their effects overlap.
  • Start simple. A reasonable habit is to change one dial, look at the output, and add a second only for a specific problem. For example, add a trim if rare odd words still slip in at a higher temperature.

Temperature is not a truth or safety setting.

The factual prompt in the lab shows the trap. When the model’s top choice is wrong, lowering the temperature makes it wrong more reliably. Raising it from near zero gives the right answer a real chance, but flattening also feeds the poorer choices: in this lab the chance of Canberra peaks around 0.8 to 1.0 and then slowly falls. Neither direction adds knowledge or reliably improves accuracy, which is why the previous lessons on making things up and on knowledge cutoffs point to sources and checks instead.

  • Low is for consistency. Extraction, classification and formats that must be repeatable usually benefit, but the output can still be wrong, and wrong the same way each time.
  • Higher is for variety. Brainstorming and creative drafts benefit from a wider spread. Very high values often produce incoherent text.
  • Safety is separate. Temperature does not decide what a model is willing to say or whether an action is permitted. That comes from training and from the controls an application adds.
Habit: choose temperature for the amount of variety you want, and verify facts by other means.
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

A team sets temperature to 0 for a question-answering feature because they want correct answers. What is the best description of what that achieves?
THE TAKEAWAY

Take this with you.

Temperature divides the model’s scores to flatten or sharpen the spread of next-token choices, and top-k and top-p trim it before one token is drawn. Use lower values for consistency and higher values for variety. Neither one measures correctness, so check facts separately.

Review: How a model predicts the next token →