How AI Language Models Work ยท Inside a Language Model
A language model guesses the next word, again and again. Build a tiny one by counting which word follows which, then let it write a sentence.
# A language model's one job: given the words so far, guess the next word.
# This tiny model learns by counting which word follows which in its training text.
text = "i like tea . i like cake . i want tea ."
words = text.split(" ")
follows = {}
for a, b in zip(words, words[1:]):
follows.setdefault(a, []).append(b)
# After "i", what came next, and how often?
seen = follows["i"]
options = list(dict.fromkeys(seen))
chances = [round(seen.count(w) / len(seen), 2) for w in options]
print(options, chances)
# Generate: start with "i", then keep adding the most likely next word.
sentence = ["i"]
for _ in range(3):
nexts = follows[sentence[-1]]
best = max(nexts, key=nexts.count)
sentence.append(best)
print(" ".join(sentence))a changes from 'i' to 'like'. b changes from 'like' to 'tea'.a changes from 'like' to 'tea'. b changes from 'tea' to '.'.a changes from 'tea' to '.'. b changes from '.' to 'i'.a changes from '.' to 'i'. b changes from 'i' to 'like'.a changes from 'i' to 'like'. b changes from 'like' to 'cake'.a changes from 'like' to 'cake'. b changes from 'cake' to '.'.cake with the value a list is added to the dict that follows points to.a changes from 'cake' to '.'. b changes from '.' to 'i'.a changes from '.' to 'i'. b changes from 'i' to 'want'.a changes from 'i' to 'want'. b changes from 'want' to 'tea'.want with the value a list is added to the dict that follows points to.a changes from 'want' to 'tea'. b changes from 'tea' to '.'.['like', 'want'] [0.67, 0.33]._ is created with the value 0._ changes from 0 to 1._ changes from 1 to 2.sentence points to.for _ in range(3).