Temperature and Randomness

Updated · 5 min read
mediumPython 3.13aillmtemperaturesamplingbeginnersinterview

Why did the assistant give a different answer the second time? Srihitha asks for a tagline for her team's project, gets one she likes, asks again, and gets a completely different one. Nothing broke. LLMs usually pick the next token with a little randomness, and a setting called temperature controls how much.

This lesson shows how temperature changes the choice of the next token, with real numbers from Python.

Picking the Next Token

In "How an LLM Generates Text", the model always took the most likely token. Most apps instead sample: they pick a token at random, but weighted by its probability, so likely tokens win most of the time and less likely ones sometimes. Temperature reshapes those probabilities before the pick.

The same choice at three temperatures
TemperatureEffectGood for
Low (near 0)The top token wins almost every time: focused and repeatableFacts, code, data extraction
Medium (around 1)Likely tokens usually win, with some varietyEveryday writing
High (above 1)Probabilities flatten: more surprising choices, more mistakesBrainstorming, creative ideas

Temperature in Python

This program turns the model's scores for four fruits into probabilities at three temperatures, then samples six picks at each:

Python
import math
import random
 
# How strongly a model favors each next word after "My favorite fruit is"
scores = {"apple": 2.0, "mango": 1.5, "banana": 1.0, "orange": 0.5}
 
def probabilities(temperature):
    weights = {w: math.exp(s / temperature) for w, s in scores.items()}
    total = sum(weights.values())
    return {w: v / total for w, v in weights.items()}
 
for t in [0.2, 1.0, 2.0]:
    p = probabilities(t)
    random.seed(1)
    picks = random.choices(list(p), weights=list(p.values()), k=6)
    print(f"T={t}:", {w: f"{v:.0%}" for w, v in p.items()}, "->", " ".join(picks))
Output
T=0.2: {'apple': '92%', 'mango': '8%', 'banana': '1%', 'orange': '0%'} -> apple apple apple apple apple apple
T=1.0: {'apple': '46%', 'mango': '28%', 'banana': '17%', 'orange': '10%'} -> apple banana banana apple mango apple
T=2.0: {'apple': '35%', 'mango': '27%', 'banana': '21%', 'orange': '17%'} -> apple orange banana apple mango mango

Dividing the scores by a small temperature exaggerates the gaps; dividing by a large one shrinks them. Real models do this over about 200,000 tokens at every step, and many apps also limit the pick to the top few tokens (settings often called top-k or top-p).

Common Mistakes

Thinking temperature 0 guarantees the same answer every time. It makes answers far more repeatable, but small differences can still happen in practice.

Thinking low temperature means correct. A model can be confidently and repeatably wrong.

Using high temperature for facts or code. More randomness means more chances to go wrong.

Interview Corner

What does temperature do in an LLM?

It controls how random the choice of the next token is. Low temperature makes the most likely token win almost every time, for focused, repeatable output; high temperature flattens the probabilities, for more varied and creative output.

Why does the same prompt give different answers?

Because tokens are usually sampled with some randomness, so different runs can pick different tokens, and each choice changes everything after it.

Practice

Exercise: change the temperature. Run the program, then add 0.5 and 5.0 to the list of temperatures. At which temperature does "orange" first appear in the picks? Then change the seed and run again, and describe what changes and what doesn't.

Check your understanding:

  1. What does a low temperature do to the probabilities?
  2. Which temperature would you choose for extracting dates from a document, and why?
  3. Why can a model be repeatably wrong at low temperature?

Quick check: temperature

4 questions
1What does a higher temperature do?
2At temperature 0.2, what did six picks give in the example?
3Which task suits a low temperature?
4Does a low temperature make answers correct?

Key Takeaways

Quick reference

TermMeaning
SamplingPicking the next token at random, weighted by probability
TemperatureA setting that controls how random sampling is
Top-k / top-pSettings that limit sampling to the most likely tokens

Was this tutorial helpful?

Lesson 32 of 186