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.
AI · beginner · 8 min · 30 steps · free
# 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)
breakword is created with the value 'tea'. chance is created with the value 0.5.word changes from 'tea' to 'coffee'. chance changes from 0.5 to 0.25.total >= p to decide which way the code goes.word changes from 'coffee' to 'juice'. chance changes from 0.25 to 0.15.total >= p to decide which way the code goes.word changes from 'juice' to 'soup'. chance changes from 0.15 to 0.07.total >= p to decide which way the code goes.word changes from 'soup' to 'tea'. chance changes from 0.07 to 0.5.word changes from 'tea' to 'coffee'. chance changes from 0.5 to 0.25.picked coffee.Answer: Only a. a alone already covers 0.9, which reaches 0.8.
Answer: Text becomes repetitive and dull. Some randomness gives variety; top-k or top-p stops it picking nonsense.
← Softmax and Temperature · Attention: Words Looking at Words →