Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

Predicting the next word

By the end of this chapter, you'll be able to

  • Explain what a language model and a token are
  • Build a mini model in Python that predicts the next word
  • Generate text word by word from probabilities
  • Explain what sets a real language model apart from this mini model

What is a language model?

A language model is a program that, from the start of a text, computes the probability of each possible continuation. Generative AI assistants (also called large language models, or LLMs) are trained on huge amounts of text: books, websites, code. They learn which words usually follow which others.

These models do not work on whole words but on tokens: pieces of words. "unbelievably" may be split into "un", "believ", "ab", "ly". To keep things simple, we will work with whole words here.

A mini model in Python

The simplest model counts, in a training text, which word follows which word. It is a bigram model (two words at a time):

from collections import Counter, defaultdict

text = (
    "the market is busy in the morning . the market is quiet in the evening . "
    "the river is quiet in the morning . the market is busy on saturday ."
)
words = text.split()

following = defaultdict(Counter)
for word, nxt in zip(words, words[1:]):
    following[word][nxt] += 1

print(following["market"])
print(following["is"])
print(following["the"].most_common(3))
Counter({'is': 3})
Counter({'busy': 2, 'quiet': 2})
[('market', 3), ('morning', 2), ('evening', 1)]

zip(words, words[1:]) forms all pairs of consecutive words, and a Counter counts how many times each following word appears. After "is", the model saw "busy" 2 times and "quiet" 2 times.

From counts to probabilities

Dividing each count by the total gives a probability:

from collections import Counter

after_is = Counter({"busy": 2, "quiet": 2})
total = sum(after_is.values())
for word, count in after_is.items():
    print(f"P({word} | is) = {count}/{total} = {count / total:.2f}")
P(busy | is) = 2/4 = 0.50
P(quiet | is) = 2/4 = 0.50

P(busy | is) reads "probability of busy given that the previous word is is".

We continue until the full stop. This sentence does not exist as such in the training text: the model composed it.

Step 5 of 5
Text description of the animation
  1. We give the model a first word.
  2. After “the”, the model saw market 3 times, morning 2 times, evening and river once each. It draws at random according to these weights.
  3. After “market”, it only ever saw “is”: probability 1.
  4. After “is”, busy and quiet are tied: the draw gave busy.
  5. We continue until the full stop. This sentence does not exist as such in the training text: the model composed it.

Generating text

To generate, we start from a word, draw the next one at random according to the probabilities, and start again. We fix the random seed (random.seed) so the example always gives the same result:

import random
from collections import Counter, defaultdict

text = (
    "the market is busy in the morning . the market is quiet in the evening . "
    "the river is quiet in the morning . the market is busy on saturday ."
)
words = text.split()
following = defaultdict(Counter)
for word, nxt in zip(words, words[1:]):
    following[word][nxt] += 1

def generate(start, length, seed):
    random.seed(seed)
    sentence = [start]
    for _ in range(length):
        options = following[sentence[-1]]
        sentence.append(random.choices(list(options), weights=list(options.values()))[0])
        if sentence[-1] == ".":
            break
    return " ".join(sentence)

for seed in (1, 2, 3):
    print(generate("the", 10, seed))
the market is quiet in the morning .
the river is busy in the evening .
the market is busy on saturday .

random.choices(options, weights=weights) draws an element respecting the weights. The model produces plausible sentences, such as “the river is busy in the evening”, which does not exist in the training text… and which nothing proves to be true.

From the mini model to real assistants

Our model only looks one word back. Real language models:

  • look thousands of tokens back (the whole start of the conversation), thanks to a neural network architecture called the transformer;
  • have learned billions of parameters on gigantic amounts of text;
  • are then fine-tuned with examples of good answers and human feedback, to follow instructions and refuse certain requests.

But the principle stays the same: predict a probable continuation. The model does not "know" that a piece of information is true: it knows it is plausible given what it has read.

Mini-lab: train your own modelPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the most probable word

Write a function most_probable(text, word) that returns the word that most often follows word in text, with its probability rounded to two decimals, or None if the word was never followed by anything.

Hint 1
Build the following counter as in the chapter, then use most_common(1).
Hint 2
The probability is the count of the chosen word divided by the sum of the counts.
Show the solution and common mistakes
from collections import Counter, defaultdict

def most_probable(text, word):
    words = text.split()
    following = defaultdict(Counter)
    for a, b in zip(words, words[1:]):
        following[a][b] += 1
    if not following[word]:
        return None
    best, count = following[word].most_common(1)[0]
    return best, round(count / sum(following[word].values()), 2)

text = "it rains in Bamako . it is hot in Bamako . it is sunny in Ségou ."
print(most_probable(text, "it"))
print(most_probable(text, "in"))
print(most_probable(text, "Kayes"))
('is', 0.67)
('Bamako', 0.67)
None

Common mistakes:

  • Writing following[word].most_common(1)[0] without first checking whether the counter is empty: for an unknown word, the list is empty and Python raises an IndexError.
  • Dividing by the number of words in the text instead of the number of words following word: the probability must only cover what follows that particular word.

Summary

  1. 1A language model computes the probability of each possible continuation of a text.
  2. 2Models work on tokens, pieces of words.
  3. 3Generating means drawing the next token at random according to these probabilities, then starting again.
  4. 4Real models look at the whole context, have billions of parameters and are fine-tuned to follow instructions.
  5. 5A model produces what is plausible, not necessarily what is true.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.