Softmax and Temperature

Turn a model's scores into chances with softmax, then turn the temperature down and up to watch its answers become surer or more adventurous.

AI · beginner · 8 min · 16 steps · free

What you'll learn

temperature.py

import math

# The model has scored three possible next words. Bigger score, better fit.
words = ["tea", "cake", "soup"]
scores = [2.0, 1.0, 0.5]

# Softmax turns scores into chances that add up to 1. Temperature decides how sure it sounds.
for temperature in [1.0, 0.5, 2.0]:
    powered = [math.exp(s / temperature) for s in scores]
    chances = [round(p / sum(powered), 2) for p in powered]
    print("temperature", temperature, "->", chances)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. Three possible next words.
  3. The model's scores for them. Scores can be any numbers, even negative, so they are not chances yet.
  4. Try three temperatures. First 1.0: the scores as they are.
  5. Softmax step 1: e to the power of each score. Everything becomes positive, and bigger scores grow much bigger.
  6. Step 2: divide each by the total, so they add up to 1. tea 0.63, cake 0.23, soup 0.14.
  7. Print them.
  8. Temperature 0.5: dividing by a small number stretches the scores apart.
  9. Now tea's power is far bigger than the others.
  10. tea 0.84. Low temperature makes the model surer: it will almost always say "tea".
  11. It prints temperature 0.5 -> [0.84, 0.11, 0.04].
  12. Temperature 2.0: dividing by a big number squeezes the scores together.
  13. powered now points to a different list: [2.71828, 1.64872, 1.28403].
  14. tea 0.48, cake 0.29, soup 0.23. Much more even: the model will sometimes pick cake or soup.
  15. It prints temperature 2.0 -> [0.48, 0.29, 0.23].
  16. Same scores, three temperatures, three moods. Low temperature is focused and repeatable (good for code and facts); high is varied and surprising (good for ideas). The model's knowledge never changed.

Common mistakes

Best practices

Key takeaways

Check yourself

You want the same answer every time for a code question. Which temperature?

Answer: Low, near 0. Low temperature makes the top choice dominate, so answers repeat.

After softmax, what do the chances always add up to?

Answer: 1. Each value is divided by the total, so together they make 1.

·

More in Inside a Language Model