TExcelTAD
Home › Math for Deep Learning & LLMs › Tokenization and Byte-Pair Encoding

Tokenization and Byte-Pair Encoding

Language models do not read characters or words; they read tokens, integer ids from a fixed vocabulary of typically 32k to 200k entries. A tokenizer must turn any string into tokens and back without loss. Characters give short vocabularies but very long sequences; whole words give short sequences but cannot handle new words. Byte-pair encoding (BPE) finds a data-driven middle ground: frequent words become single tokens, rare words split into reusable pieces.

The BPE algorithm

Training (done once, on a corpus):

  1. Start with a vocabulary of single symbols (characters, or all 256 bytes in byte-level BPE).
  2. Count every adjacent pair of symbols in the corpus.
  3. Merge the most frequent pair into a new symbol, add it to the vocabulary, and record the merge.
  4. Repeat until the vocabulary reaches the target size.

Encoding a new string replays the recorded merges in order. Because the base alphabet contains every byte, any string can be encoded: there is no unknown token.

python · try it yourself
from collections import Counter

corpus = "low lower lowest newer newest wider widest " * 3
words = Counter(corpus.split())
vocab = {tuple(w) + ("_",): c for w, c in words.items()}          # "_" marks the end of a word
merges = []
for step in range(8):
    pairs = Counter()
    for sym, c in vocab.items():
        for a, b in zip(sym, sym[1:]):
            pairs[a, b] += c
    best = max(pairs, key=pairs.get)
    merges.append(best)
    new_vocab = {}
    for sym, c in vocab.items():
        out, i = [], 0
        while i < len(sym):
            if i < len(sym) - 1 and (sym[i], sym[i + 1]) == best:
                out.append(sym[i] + sym[i + 1]); i += 2
            else:
                out.append(sym[i]); i += 1
        new_vocab[tuple(out)] = c
    vocab = new_vocab
    print(f"merge {step + 1}: {best[0]!r} + {best[1]!r} (count {pairs[best]})")
print("segmentations:", [" ".join(s) for s in vocab])
merge 1: 'w' + 'e' (count 12)
merge 2: 'l' + 'o' (count 9)
merge 3: 'r' + '_' (count 9)
merge 4: 's' + 't' (count 9)
merge 5: 'st' + '_' (count 9)
merge 6: 'lo' + 'we' (count 6)
merge 7: 'n' + 'e' (count 6)
merge 8: 'ne' + 'we' (count 6)
segmentations: ['lo w _', 'lowe r_', 'lowe st_', 'newe r_', 'newe st_', 'w i d e r_', 'w i d e st_']

Encoding new text

Encoding applies the learned merges, in the order they were learned, to each new word. Here is a small hand-picked merge list of the same kind:

python · try it yourself
merges = [("e", "s"), ("es", "t"), ("est", "_"), ("l", "o"), ("lo", "w"), ("e", "r"), ("er", "_"), ("w", "i")]
def encode(word):
    sym = list(word) + ["_"]
    for a, b in merges:                              # apply merges in the learned order
        i, out = 0, []
        while i < len(sym):
            if i < len(sym) - 1 and sym[i] == a and sym[i + 1] == b:
                out.append(a + b); i += 2
            else:
                out.append(sym[i]); i += 1
        sym = out
    return sym
for w in ("lowest", "slowest", "wildest", "zebra"):
    print(f"{w:8s} -> {encode(w)}")
lowest   -> ['low', 'est_']
slowest  -> ['s', 'low', 'est_']
wildest  -> ['wi', 'l', 'd', 'est_']
zebra    -> ['z', 'e', 'b', 'r', 'a', '_']

Unseen words like "slowest" reuse learned pieces ("low", "est_"); a word with no learned pieces falls back to characters.

Why tokenization matters for the math

  • Sequence length: English text averages roughly 4 characters (about 0.75 words) per token with a 50k-100k vocabulary. Attention cost and context limits are counted in tokens.
  • Cross-entropy and perplexity are per token, so they are only comparable between models with the same tokenizer; bits per byte normalizes by text length instead (Perplexity).
  • Vocabulary size trades embedding parameters (VdVd) and softmax cost against sequence length.
  • Quirks: digits split irregularly (hurting arithmetic), leading spaces are part of tokens (" the" differs from "the"), and languages underrepresented in the training corpus need more tokens per word.

Other schemes

WordPiece (BERT) merges the pair that most increases the corpus likelihood instead of the most frequent one. Unigram LM (SentencePiece) starts from a large vocabulary and prunes pieces that least reduce the likelihood, and can sample alternative segmentations. Byte-level BPE (GPT-2 onward) runs BPE on UTF-8 bytes.

In software

  • tiktoken (OpenAI), Hugging Face tokenizers, and sentencepiece implement these algorithms in fast native code.
  • tokenizer.encode("Hello world") returns ids; decode inverts it exactly.
  • Special tokens (beginning of sequence, end of turn, padding) are added outside the BPE vocabulary.

Go further: Byte-Pair Encoding from Scratch adds byte-level BPE and checks the encoder against GPT-2's merges.

Exercises

Exercise 1: First merge

In the corpus "aaab aab", which pair does BPE merge first (count pairs within words)?

Answer

"a" + "a".

Solution

"aaab" has pairs aa, aa, ab; "aab" has aa, ab. Counts: aa 3, ab 2.

Exercise 2: Tokens and context

A model has a 4096-token context. Roughly how many English words fit, at 0.75 words per token?

Answer

About 3,000 words.

Solution

4096⋅0.75≈30724096 \cdot 0.75 \approx 3072.

Exercise 3: Byte-level fallback (code)

How many UTF-8 bytes do "cat", "café" and "猫" take? These are the base tokens of byte-level BPE before any merge.

Answer

3, 5 and 3.

Solution

"é" takes 2 bytes and the Chinese character 3.

python · try it yourself
for s in ("cat", "café", "猫"):
    print(s, len(s.encode("utf-8")), list(s.encode("utf-8")))
cat 3 [99, 97, 116]
café 5 [99, 97, 102, 195, 169]
猫 3 [231, 140, 171]

Test yourself

BPE training repeatedly…

  1. splits the longest word
  2. merges the most frequent adjacent pair of symbols
  3. removes rare characters
  4. sorts the vocabulary

Why can byte-level BPE encode any string?

  1. It has an unknown token
  2. Its base vocabulary contains all 256 byte values
  3. It uses whole words
  4. It ignores rare characters

Why are per-token perplexities of models with different tokenizers not directly comparable?

  1. They use different GPUs
  2. The same text is split into different numbers of tokens
  3. Perplexity is always 1
  4. Tokenizers change the labels