How AI Language Models Work ยท Text as 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.
# 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)word changes from 'the' to 'cat'.word not in vocab to decide which way the code goes.word changes from 'cat' to 'sat'.word not in vocab to decide which way the code goes.word changes from 'sat' to 'on'.word not in vocab to decide which way the code goes.word changes from 'the' to 'mat'.word not in vocab to decide which way the code goes.for word in words.