How AI Language Models Work ยท Inside a Language Model

Top-k and Top-p: Choosing Safely at Random

Picking the next word at random makes text lively, but should never pick nonsense. Top-k and top-p cut off the unlikely tail before rolling the dice.

sampling.py

# The model's chances for the next word, most likely first.
words = ["tea", "coffee", "juice", "soup", "glue"]
chances = [0.5, 0.25, 0.15, 0.07, 0.03]

# Top-k: keep only the k most likely words, so a silly one like "glue" can never be picked.
k = 3
top_k = words[:k]

# Top-p: keep the most likely words until their chances add up to at least p.
p = 0.8
kept, total = [], 0
for word, chance in zip(words, chances):
    if total >= p:
        break
    kept.append(word)
    total = round(total + chance, 2)

# Pick at random from what is kept. A real model rolls a random number; here the roll is fixed.
roll, running = 0.6 * total, 0
for word, chance in zip(kept, chances):
    running = round(running + chance, 2)
    if running >= roll:
        print("picked", word)
        break

Step by step

  1. Five possible next words, most likely first.
  2. Their chances. Even "glue" has a small chance, and a random pick would sometimes choose it.
  3. Top-k with k = 3.
  4. Keep only the first 3: tea, coffee, juice. soup and glue can never be picked.
  5. Top-p with p = 0.8: keep words until their chances add up to 0.8.
  6. Start with nothing kept and a total of 0.
  7. word is created with the value 'tea'. chance is created with the value 0.5.
  8. The total (0) is below 0.8, so keep going.
  9. Keep "tea".
  10. Total 0.5.
  11. word changes from 'tea' to 'coffee'. chance changes from 0.5 to 0.25.
  12. Python checks total >= p to decide which way the code goes.
  13. Keep "coffee".
  14. Total 0.75: still below 0.8.
  15. word changes from 'coffee' to 'juice'. chance changes from 0.25 to 0.15.
  16. Python checks total >= p to decide which way the code goes.
  17. Keep "juice".
  18. Total 0.9.
  19. word changes from 'juice' to 'soup'. chance changes from 0.15 to 0.07.
  20. Python checks total >= p to decide which way the code goes.
  21. The kept words cover 0.9, so stop. If the model had been very sure (say tea 0.85), top-p would keep only one word.
  22. Roll the dice. A real model uses a random number; here it is fixed at 0.6 of the kept total, 0.54.
  23. word changes from 'soup' to 'tea'. chance changes from 0.07 to 0.5.
  24. Walk through the kept words, adding up their chances: 0.5.
  25. 0.5 has not reached 0.54 yet.
  26. word changes from 'tea' to 'coffee'. chance changes from 0.5 to 0.25.
  27. Add coffee: 0.75.
  28. 0.75 has passed 0.54, so the roll landed on coffee.
  29. It prints picked coffee.
  30. "coffee" is picked. A different roll could give tea or juice, but never soup or glue. Chat models usually combine temperature with top-p.