Byte Pair Encoding: How a Compression Trick From the 1990s Became Every LLM’s Tokenizer

Language models never see words, letters, or sentences. They see integers. Everything you type gets mapped to a sequence of token IDs before the first embedding lookup, and everything the model “says” starts life as a stream of predicted token IDs that some other component converts back into text. That component — the tokenizer — is a model in its own right: it has its own training corpus, its own training algorithm, and its own frozen vocabulary, fixed long before the language model begins training.

Tokenization deserves more attention than it gets because it silently shapes nearly everything downstream. It sets the price of your API call, determines how much text fits in a context window, and explains a suspicious share of the famous failure modes: arithmetic mistakes on long numbers, weird behavior around trailing spaces, and the fact that the same paragraph costs several times more tokens in Greek than in English. The algorithm behind almost all of it is byte pair encoding, a data compression technique from the 1990s that turned out to be nearly perfect for the job.

The Idea: Compression Repurposed

Byte pair encoding (BPE) was originally a compression method: repeatedly find the most common pair of symbols in a sequence and replace both occurrences with one new symbol that didn’t exist before. Each merge shrinks the sequence. Run it enough times and the data compresses into fewer symbols, where the symbols are frequent patterns discovered from the data itself.

Tokenization keeps the training loop and throws away the compression goal. Instead of shrinking text, you are building a vocabulary: each merge creates a new token representing a frequent byte sequence. Common words eventually become single tokens, frequent prefixes and suffixes get their own entries, and rare strings stay as sequences of smaller pieces. The result is a middle ground between character-level tokenization (tiny vocabulary, uselessly long sequences) and word-level tokenization (huge vocabulary, hopeless with typos, plurals, and any word the corpus missed).

The Training Loop, Step by Step

Suppose a training corpus contains just these words with these frequencies:

"low" x 5    "lower" x 2    "newest" x 6    "widest" x 3

Training starts by splitting everything into individual bytes, and counts every adjacent pair:

l o w l o w l o w l o w l o w e r l o w e r
n e w e s t n e w e s t n e w e s t
n e w e s t n e w e s t n e w e s t
w i d e s t w i d e s t w i d e s t

pair counts: (e,s)=9  (e,w)=8  (s,t)=9  (n,e)=6  (w,e)=8  (l,o)=7  (o,w)=7 ...

The most frequent pair — say (e,s) — becomes the first merge: every occurrence collapses into a new token es, the vocabulary grows by one entry, and the counts are recomputed. Then (es,t) merges into est, and now the word “newest” is just three tokens: n e w est. Merge after merge, the vocabulary climbs from 256 base symbols to the target size, and the merges discovered first — the most frequent pairs — become the oldest, highest-priority rules:

merge 1: (e,s)  -> "es"
merge 2: (es,t) -> "est"
merge 3: (l,o)  -> "lo"
merge 4: (lo,w) -> "low"   ... and so on, until vocab_size is reached

The order matters more than people expect. Merges are applied in the order they were learned, so earlier (more frequent) merges win conflicts. That priority order is the entire difference between the training phase and the encoding phase below.

Why Bytes: The Trick That Removed the Unknown Token

Early subword tokenizers split text into characters and built the base vocabulary from the characters seen in training. That has a fatal flaw: any character that never appeared in the corpus cannot be tokenized, so it degrades into an “unknown” token that destroys all information. Tokenize a corpus of English prose, then feed it a name written in Tamil, and you get garbage.

Byte-level BPE solves this completely: split the text into its raw UTF-8 bytes instead of characters. Every possible string — any language, emoji, binary blobs, invalid sequences your users paste in — decomposes into bytes, so the base vocabulary is always exactly 256 entries and the unknown token ceases to exist. Frequent byte sequences then merge upward into whole characters, then subwords, then words. A consequence worth knowing: an emoji like 🚀 is four UTF-8 bytes, so if no merge captured it during training it will cost four tokens; in byte-level vocabularies that did learn it, it costs one.

One implementation detail shows up in every GPT-family tokenizer: whitespace. Since BPE operates on bytes and words usually arrive preceded by a space, the space is encoded as a distinct byte value that appears inside tokens — in GPT-2’s vocabulary you will see tokens rendered with a “Ġ” prefix, which is just a space wearing a costume so it survives the round trip. Newlines get their own treatment, which is why models can be oddly sensitive to trailing whitespace: the token for hello and the token for hello are completely different entries, and a prompt ending in a stray space forces the model down a different distribution than the one its training data taught it.

Implementing It in ~40 Lines of Python

The algorithm is small enough to hold in your head. Training counts pairs, merges the most frequent one, and repeats; encoding replays the learned merges in priority order:

from collections import Counter

def merge(tokens: list[int], pair: tuple[int, int], new_id: int) -> list[int]:
    out, i = [], 0
    while i < len(tokens):
        if i < len(tokens) - 1 and (tokens[i], tokens[i + 1]) == pair:
            out.append(new_id)
            i += 2                      # consumed both halves of the pair
        else:
            out.append(tokens[i])
            i += 1
    return out

def train_bpe(text: str, vocab_size: int) -> dict[tuple[int, int], int]:
    tokens = list(text.encode("utf-8"))          # start from raw bytes
    merges: dict[tuple[int, int], int] = {}      # pair -> merged token id
    next_id = 256
    while next_id < vocab_size:
        counts = Counter(zip(tokens, tokens[1:]))
        if not counts:
            break                                # nothing left to merge
        (a, b), _ = counts.most_common(1)[0]
        merges[(a, b)] = next_id
        tokens = merge(tokens, (a, b), next_id)
        next_id += 1
    return merges

def encode(text: str, merges: dict[tuple[int, int], int]) -> list[int]:
    tokens = list(text.encode("utf-8"))
    while len(tokens) >= 2:
        # apply the earliest-learned applicable merge (lowest id) first
        pair = min(zip(tokens, tokens[1:]),
                   key=lambda p: merges.get(p, float("inf")))
        if pair not in merges:
            break
        tokens = merge(tokens, pair, merges[pair])
    return tokens

Run train_bpe on a decent chunk of text and inspect the merges — the first ones learned are things like a space plus “t”, a space plus “the”, and other obsessively common English fragments, which tells you immediately that the vocabulary is a statistical profile of the training corpus. Two details separate this toy from production tokenizers. Real ones pre-tokenize with a regex that splits text into word-like chunks before pair counting, so merges never cross word boundaries and the encode step stays fast on large documents. And real ones reserve special token IDs — end-of-text, padding, role markers — that are never produced by the merge loop but injected by the surrounding chat template. If you want to go further, both OpenAI’s tiktoken and the Hugging Face tokenizers library are open source, and reading their merge logic alongside the toy version above is the fastest way to make the ideas stick.

Vocabulary Size Is a Real Tradeoff

How big should the vocabulary be? GPT-2 used 50,257 tokens; recent large models use vocabularies in the 100k–250k range (Llama 3 sits around 128k, GPT-4o near 200k). The pressure runs in both directions. A larger vocabulary means fewer tokens per document — text compresses into more whole-word tokens, which stretches a fixed context window over more content and lowers per-token API costs. But the embedding table and the output layer both scale with vocabulary size, and every rare token in it receives far less training signal than a frequent one, which wastes parameters and can produce poorly calibrated predictions on unusual words.

Vocabulary choice also bakes in inequality between languages. A tokenizer trained mostly on English gives common English words single tokens, while the same meaning in Greek, Hindi, or Japanese decomposes into many more pieces — often two to three times the token count for equivalent text, and sometimes much worse. That multiplier hits twice: it costs more money and it eats the context window, so the “same” long conversation has less room left in it. Expanding a vocabulary with more multilingual training data is one of the quiet reasons newer models handle non-English input better than their predecessors.

When Tokenization Is the Bug

A surprising number of model quirks stop being mysterious once you look at the token stream:

  • Arithmetic on long numbers. If a tokenizer chunks 1234567 into pieces like 123, 456, 7, the model must perform digit-level reasoning across arbitrary chunk boundaries it never saw a consistent version of. Newer tokenizers force every digit into its own token precisely to make arithmetic more uniform.
  • Whitespace sensitivity. Because leading spaces are part of tokens, the string "Hello" and " Hello" encode differently, and template bugs that inject a stray space can visibly degrade output quality.
  • Glitch tokens. Vocabularies scraped from messy web text contain bizarre strings that appear in the vocabulary but almost never in the training data, so the model has no reliable representation for them — producing confident nonsense when they surface.
  • Budget and cost distortion. Any pipeline that budgets context by character count rather than token count will misestimate by a language-dependent factor, which matters a lot for retrieval pipelines stuffing documents into prompts.

None of this requires you to become a tokenizer expert, but it does argue for one habit: before blaming the model for a strange output, encode the input and look at the token IDs. Half the time the surprise is visible right there — an unexpected chunking, a whitespace token you didn’t intend, or a string that costs three times what you budgeted. The tokenizer is the first thing your text meets on its way into the model, and it sees your data through the statistics of a corpus you never chose. Knowing how that lens was ground tells you where it distorts.

Leave a Reply

Your email address will not be published. Required fields are marked *