Building Tokenizers from Scratch: What Happens Before the Model Thinks

A language model never sees raw text. It sees token IDs. This fundamental fact makes tokenization the first — and often most consequential — design decision in the language model stack. Before a single matrix multiply happens inside GPT or BERT, every character of your prompt has already been chopped, merged, and looked up in a fixed vocabulary, silently dictating sequence length, embedding table size, and inference cost.

Tokenization: The Hidden Systems Decision

Tokenization is often called the "bottleneck before the model." While flashy attention mechanisms and model architectures dominate the conversation, tokenization quietly determines how long your sequences are and how much an inference call costs. The core trade-off is straightforward but profound: small vocabularies yield long sequences and tiny embedding tables; large vocabularies yield short sequences but multi-megabyte embedding tables.

Consider a concrete example: a character-level tokenizer with a vocabulary of 100 tokens requires only around 200 KB for embeddings. However, a 50-word sentence expands into roughly 250 character tokens, demanding 62,500 attention computations per layer. In contrast, a BPE tokenizer with a 50,000-token vocabulary consumes about 97.7 MB for embeddings but compresses the same sentence to roughly 75 tokens, requiring only 5,625 attention computations — a 10x reduction in computational cost. Production systems enthusiastically absorb the memory cost because the attention savings are so dramatic.

Building a BPE Tokenizer from Scratch

Byte Pair Encoding, originally a data compression technique, forms the backbone of GPT-style tokenizers. The algorithm is elegantly simple: start with a character-level vocabulary, count all adjacent character pairs in the training corpus, merge the most frequent pair into a new token, and repeat until you hit the target vocabulary size.

A pure Python implementation from scratch involves several core steps: first, converting text to a list of byte IDs (0–255), then iteratively counting adjacent token pairs across the corpus, finding the most frequent pair, assigning it a new token ID (starting from 256), replacing all instances with the new token, and storing the merge rule. The resulting vocabulary maps token IDs to byte sequences, and the merge rules allow both encoding (applying merges in order) and decoding (reversing the lookup).

Building this yourself reveals nuances that production tokenizers hide. For example, handling end-of-word markers and deciding how to handle spaces — GPT-2 style tokenizers convert spaces to special tokens like Ġ to preserve sentence structure, a detail that dramatically affects how the model learns language patterns.

WordPiece: BERT's Approach

BERT uses WordPiece, a tokenization algorithm that superficially resembles BPE but operates differently under the hood. The training algorithm is similar — it starts from a small vocabulary containing all characters and learns merge rules. However, instead of selecting the most frequent pair to merge, WordPiece scores each candidate pair using the formula:

score = freq(pair) / (freq(first) × freq(second))

This scoring prioritizes merging pairs where the individual parts are less frequent in the vocabulary, creating subword units that maximize coverage. For example, ("hu", "##gging") will likely merge before ("un", "##able"), even if the latter appears more frequently, because the individual parts are less common.

The tokenization algorithm differs even more dramatically: WordPiece stores only the final vocabulary, not the merge rules. Starting from a word, it finds the longest subword in the vocabulary, splits there, and repeats — a greedy longest-match approach. This is why BERT tokens look like ['token', '##ization'] — the ## prefix indicates continuation of a word.

Understanding Tokenization Differences Across Models

Different models use different tokenizers, and the differences matter. GPT-4 uses o200k_base encoding with a 128k context window, while Claude uses a proprietary BPE implementation, and Gemini uses SentencePiece-based estimation. For multilingual content, the differences can be stark — Korean text can tokenize with 2x token count spread across models on the same string.

Practical Token Management with tiktoken

OpenAI's tiktoken library provides exact token counting for models using cl100k_base and o200k_base encodings. This is essential for managing context windows and optimizing prompts:

import tiktoken
enc = tiktoken.encoding_for_model("gpt-4")
tokens = enc.encode("Your prompt here")
print(f"Token count: {len(tokens)}")

Research Gap: The Hidden Cost of Tokenization

While researchers spend enormous effort optimizing model architectures and training algorithms, tokenization remains an afterthought in most literature. We lack standardized benchmarks comparing tokenizer efficiency across languages, and there is no consensus on optimal vocabulary size for different domains. The question remains: for a given task and language distribution, what tokenizer configuration minimizes both computational cost and loss of semantic information?

← Back to all articles