Skip to content
ml-recall

Topic notes

Tokenization

How text becomes token ids — word, character and subword units, the tokenizer pipeline, and the BPE, WordPiece and Unigram algorithms with their training and encoding rules.

4-min read AI-checked

Practise 44 questions Take a test

Key ideas

Formulas

score(a,b)=freq(ab)freq(a)×freq(b)\mathrm{score}(a, b) = \frac{\mathrm{freq}(ab)}{\mathrm{freq}(a) \times \mathrm{freq}(b)}

Worked example

BPE on the word counts cat 6, cats 3, hat 4, that 2, chat 1. Split into characters the corpus is 3⋅6+4⋅3+3⋅4+4⋅2+4⋅1=543 \cdot 6 + 4 \cdot 3 + 3 \cdot 4 + 4 \cdot 2 + 4 \cdot 1 = 54 symbols, with base vocabulary {a, c, h, s, t}.

step pair counts (top) merge corpus length
1 a t 16, c a 9, h a 7 at 54−16=3854 - 16 = 38
2 c at 9, h at 7, at s 3 cat 38−9=2938 - 9 = 29
3 h at 7, cat s 3, t h 2 hat 29−7=2229 - 7 = 22

The vocabulary now has 5+3=85 + 3 = 8 tokens. The unseen word "chats" is encoded as c h a t s → c h at s (merge 1; merge 2 needs c at, which does not occur) → c hat s (merge 3). WordPiece on the same corpus would merge t ##h first: its score 2/(2⋅3)=1/32/(2 \cdot 3) = 1/3 beats 16/(16⋅16)=1/1616/(16 \cdot 16) = 1/16 for the most frequent pair ##a ##t.

In code

from collections import Counter

corpus = {"cat": 6, "cats": 3, "hat": 4, "that": 2, "chat": 1}
words = {w: " ".join(w) for w in corpus}          # start from single characters
for step in range(3):
    pairs = Counter()
    for w, s in words.items():
        sym = s.split()
        for p in zip(sym, sym[1:]):
            pairs[p] += corpus[w]                 # count pairs inside words only
    (a, b), n = pairs.most_common(1)[0]
    words = {w: f" {s} ".replace(f" {a} {b} ", f" {a}{b} ").strip() for w, s in words.items()}
    print(step + 1, a + b, n)                     # 1 at 16 / 2 cat 9 / 3 hat 7
print(words["that"], "|", words["chat"])          # t hat | c hat

Common pitfalls

References

  1. Hugging Face LLM Course — Ch. 2 Using Transformers, Tokenizers (Word-based, Character-based, Subword tokenization)
  2. Hugging Face LLM Course — Ch. 6 The Tokenizers library, Training a new tokenizer from an old one
  3. Hugging Face LLM Course — Ch. 6, Normalization and pre-tokenization (Normalization, Pre-tokenization, SentencePiece)
  4. Hugging Face LLM Course — Ch. 6, Byte-Pair Encoding tokenization (Training algorithm, Tokenization algorithm)
  5. Hugging Face LLM Course — Ch. 6, WordPiece tokenization (Training algorithm, Tokenization algorithm)
  6. Hugging Face LLM Course — Ch. 6, Unigram tokenization (Training algorithm, Tokenization algorithm)
  7. Hugging Face LLM Course — Ch. 6, Building a tokenizer, block by block (introduction, the four steps)
  8. Hugging Face LLM Course — Ch. 2, Behind the pipeline (Preprocessing with a tokenizer)