How AI Model Tokenizers Work: BPE, WordPiece, SentencePiece

Understand subword tokenization in LLMs. Learn how Byte-Pair Encoding (BPE) splits words, impacts API pricing, and handles international characters.

Large language models (LLMs) do not process raw text strings or individual characters; they compute probabilities across numerical indices called tokens. Tokenizers serve as the bidirectional translation bridge between human language and neural network vector embeddings. The specific subword segmentation algorithm chosen (such as Byte-Pair Encoding, WordPiece, or Unigram/SentencePiece) directly dictates model vocabulary efficiency, context window usage, and API billing rates across different languages.

Understanding how tokenizers parse text helps developers calculate token overhead, debug unexpected model hallucinations, and optimize prompt lengths.

The Evolution of Text Tokenization

Early natural language processing systems relied on whitespace word-level tokenization or character-level tokenization. Both approaches suffer from structural limitations:

  • Word-Level Tokenization: Splits strictly on whitespace and punctuation. A vocabulary covering English inflections, compound words, and technical jargon needs hundreds of thousands of entries. Misspelled words or novel terminology result in out-of-vocabulary (<unk>) errors.
  • Character-Level Tokenization: Uses a tiny vocabulary (roughly 256 bytes or characters). While it eliminates out-of-vocabulary errors, sequences become several times longer, which is expensive because standard self-attention cost grows quadratically with sequence length.
  • Subword Tokenization: The modern compromise. High-frequency words remain whole tokens (for example, apple -> [apple]), while rare or inflected words decompose into recurring subword units (for example, tokenization -> [token], [ization]).

Comparing Core Subword Algorithms

Different foundation model families utilize distinct subword segmentation strategies.

Algorithm Invented For Primary Model Implementations Vocabulary Construction Method Whitespace Handling
Byte-Pair Encoding (BPE) Data compression (Gage 1994), adapted for NLP (Sennrich 2016) GPT-2, GPT-4, Llama, Mistral, RoBERTa Iterative merging of most frequent adjacent byte or character pairs Explicit token symbol (such as Ġ in GPT-2 or raw UTF-8 bytes)
WordPiece Speech recognition, adapted by Google (Schuster 2012) BERT, DistilBERT, Electra Merges pairs that maximize language model likelihood on training data Uses prefix continuation markers (such as ##word)
Unigram (often via SentencePiece) Kudo (2018), Google T5, ALBERT, XLNet Starts with an oversized vocabulary and prunes tokens with minimal loss contribution SentencePiece treats whitespace as a regular symbol (▁, U+2581)

Step-by-Step Mechanics of Byte-Pair Encoding (BPE)

Byte-Pair Encoding constructs its vocabulary bottom-up through frequency counting:

  1. Initial Vocabulary: Seeded with every base character or byte (256 raw bytes for byte-level BPE).
  2. Frequency Counting: The corpus is split into characters. Adjacent token pairs are counted across all words.
  3. Merge Extraction: The most frequent pair is merged into a new unified subword token and added to the vocabulary.
  4. Iteration: Steps 2 and 3 repeat until reaching the desired vocabulary size (typically 32,000 to 100,000 tokens).

Python Demonstration: Naive BPE Training Loop

import re
from collections import Counter

def get_stats(vocab: dict[str, int]) -> Counter:
    """Count frequency of adjacent character pairs in vocabulary."""
    pairs = Counter()
    for word, freq in vocab.items():
        symbols = word.split()
        for i in range(len(symbols) - 1):
            pairs[symbols[i], symbols[i + 1]] += freq
    return pairs

def merge_vocab(pair: tuple[str, str], v_in: dict[str, int]) -> dict[str, int]:
    """Merge all occurrences of the target pair in the vocabulary."""
    v_out = {}
    # Match the pair only as whole symbols (plain str.replace could merge
    # across symbol boundaries, e.g. "es t" when merging ("s", "t")).
    pattern = re.compile(r"(?<!\S)" + re.escape(" ".join(pair)) + r"(?!\S)")
    replacement = "".join(pair)
    for word, freq in v_in.items():
        v_out[pattern.sub(replacement, word)] = freq
    return v_out


corpus = {
    "l o w </w>": 5,
    "l o w e r </w>": 2,
    "n e w e s t </w>": 6,
    "w i d e s t </w>": 3
}

# Run 5 merge iterations
for step in range(5):
    pairs = get_stats(corpus)
    if not pairs:
        break
    best_pair = pairs.most_common(1)[0][0]
    corpus = merge_vocab(best_pair, corpus)
    print(f"Step {step + 1}: Merged {best_pair} -> {''.join(best_pair)}")

The Non-English Tokenization Tax

Because major LLM tokenizers (such as cl100k_base or o200k_base) are trained on English-heavy data, common English words usually map to a single token. OpenAI's rule of thumb is that one token is roughly 4 characters or about three quarters of an English word.

Languages with non-Latin scripts (Cyrillic, Arabic, Devanagari) or rich morphology (heavily inflected Polish, compound-forming German, agglutinative Hungarian or Turkish) are often split into shorter fragments, so the same content needs more tokens. Petrov et al. (NeurIPS 2023) measured 17 tokenizers and found that translations of the same text can differ in token count by up to 15 times for some language pairs. Newer tokenizers with larger vocabularies, such as o200k_base, narrow but do not remove this gap.

Pro-Tip: Trailing Whitespace and Indentation Many BPE tokenizers attach the leading space to the token ( apple and apple are different tokens). Modern tokenizers have tokens for common runs of spaces, but unusual whitespace, mixed tabs and spaces, or deep indentation in JSON can still add tokens. Minifying JSON and normalizing indentation is a cheap way to cut prompt length.

Before sending prompts to high-throughput API endpoints, verify your character-to-token footprint using our Character Counter. If your prompts contain confidential user logs or company source code, use our client-side Prompt Anonymizer to scrub internal IPs, API keys, and employee names before your text hits external model tokenizers.

Frequently Asked Questions (FAQ)

What is the average ratio between words and tokens in English?

In standard English prose, 100 tokens represent approximately 75 words. For programming code, mathematical formulas, or deeply nested JSON structures, the ratio shifts significantly: 100 tokens may represent only 30 to 45 words or code symbols.

Why do LLMs struggle with character-counting tasks?

LLMs do not see individual letters unless a word is explicitly split into single characters. For example, a word like strawberry is typically split into a few multi-letter tokens rather than ten letters. The model has to infer which letters each token contains from patterns learned in training, which makes exact letter counting error-prone.

What is Byte-Level BPE (BBPE)?

Byte-Level BPE initializes its base vocabulary with 256 individual raw byte values instead of Unicode characters. This guarantees that any valid or malformed UTF-8 byte stream can be tokenized without generating an out-of-vocabulary (<unk>) token.

References & Official Sources