Tokenization

Tokenization

Human language exists as discrete, variable-length text strings governed by syntax, grammar, and morphology. Deep neural networks, conversely, are differentiable mathematical functions that operate strictly on continuous numerical vectors. The bridge between these two representations is tokenization.

The design of every tokenizer is governed by a fundamental tradeoff in sequence modeling:

  1. Character-Level Representation: Guarantees zero out-of-vocabulary (OOV) errors because every text decomposes into individual Unicode characters. However, it inflates sequence length by an order of magnitude. Because self-attention compute and memory scale quadratically () with sequence length , processing text character-by-character imposes a massive computational tax on every attention layer.
  2. Word-Level Representation: Keeps sequence lengths short and preserves obvious semantic units. However, human vocabulary is practically open-ended: proper names, technical jargon, slang, and typos are infinite. A fixed word vocabulary requires enormous embedding matrices () and inevitably fails when encountering unseen words at inference time.

Subword tokenization resolves this dilemma. By treating words as compositional sequences of high-frequency subword chunks, common words remain single tokens, rare words break down into familiar morphemes, and sequence length remains computationally efficient.


How Tokenization Works

Modern tokenizers transform raw text into integer tensors through three distinct phases:

Text-to-Tensor Tokenization Geometry ("understanding" → X ∈ R3 × d)

1. UTF-8 Byte Sequenceunderstanding2. BPE Merged Subwords & Vocabulary Indices (t ∈ V3)"under"ID: 2104"stand"ID: 3812"ing"ID: 278Gather WE[t]O(1) Lookup3. Dense Token Tensor X ∈ R3 × dWE[2104]+0.42-0.18+0.75WE[3812]+0.81+0.34-0.62WE[278]-0.15+0.91+0.09
Figure 1: A 13-byte UTF-8 string is compressed by BPE merge rules into subword indices , which directly index rows of to form the dense input tensor .

The BPE Algorithm Walkthrough

To see how Byte-Pair Encoding (BPE) constructs its vocabulary, consider building a tokenizer from scratch on a miniature training corpus consisting of four words and their frequencies:

1. Initial Character Vocabulary

We append a special end-of-word suffix </w> to each word to preserve word boundary information across merges. Each word starts split into individual character symbols:

  • l o w </w> (frequency: 5)
  • l o w e r </w> (frequency: 2)
  • n e w e s t </w> (frequency: 6)
  • w i d e s t </w> (frequency: 3)

The base vocabulary contains all 11 unique symbols:

2. Counting Symbol Pairs

We scan the corpus and count all adjacent pairs of symbols:

Adjacent Symbol PairOccurrences Across CorpusTotal Frequency
e + s9
s + t9
l + o7
o + w7
w + e6
n + e6
w + </w>5

Both e + s and s + t share the top frequency of 9. Breaking ties deterministically, we merge e + s first:

  • Merge Rule 1: e + s es
  • Updated Corpus:
    • l o w </w> (5)
    • l o w e r </w> (2)
    • n e w es t </w> (6)
    • w i d es t </w> (3)

3. Merging Most Frequent Pairs

Re-evaluating adjacent pair frequencies in the updated corpus:

  • es + t appears times.
  • est + </w> then appears times.
  • l + o and lo + w each appear times.

Applying these greedy merges in sequence produces five learned rules:

  1. Rule 1: e + s es (freq 9)
  2. Rule 2: es + t est (freq 9)
  3. Rule 3: est + </w> est</w> (freq 9)
  4. Rule 4: l + o lo (freq 7)
  5. Rule 5: lo + w low (freq 7)

4. Tokenizing Unseen Words

When the model encounters the previously unseen word lowest, it splits the word into base characters (l o w e s t </w>) and applies the learned merge rules in order, decomposing lowest into two root morphemes (low and est</w>) without throwing an unknown token error:

Byte-Pair Encoding (BPE) Subword Merge Simulator

Step through each merge rule to see how frequent adjacent pairs fuse into subwords and segment the unseen word lowest.

Vocabulary |V|: 11
Unseen Word Length: 7 tokens
Live Segmentation of Unseen Word: lowest
Corpus Frequencies Top: e + s (9)
Learned Merge Table 0 / 5 Active
Step 0 / 5
Merge Step:

Practical Edge Cases & Realities

Byte-Level BPE & Zero Out-of-Vocabulary Tokens

Early BPE models operated on Unicode characters. If an input contained an unencountered emoji, rare mathematical symbol, or character from an unsupported script, the tokenizer emitted the destructive unknown token [UNK].

Modern frontier tokenizers (Tiktoken for GPT-4, LLaMA 3, Gemma) eliminate [UNK] completely using Byte-Level BPE:

  • The base vocabulary is initialized with all 256 raw bytes ( through ) of the UTF-8 specification.
  • Because every Unicode symbol decomposes into 1 to 4 UTF-8 bytes (for example, the emoji ✨ maps to UTF-8 bytes 0xE2, 0x9C, 0xA8), any input text is representable without fallback errors.

Numbers & Digit Splitting

Standard BPE trained on raw text merges numbers inconsistently:

  • 1234 might tokenize as 12 + 34
  • 12345 might tokenize as 123 + 45
  • 123456 might tokenize as 1 + 234 + 56

This unpredictable chunking forces attention layers to waste capacity inferring decimal alignment before performing arithmetic. Modern models enforce regex pre-tokenization rules that split every individual digit into its own token, stabilizing mathematical reasoning.

Multilingual Fertility & Compute Cost

Tokenizer vocabularies trained predominantly on English corpora dedicate most entries to English morphemes.

  • In English, fertility (tokens per character) is roughly 0.25 to 0.30 (~4 characters per token).
  • In non-Latin scripts (Hindi, Arabic, Japanese, Telugu), text frequently splits into individual bytes, causing fertility to surge to 0.80 to 1.20 tokens per character.

This means non-English prompts consume to more tokens for the exact same semantic content, driving up API costs, inference latency, and memory consumption.


Comparing Modern Tokenizers

AlgorithmUsed ByOptimization ObjectiveBoundary Handling
Byte-Pair Encoding (BPE)GPT-4, LLaMA 3Co-occurrence frequency ()Regex pre-tokenization with byte fallback
WordPieceBERTLikelihood of unigram language modelExplicit prefix marking (e.g. ##ing)
SentencePiece / UnigramT5, MistralPrunes seed vocabulary via unigram lossTreats whitespace as a standard symbol (▁)

Key Papers & References