Velamuvi AIAcademy

Lesson 5 of 12 · How It Works

How LLMs Predict the Next Word

Inside a language model: text becomes next-word probabilities, one word is picked and it repeats. Play with temperature and top-p and build a tiny predictor.

  • 8 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • The loop every language model runs to write an answer
  • How a model turns text into probabilities for the next token
  • Why more context gives better predictions
  • What temperature and top-p do, and when to change them

The loop behind every answer

When you send a message to a chat assistant, the model runs the same short loop again and again:

  1. Read everything so far: your message, and any answer written so far.
  2. Score every possible next token, giving each a probability.
  3. Pick one token.
  4. Add it to the text, and go back to step 1.

The loop stops when the model picks a special "end" token, or reaches a length limit. A 300-word answer means running this loop roughly 400 times.

Step 2: from text to probabilities

A model's vocabulary has around 100,000 to 200,000 tokens. For every next position, it gives each one a probability. Almost all of them get a tiny probability; a handful get most of it.

Where do the probabilities come from? From patterns in the training data. The program below does it in the simplest way possible: it counts what came after the same words in some example text.

Try it yourselfPython
text = (
    "the cat sat on the mat . the cat sat on the sofa . "
    "the dog sat on the mat . the cat lay on the bed . "
    "the dog sat on the floor . the cat sat on the mat ."
)
words = text.split()

def next_word_chances(context):
    # context is the list of previous words, for example ["on", "the"]
    size = len(context)
    counts = {}
    for i in range(len(words) - size):
        if words[i:i + size] == context:
            following = words[i + size]
            counts[following] = counts.get(following, 0) + 1
    total = sum(counts.values())
    for word in counts:
        print(f"  {word:6} {counts[word] / total:.0%}")

print("After 'the':")
next_word_chances(["the"])
print("After 'on the':")
next_word_chances(["on", "the"])

Look at the difference. With only one word of context, the, the model cannot tell whether a sentence is starting ("the cat") or ending ("on the mat"), so animals and furniture get mixed up. With two words, on the, every option is a sensible place to sit.

Step 3: picking a token

Given the probabilities, the model has to choose. The simplest rule is to always take the most likely token.

Most assistants instead sample: they pick at random, but in proportion to the probabilities. A token with 50% probability is chosen about half the time. That is why the same question can get different answers.

Try it below. Each click picks the next word 20 times from the same probabilities.

The cat sat on the ___

mat42.0%
floor18.0%
sofa14.0%
bed10.0%
chair8.0%
roof5.0%
moon3.0%

Bars: chance of being picked now. Dashed line: the model's original probability.

Drag temperature to 0 and every pick is mat. Raise it to 2 and even moon turns up. Lower top-p to cut the unlikely tail.

Temperature

The rule is: raise every probability to the power 1 / temperature, then rescale so they add up to 1 again.

Try it yourselfPython
def apply_temperature(chances, temperature):
    adjusted = {}
    for word in chances:
        adjusted[word] = chances[word] ** (1 / temperature)
    total = sum(adjusted.values())
    for word in adjusted:
        adjusted[word] = adjusted[word] / total
    return adjusted

chances = {"mat": 0.5, "sofa": 0.2, "bed": 0.2, "floor": 0.1}

for temperature in [0.5, 1.0, 2.0]:
    adjusted = apply_temperature(chances, temperature)
    parts = []
    for word in adjusted:
        parts.append(f"{word} {adjusted[word]:.0%}")
    print(f"temperature {temperature}:", "  ".join(parts))

At temperature 1 nothing changes. At 0.5 mat jumps from 50% to 74%. At 2 the options become much more even.

UseSuggested temperature
Facts, data extraction, code, mathslow (0 to 0.3)
Everyday writing and chatmedium (around 0.7 to 1)
Brainstorming, poems, unusual ideashigher (1 to 1.3)

In chat apps you usually cannot change temperature; the app picks a sensible value. In the API used by developers it is a setting you can choose, though some newer models fix it themselves.

Common mistakes

Practice exercise

Apply temperature 0.5 to a model's probabilities for the next word.

Your solutionPython
chances = {"yes": 0.6, "no": 0.3, "maybe": 0.1}
temperature = 0.5

# Apply the temperature: raise each chance to the power 1 / temperature,
# then divide each result by their total.
# Print each word and its new chance with 2 decimal places, like:
# yes 0.78
Knowledge check

What happens when you raise the temperature from 0.2 to 1.5?

Summary

  • An LLM writes by running a loop: read, score every token, pick one, add it, repeat.
  • The scores form a probability distribution over the vocabulary, learned from training data.
  • More context gives sharper, better predictions.
  • Greedy decoding always takes the top token; sampling picks in proportion to the probabilities.
  • Temperature sharpens (low) or flattens (high) the probabilities; top-p cuts off the unlikely tail.

Next: what tokens really are, and how much text a model can see at once.

Finished reading? Tick it off to track your progress.