How AI Language Models Work · Text as Numbers
Real tokenizers are learned, not written by hand. Start from single letters and keep merging the most common pair, and useful pieces like "low" appear by themselves.
# Real tokenizers learn word pieces. Byte-pair encoding (BPE): start from letters, keep merging the most common pair.
words = ["l o w", "l o w e r", "l o w e s t", "s l o w"]
for merge in range(3):
pairs = [a + " " + b for w in words for a, b in zip(w.split(" "), w.split(" ")[1:])]
options = list(dict.fromkeys(pairs))
counts = [pairs.count(p) for p in options]
best = options[counts.index(max(counts))]
words = [(" " + w + " ").replace(" " + best + " ", " " + best.replace(" ", "") + " ").strip() for w in words]
print("merge", merge, ":", best, "->", words)merge 0 : l o -> ['lo w', 'lo w e r', 'lo w e s t', 's lo w'].merge changes from 0 to 1.pairs now points to a different list: ['lo w', 'lo w', 'w e', 'e r', 'lo w', 'w e', 'e s', 's t', …].options now points to a different list: ['lo w', 'w e', 'e r', 'e s', 's t', 's lo'].best changes from 'l o' to 'lo w'.merge 1 : lo w -> ['low', 'low e r', 'low e s t', 's low'].merge changes from 1 to 2.pairs now points to a different list: ['low e', 'e r', 'low e', 'e s', 's t', 's low'].options now points to a different list: ['low e', 'e r', 'e s', 's t', 's low'].best changes from 'lo w' to 'low e'.merge 2 : low e -> ['low', 'lowe r', 'lowe s t', 's low'].