How AI Language Models Work ยท Text as Numbers

Tokens: Turning Text into Numbers

Language models only work with numbers. Watch a sentence become a list of token ids, and see what happens to a word the model has never seen.

tokens.py

# A language model cannot read letters. Text first becomes a list of numbers: tokens.
text = "the cat sat on the mat"
words = text.split(" ")

# Give every new word the next free number. This list of known words is the vocabulary.
vocab = {}
for word in words:
    if word not in vocab:
        vocab[word] = len(vocab)

ids = [vocab[word] for word in words]
print(ids)

# A word the vocabulary has never seen has no number. Here it becomes -1, "unknown".
new_ids = [vocab.get(word, -1) for word in "the dog sat".split(" ")]
print(new_ids)

Step by step

  1. The sentence the model is given.
  2. Split it at the spaces: six words. "the" appears twice.
  3. An empty vocabulary: a dict from each known word to its number.
  4. Go through the words one at a time.
  5. "the" is not in the vocabulary yet.
  6. So it gets the next free number: len(vocab) is 0, so "the" is 0.
  7. word changes from 'the' to 'cat'.
  8. Python checks word not in vocab to decide which way the code goes.
  9. "cat" is new too: it becomes 1.
  10. word changes from 'cat' to 'sat'.
  11. Python checks word not in vocab to decide which way the code goes.
  12. "sat" becomes 2.
  13. word changes from 'sat' to 'on'.
  14. Python checks word not in vocab to decide which way the code goes.
  15. "on" becomes 3.
  16. The fifth word is "the" again.
  17. "the" is already in the vocabulary, so it keeps its number 0. No new entry.
  18. word changes from 'the' to 'mat'.
  19. Python checks word not in vocab to decide which way the code goes.
  20. "mat" becomes 4. Five different words, numbered 0 to 4.
  21. Python moves to the next item of the loop: for word in words.
  22. Now the sentence becomes token ids: look up each word in the vocabulary. "the" is 0 both times.
  23. This list of numbers is what the model actually receives.
  24. A new sentence. "dog" is not in the vocabulary, so .get gives -1, meaning unknown.
  25. The model never sees "the dog sat": it sees [0, -1, 2]. Every answer a language model writes starts as numbers like these, turned back into text at the end.