Understanding AI · lesson 44 of 60 · about 7 minutes
Writing One Word at a Time
Put it together: a tiny text generator that writes a sentence one predicted word at a time.
What you'll learn
- Generate text by repeatedly predicting the next word
- Explain why each new word depends on the ones before
- Explain why tiny models write nonsense and big ones don't
Round and round again
To write a sentence, predict a word, add it on, then predict the next word from the new end of the sentence, and so on. Each new word becomes part of the context for the next one.
Chatbots write your whole answer like this, one token at a time, which is why you can watch the text appear bit by bit.
A mini generator using the word-pair table. `" ".join(...)` glues the words back into one line.
words = "i like cats . i like dogs . i like cats . you like cats .".split()
following = {}
for a, b in zip(words, words[1:]):
if a not in following:
following[a] = {}
following[a][b] = following[a].get(b, 0) + 1
word = "i"
sentence = [word]
for step in range(3):
options = following[word]
word = max(options, key=options.get)
sentence.append(word)
print(" ".join(sentence))Output
i like cats .Why big models do better
Our generator only looks at one word back, so it soon writes nonsense. Real chatbots look at thousands of tokens back and have learned from a huge share of the text ever written, with billions of weights capturing grammar, facts and style. Same trick, vastly bigger.
Tip
Each new word becomes part of what the next word is predicted from.
Now try it yourself
This lesson is free in Codiqo, with 6 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.