The token maker
So far our GPT reads one character at a time. Real models don’t: they read tokens, pieces of text that can be a letter, a syllable or a whole word. Chapter 10 of the book explains why and builds from scratch the method with which almost all language models make their tokens: byte pair encoding, BPE.
Whole words don’t work: Pinocchio contains almost six thousand different ones, more than half appear only once, and in the validation text 440 words had never been seen before. Characters work but are slow: a sentence becomes a very long row. BPE sits in the middle. It starts from the 69 characters, looks for the most frequent pair of consecutive symbols in the text, merges it into a new symbol and starts again. Each merge adds a token to the vocabulary. The book does 443 of them, to reach 512 tokens.
The 443 merges are the ones the book learned on 90% of Pinocchio, in the order in which they were found. Type a text and watch it cut into tokens, one per colour. The slider decides how many merges to use: at zero the tokenizer goes back to characters, at 443 it is the book’s. On the right, the compression curve on the validation set and the list of merges, with the ones in use lit up.
Three experiments
1. Pinocchio is a token. Press “1”. “ Pinocchio” and “ burattino”, leading space included, are one token each: they appear so often that the merges have built them whole. “ Geppetto”, instead, becomes “ G” plus “eppetto”: a capital G after a space is not frequent enough. The tokenizer knows nothing about grammar, it only knows how to count.
2. One merge at a time. Press “2” and watch “C’era una volta un pezzo di legno.” (Once upon a time there was a piece of wood.) go from 34 tokens, one per character, to 12. The first merges are “ c”, “ d”, “ s”, “ p”, “er”, “no”: a space followed by a consonant, the most common syllables. Then come the short words, “ di”, “ un”, “ una”, and at the end “ legno”. On the curve, compression rises fast at first and then more and more slowly: with 100 merges the validation set has 1.69 characters per token, with 443 it has 2.38. Each extra token gains less than the one before.
3. Never-seen words. Press “3”. “andai” (I went) and “ritornai” (I came back) never appear in the training text, yet the tokenizer writes them without any trouble: “ an”, “da”, “i” and “ ri”, “tor”, “na”, “i”. With characters and merges, every word can be put together, even words that do not exist. It is the decisive advantage over whole words.
In the book, an LSTM trained on these tokens reaches a loss of 1.445 per character, worse than the 1.365 of the LSTM on the characters of chapter 9: on a single book, a larger vocabulary has a cost. That is why the book’s GPT keeps reading characters.
The same experiment in Python
The code downloads Pinocchio from the book’s repository, learns the 443 merges as in the chapter (a few seconds) and redoes the three experiments.
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/pinocchio.txt
import re
from collections import Counter
testo = open("pinocchio.txt", encoding="utf-8").read()
n = int(0.9 * len(testo))
train, val = testo[:n], testo[n:]
SCHEMA = re.compile(r" ?\w+| ?[^\w\s]+|\s+") # first, cut into pieces
def addestra_bpe(testo, quante_fusioni):
sequenze = Counter({tuple(p): k for p, k in Counter(SCHEMA.findall(testo)).items()})
fusioni = []
for _ in range(quante_fusioni):
coppie = Counter()
for seq, k in sequenze.items():
for a, b in zip(seq, seq[1:]):
coppie[(a, b)] += k
(a, b), _ = coppie.most_common(1)[0] # the most frequent pair
fusioni.append((a, b))
nuove = Counter()
for seq, k in sequenze.items(): # merge it everywhere
fusa, i = [], 0
while i < len(seq):
if i < len(seq) - 1 and (seq[i], seq[i + 1]) == (a, b):
fusa.append(a + b); i += 2
else:
fusa.append(seq[i]); i += 1
nuove[tuple(fusa)] += k
sequenze = nuove
return fusioni
def codifica(testo, fusioni):
rango = {coppia: i for i, coppia in enumerate(fusioni)}
token = []
for pezzo in SCHEMA.findall(testo):
s = list(pezzo)
while len(s) > 1: # the oldest possible merge
r, i = min((rango.get((a, b), float("inf")), i) for i, (a, b) in enumerate(zip(s, s[1:])))
if r == float("inf"):
break
s = s[:i] + [s[i] + s[i + 1]] + s[i + 2:]
token += s
return token
fusioni = addestra_bpe(train, 443) # 69 characters + 443 merges = 512 tokens
print([a + b for a, b in fusioni[:8]])
# [' c', ' d', ' s', ' p', 'er', 'no', ' a', 'to']
# 1. Pinocchio is a token
print(codifica(" Pinocchio burattino Geppetto", fusioni))
# [' Pinocchio', ' burattino', ' G', 'eppetto']
# 2. One merge at a time: how much it compresses on the validation set
for k in [0, 100, 200, 443]:
print(k, round(len(val) / len(codifica(val, fusioni[:k])), 2))
# 0 1.0 / 100 1.69 / 200 1.99 / 443 2.38
# 3. Never-seen words
print(codifica(" andai ritornai", fusioni))
# [' an', 'da', 'i', ' ri', 'tor', 'na', 'i']
In the book
This lab accompanies chapter 10, “Tokens”. The chapter counts the words of Pinocchio and comes across Zipf’s law, builds BPE first by hand and then on the whole book, uses it to encode and decode, and trains the LSTM of chapter 9 on tokens, with the right way to compare losses measured in different units.
The “Inside the Puppet” series
- Chapter 1 The teacher inside the text
- Chapter 2 Pinocchio turns into numbers
- Chapter 3 The loaded die
- Chapter 4 The neuron that learns to count
- Chapter 5 The engine in reverse
- Chapter 6 Bending the line
- Chapter 7 Bengio’s network
- Chapter 8 Training well
- Workshop A The diagnosis threshold
- Chapter 9 The puppet’s memory
- Workshop B The bag and the network
- Chapter 10 The token maker
- Chapter 11 The map of words
- Chapter 12 Where Pinocchio looks
- Chapter 13 Sixteen glances
- Chapter 14 The puppet’s thermometer
- Workshop C Eight books and one
- Chapter 15 The Cricket answers
- Chapter 16 How many bits are needed
- Chapter 17 Learning to say “I don’t know”
- Chapter 18 The Cricket with the open book
- Chapter 19 The puppet’s eyes
- Workshop D Thirty-two by thirty-two
- Chapter 20 The plane of digits
- Chapter 21 The pencil