Papa Programmer
Lesson 03 of 20

Tokens and tokenisers

9 min read

Optional

Why not letters or whole words

A tokeniser has to choose how big each piece is. Both obvious choices have a problem.

  • Letters. The vocabulary is small, but every word costs many steps. A model would need about five predictions to write one English word.
  • Whole words. Each word costs one step, but the vocabulary needs millions of entries. A new word, a name or a typo would still be missing.

Tokens sit between the two. A common word such as "the" is one token. A rare word splits into a few pieces that the tokeniser already knows, so no word is ever unknown.

LettersWhole wordsTokens
Size of the vocabularyAbout a hundredMillionsTens of thousands
Steps for one common wordSeveralOneUsually one
A word it has never seenSpelled outMissingSplit into known pieces
Three ways to cut text into pieces

Byte pair encoding in 20 lines

Most LLM tokenisers use Byte pair encodingA way to build a tokeniser. It starts from single characters or bytes and keeps merging the most common neighbouring pair into a new token. Often shortened to BPE., or BPE. The idea is short:

  1. Start with every word split into single characters.
  2. Count every pair of neighbouring pieces.
  3. Merge the most common pair into one new piece.
  4. Repeat until the vocabulary reaches the size you want.

The program below runs four merges on five words.

python
from collections import Counter

words = ["low", "lower", "lowest", "slow", "slower"]
corpus = [list(word) for word in words]

def most_common_pair(corpus):
	pairs = Counter()
	for symbols in corpus:
		pairs.update(zip(symbols, symbols[1:]))
	return pairs.most_common(1)[0][0]

def merge(symbols, pair):
	merged, i = [], 0
	while i < len(symbols):
		if tuple(symbols[i:i + 2]) == pair:
			merged.append(symbols[i] + symbols[i + 1])
			i += 2
		else:
			merged.append(symbols[i])
			i += 1
	return merged

for step in range(1, 5):
	pair = most_common_pair(corpus)
	corpus = [merge(symbols, pair) for symbols in corpus]
	print(f"Merge {step}: {pair[0]} + {pair[1]}")
	print("   ", " | ".join(" ".join(symbols) for symbols in corpus))

It prints:

text
Merge 1: l + o
    lo w | lo w e r | lo w e s t | s lo w | s lo w e r
Merge 2: lo + w
    low | low e r | low e s t | s low | s low e r
Merge 3: low + e
    low | lowe r | lowe s t | s low | s lowe r
Merge 4: lowe + r
    low | lower | lowe s t | s low | s lower

After four merges, "low" and "lower" are single pieces. "lowest" is still four pieces, because "est" was too rare in this tiny text to earn a merge. A real tokeniser does the same thing over billions of words and stops after tens of thousands of merges.

Real vocabulary sizes

The list of merges becomes the tokeniser, and each piece gets an id number.

  • GPT-2 works on bytes instead of characters, so any text can be encoded. Its vocabulary has 50,257 tokens: 256 single bytes, 50,000 merges and one end-of-text token.
  • Newer tokenisers are larger. Llama 3 uses a vocabulary of 128,256 tokens. A larger vocabulary means fewer tokens for the same text.

Token counts decide cost and length

Prices, speed and length limits are all counted in tokens, not words. OpenAI's guidance for English text is that one token is about four characters, or about three quarters of a word. Other languages and program code often need more tokens for each word.

Odd effects of tokens

The model sees token ids, not letters. Three effects follow from that.

  • Spelling and counting letters are hard. A model that sees "strawberry" as two or three tokens has no direct view of each letter.
  • Spaces belong to tokens. In GPT-2's tokeniser, the space before a word is part of the token. " Hello" with a space and "Hello" without one are different tokens.
  • Numbers split unevenly. A long number can break into chunks of different sizes, which makes arithmetic harder for the model.

When a model makes a strange mistake with spelling or digits, the tokeniser is the first place to look.

Pieces between letters and wordsCommon words are one token, and rare words split into known pieces.
BPE merges common pairsThe tokeniser is the list of merges learned from a large amount of text.
Count in tokensCost, speed and length limits all use tokens, not words.

Your reading position is saved

0%

0 of 20 complete

Contents

Learning tools