Tokenization and byte-pair encoding

Why models see sub-words, not characters or words, and how many odd behaviours trace back to it.

Intermediate about 4 h

The picture

  1. 01

    Raw text

    UTF-8 bytes

  2. 02

    Pre-tokenise

    split on patterns

  3. 03

    BPE merges

    learned pairs

  4. 04

    Token ids

    integers

  5. 05

    Embedding lookup

    vectors

Why sub-words

A model needs a fixed vocabulary. Characters make sequences very long; words cannot cover new words and typos. Sub-word tokenizers split text into frequent chunks: "unbelievable" might become un, believ, able. Rare words fall back to smaller pieces, and byte-level BPE can encode any string.

Byte-pair encoding in 25 lines

Start from bytes. Repeatedly merge the most frequent adjacent pair into a new token.

from collections import Counter

def pair_counts(ids):
    return Counter(zip(ids, ids[1:]))

def merge(ids, pair, new_id):
    out, i = [], 0
    while i < len(ids):
        if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
            out.append(new_id); i += 2
        else:
            out.append(ids[i]); i += 1
    return out

def train_bpe(text: str, n_merges: int):
    ids = list(text.encode("utf-8"))
    merges = {}
    for k in range(n_merges):
        counts = pair_counts(ids)
        if not counts:
            break
        pair = counts.most_common(1)[0][0]
        merges[pair] = 256 + k
        ids = merge(ids, pair, 256 + k)
    return merges

def encode(text, merges):
    ids = list(text.encode("utf-8"))
    while len(ids) >= 2:
        pair = min(pair_counts(ids), key=lambda p: merges.get(p, float("inf")))
        if pair not in merges:
            break
        ids = merge(ids, pair, merges[pair])
    return ids

Production tokenizers add a pre-tokenisation regex (so merges never cross word or punctuation boundaries) and reserved special tokens such as <|endoftext|>.

Using a real tokenizer

import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
for s in ["hello world", "  hello world", "12345678", "नमस्ते"]:
    ids = enc.encode(s)
    print(repr(s), len(ids), [enc.decode([i]) for i in ids])

Run it and look: leading spaces change the tokens, long numbers split into arbitrary chunks, and scripts that are rare in the training data cost many more tokens per character.

Consequences you will meet again

  • Cost and latency scale with tokens, not characters. Non-English text and code can be much more expensive.
  • Arithmetic and spelling are hard because the model never sees digits or letters as units.
  • Glitch tokens. Tokens that exist in the vocabulary but barely appear in training produce erratic behaviour.
  • Chat templates matter. Special tokens delimit roles; sending the wrong template silently degrades a model.

Common mistakes

  • Counting tokens with one model's tokenizer and billing against another's.
  • Training the tokenizer on data unlike your target (code, another language).
  • Trimming a prompt by characters and cutting through a multi-byte character.

Exercises

  1. Train BPE with 256, 1k and 5k merges on a text corpus and plot compression (bytes per token).
  2. Find three strings where a tokenizer's behaviour explains a model failure.

You are done when you can…

  • Train a BPE tokenizer on a corpus and encode and decode round-trip
  • Explain why arithmetic, spelling and non-English text are harder for LLMs
  • Count tokens before you send a request and estimate its cost