Tokenizers, Unicode, and Byte-Pair Encoding

1. Tokenizer

A tokenizer breaks a string into chunks and maps them to integer IDs. Those IDs can be used to reconstruct the string.

The text hello maps to an illustrative token ID, followed by an embedding vector.
Text → token IDs → embedding vector. The ID is illustrative and depends on the vocabulary.

2. Unicode and UTF-8

Unicode assigns code points to characters. UTF-8 defines how to represent those code points as sequences of bytes.

For A, the Unicode code point is U+0041, and its UTF-8 representation is 01000001.

Unicode identifies A with code point U+0041; UTF-8 represents it as the eight-bit byte 01000001.
Character, code point, and encoded byte.

A byte has eight bits and 256 possible values, from 0 through 255.

3. Byte-Pair Encoding

Byte-level BPE constructs a vocabulary by repeatedly merging frequent adjacent byte sequences until the target vocabulary size is reached. This reduces the number of tokens needed to represent the text while retaining the ability to encode arbitrary UTF-8 input.

Training the tokenizer on raw text produces a vocabulary tailored to that data.

4. A BPE Example

The string abab is encoded as the UTF-8 bytes 61 62 61 62, written in hexadecimal. Two merge rules combine these pieces:

PriorityMerge ruleNew token ID
1a + b → ab256
2ab + ab → abab257
The bytes for abab merge into two ab pieces, then one abab token; vocabulary lookup gives the example ID 257.
Two merges turn four byte pieces into one token representing all four bytes.

After the first merge, the pieces are ab and ab. After the second, the result is one token, abab, representing four bytes. Looking it up in this example’s vocabulary gives the token ID 257.

Notebooks

Four notebooks inspect these representations. Each page is the notebook, and the file beside it is the notebook itself.

  1. Text, Unicode, and bytes · file
  2. Vocabulary, token IDs, and embeddings · file
  3. BPE merge order and corpus frequencies · file
  4. A real tokenizer · file

Undertide