Tokenization: How LLMs Actually See Text

Matt George

Fractional CTO · Founder of Injuria.ai

•12 min read•

Large Language Models don't read text. Not in the way humans do. When a model like GPT-4 processes your prompt, it doesn't see words, sentences, or even letters. It sees a sequence of integers. The process that translates your human-readable text into this machine-readable list of numbers is called tokenization. This crucial, often invisible, step dictates not only how an LLM understands language but also its performance, its limitations, and even the cost of running it. Understanding tokenization isn't just an academic exercise; it's a practical necessity for any engineer or leader building with or on top of this technology.

At its core, tokenization solves the fundamental problem of representation. Neural networks, the engine of modern AI, are mathematical structures. They operate on vectors and matrices of numbers, not on abstract symbols like 'A' or 'apple'. To process language, we must find a way to convert the symbolic nature of text into a numerical format. Tokenization is the first and most critical step in this pipeline. It breaks down a piece of text into a list of smaller units, called tokens, and then maps each token to a unique integer ID. These IDs are then used to look up corresponding vectors in an embedding matrix[1], but the tokenization itself is the point where text ceases to be text and begins its journey into the mathematical realm of the model.

The Path to Modern Tokenization

The way we tokenize text has evolved significantly. Early approaches were simple but fraught with problems that limited the capabilities of natural language processing (NLP) systems. Understanding this history clarifies why modern LLMs work the way they do.

Early Attempts: Words and Characters

The most intuitive way to tokenize text is to split it by spaces. This is called word-based tokenization. You take a sentence like "The quick brown fox jumps," and you get the tokens ["The", "quick", "brown", "fox", "jumps"]. Each unique word in your training data gets a unique integer ID. This works for simple cases, but it has two catastrophic failures.

First is the vocabulary explosion. A language like English has hundreds of thousands of words. If you include names, jargon, and misspellings, the vocabulary becomes nearly infinite. A model would need an impossibly large list of all possible words. Second is the out-of-vocabulary (OOV) problem. If the model encounters a word during inference that it never saw during training (like a new slang term or a typo), it has no ID for it. The system would have to represent it with a generic <UNK> (unknown) token, losing all of its meaning.

Frustrated by the limitations of word tokens, engineers tried the opposite approach: character-based tokenization. Here, the text is split into individual characters: ['T', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k', ...]. This elegantly solves the OOV problem because any word can be constructed from a small set of characters. The vocabulary is tiny and fixed (for example, the 256 values in ASCII[2] or the broader Unicode[3] set). However, this creates a new problem: sequence length. A single word like "unforgettable" is one token for a word-based system, but 13 tokens for a character-based one. Since the computational cost of many model architectures (like Transformers) scales with the square of the sequence length, character-based models become incredibly inefficient and struggle to capture meaning that is contained in multi-character units, like the concept of a "word".

The Breakthrough: Subword Tokenization

The modern solution, and the one used by virtually all state-of-the-art LLMs, is subword tokenization. It's a brilliant compromise between word and character methods. The core idea is to break words into smaller, meaningful components. Common words like "and" or "like" can remain as single tokens, while rare or complex words like "tokenization" can be broken into pieces like tok, en, ization. This way, the model can maintain a fixed, manageable vocabulary size while still being able to represent any word by combining its subword parts. It effectively learns a vocabulary of word-fragments.

Several algorithms have been developed to achieve this, but most are variants of a few key ideas. They are not based on linguistic rules (like prefixes or suffixes) but on statistical frequency. The tokenizer algorithm is trained on a massive text corpus, learning the most efficient way to segment words based on what patterns appear most often.

How Subword Tokenization Actually Works

To make this concrete, let's explore the most foundational subword algorithm: Byte Pair Encoding (BPE)[4]. Originally a data compression algorithm from the 1990s, it was adapted for NLP in 2015 by Sennrich et al.[5] and forms the basis for the tokenizers used in the GPT series, Llama, and many other models.

BPE is an iterative process:

  1. Initialization: Start with a vocabulary consisting of all the individual characters (bytes) present in your training corpus.
  2. Counting: Scan the entire corpus and count the frequency of all adjacent pairs of tokens in your current vocabulary.
  3. Merging: Find the most frequent pair (e.g., 't' followed by 'h'). Merge these two tokens into a new, single token 'th'. Add this new token to your vocabulary.
  4. Repetition: Repeat steps 2 and 3 for a predetermined number of merges. This number of merges, a hyperparameter, directly controls the final vocabulary size.

After thousands of merges, the vocabulary will contain the initial single characters plus a rich set of frequent multi-character subwords, and even entire common words.

A Worked Example of BPE

Let's trace a simplified BPE training process. Imagine our training corpus is just a dictionary of word counts:

{ "low": 5, "lower": 2, "newest": 6, "widest": 3 }

For simplicity, we'll represent the words with their characters and an end-of-word symbol </w>:

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

Step 1: Initial Vocabulary
Our initial vocabulary is just the set of all characters used: {'l', 'o', 'w', 'e', 'r', 'n', 's', 't', 'i', 'd', '</w>'}.

Step 2: First Merge
We count all adjacent pairs. The most frequent pair is e followed by s, which appears in newest (6 times) and widest (3 times), for a total of 9 occurrences. So, we merge them.

  • New Token: es
  • New Vocabulary: {'l', 'o', 'w', 'e', 'r', 'n', 's', 't', 'i', 'd', '</w>', 'es'}

Step 3: Second Merge
Now our corpus effectively looks like this, replacing e s with es:

n e w es t </w> (6 times)
w i d es t </w> (3 times)

The next most frequent pair is es followed by t (9 times). We merge them.

  • New Token: est
  • New Vocabulary: {'l', 'o', 'w', 'e', 'r', 'n', 's', 't', 'i', 'd', '</w>', 'es', 'est'}

Step 4: Continue Merging
This process continues. The next merge might be l and o (lo), then n and e (ne), and so on. After many iterations, the vocabulary will be populated with statistically significant subwords.

When it's time to tokenize a new word, say "lowest", the trained tokenizer applies the learned merges in the same order. It would first break "lowest" into characters ['l', 'o', 'w', 'e', 's', 't'], then merge e and s to es, then es and t to est, resulting in the tokenization ['l', 'o', 'w', 'est'].

Other Important Algorithms

While BPE is foundational, other algorithms are also in use:

  • WordPiece: Used by Google's BERT[6], WordPiece is similar to BPE but with a key difference in its merge criterion. Instead of choosing the most frequent pair, it merges the pair that maximizes the likelihood of the training data. It's a subtle but important statistical distinction.
  • Unigram Language Model: Introduced by Kudo[7], this approach is fundamentally different. It starts with a large vocabulary of possible subwords and iteratively removes the ones that contribute least to the overall probability of the corpus, until it reaches the desired vocabulary size. This method also allows for multiple possible tokenizations for the same string, each with a probability, which can be used for training-time regularization.
  • SentencePiece: Developed by Google, SentencePiece[8] is not a new tokenization algorithm itself, but a software library that bundles BPE or Unigram into a convenient package. Its key innovation is to treat all text as a raw stream, including spaces. It encodes spaces as a special character (e.g., _). This makes the tokenization and detokenization process purely algorithmic and language-agnostic, as it doesn't rely on space-based word splitting, a feature that is critical for languages like Chinese, Japanese, or Thai.

The Real-World Impact: Tradeoffs and Failure Modes

For a technical leader, the choice of tokenizer (or awareness of the one used by a chosen model) has direct consequences for performance, cost, and correctness. These are not academic details; they are practical engineering tradeoffs.

Vocabulary Size and Efficiency

The size of the vocabulary is a primary tradeoff. The GPT-3[9] tokenizer has a vocabulary of 50,257. The Llama 2 tokenizer has 32,000, while Llama 3 expanded this to 128,256. A larger vocabulary allows more common words and even multi-word phrases to be represented as a single token, leading to shorter, more efficient sequence lengths for the model to process. However, it also increases the size of the model's embedding matrix, which can increase memory usage and slow down computation. A smaller vocabulary is more compact but may fragment common words into multiple tokens, increasing sequence length and potentially making it harder for the model to grasp the word's meaning.

The Fragmentation Problem

Tokenization can lead to bizarre and non-intuitive failures. A classic example is the word "SolidGold". A BPE tokenizer might see this as Sol, id, Gold, completely missing the intended concept. This happens frequently with code, URLs, and any text that deviates from standard prose.

This is particularly problematic with numbers. A model's tokenizer might not have a unique token for every number. The number 2024 might be a single token, but 2025 might be tokenized as 20, 25. The number 1,000,000 could become 1, ,000, ,000. This fragmentation is a key reason why LLMs are notoriously bad at precise arithmetic; they don't see numbers as holistic quantities but as arbitrary collections of digits and punctuation.

Language and Domain Mismatches

Tokenizers are trained, not universal. A tokenizer trained on a massive English corpus will be suboptimal for other languages. German, with its long compound words, requires a different tokenization strategy than Vietnamese, with its single-syllable words. This is why multilingual models often use much larger vocabularies and tokenizers trained on a balanced, multilingual corpus.

Similarly, a tokenizer trained on general web text will struggle with specialized domains. A tokenizer for a model intended to analyze source code will be trained differently, prioritizing common programming syntax like ->, _, and (, which would be rare in prose. Using a general-purpose model on a highly specialized domain without fine-tuning the tokenizer can lead to inefficient tokenization and poor performance.

The Cost of Tokens

In the commercial world, tokens are money. API providers like OpenAI[10], Anthropic[11], and Google Cloud[12] price their services based on the number of input and output tokens. A seemingly short English sentence can become a long and expensive sequence of tokens if it contains many rare words. For example, the sentence "The ichthyologist studied ichthyosaurs" will likely use far more tokens than "The fish doctor studied fish fossils," because "ichthyologist" and "ichthyosaurs" will be broken down into many small, rare subwords.

This has direct implications for prompt engineering and application design. To manage costs and stay within context window limits, engineers must be mindful of how their text will be tokenized. Using simpler language and avoiding jargon where possible can directly reduce operational costs.

Correcting Common Misconceptions

Given its complexity, several misconceptions about tokenization are common among practitioners.

Misconception 1: A token is a word.
This is the most common error. As we've seen, a token is a subword unit. A good rule of thumb is that one token often corresponds to about four characters of text for common English. You can use online tools, like OpenAI's Tokenizer[13], to see this in action.

Misconception 2: Tokenization is standardized.
False. Every model family has its own tokenizer, trained on its specific corpus. The tokenizer for GPT-4 is different from the one for Llama 3, which is different from the one for Claude 3. Using the wrong tokenizer for a model is a common mistake that leads to severely degraded performance or outright failure. Libraries like Hugging Face's AutoTokenizer[14] exist to automatically fetch the correct tokenizer for a given model, abstracting away this complexity.

Misconception 3: Tokenization is just about splitting strings.
False. It's a data-driven, statistical process. The BPE merge rules or the Unigram vocabulary are not hand-coded; they are learned from analyzing terabytes of text data. The tokenizer is a model in its own right, albeit a much simpler one than the LLM it serves.

The State of Tokenization Today

Today, the field has largely converged on BPE and its variants. The tokenizers for the most prominent models (OpenAI's GPT series, Meta's Llama, Anthropic's Claude) are all based on BPE. The de facto standard for working with these in open source is the Hugging Face tokenizers[15] library, which provides fast, reliable implementations of these algorithms. For developers working with OpenAI models specifically, the tiktoken[16] library offers a highly optimized implementation of their official tokenization schemes.

While subword tokenization is the dominant paradigm, research continues. Some researchers are exploring "token-free" models that operate directly on raw bytes. Google's ByT5[17] is a notable example, processing text as a stream of UTF-8[18] bytes. This completely eliminates the need for a separate tokenization step and is truly language-agnostic. However, these models must process much longer sequences (since every byte is a token), which presents its own significant computational challenges. For the foreseeable future, subword tokenization remains the practical and established foundation upon which our most powerful language models are built.

Sources (18)
  1. Word embedding on Wikipedia
  2. ASCII on Wikipedia
  3. The Unicode Consortium
  4. Byte pair encoding on Wikipedia
  5. Neural Machine Translation of Rare Words with Subword Units (Sennrich et al., 2015)
  6. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (Devlin et al., 2018)
  7. Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates (Kudo, 2018)
  8. SentencePiece on GitHub
  9. Language Models are Few-Shot Learners (Brown et al., 2020)
  10. OpenAI API Pricing
  11. Anthropic API Pricing
  12. Google Cloud Generative AI Pricing
  13. OpenAI Tokenizer Tool
  14. Hugging Face AutoTokenizer Documentation
  15. Hugging Face tokenizers library on GitHub
  16. OpenAI tiktoken library on GitHub
  17. ByT5: Towards a token-free future with pre-trained byte-to-byte models (Xue et al., 2021)
  18. UTF-8 on Wikipedia

Recommended reading

Evaluating LLMs: How to Measure Output Quality13 min readA comprehensive guide for technical leaders on measuring LLM performance, covering human evaluation, automated metrics like BLEU and BERTScore, and the modern LLM-as-a-Judge approach.Choosing an Embedding Model11 min readA comprehensive guide for engineers and technical leaders on how embedding models work, the critical tradeoffs involved in selecting one, and the current state of open-source and proprietary options.How to Build an AI Agent: The Loop, Memory, and Tools13 min readA technical guide for engineers and leaders on the architecture of AI agents, covering the core reasoning loop, memory systems, tool integration, and critical production trade-offs.Semantic Caching: A Technical Guide for LLM Applications11 min readSemantic caching reduces LLM application costs and latency by storing and reusing responses to conceptually similar queries, using vector embeddings and similarity search instead of exact-text matching.Speculative Decoding: How LLMs Generate Faster12 min readSpeculative decoding accelerates large language model inference by using a smaller, faster model to draft text that a larger, more powerful model then verifies in parallel, significantly reducing generation latency without compromising output quality.Structured Data Extraction With LLMs: When It Beats Hand-Written Parsers12 min readLarge Language Models can extract structured data like JSON from unstructured text with surprising reliability, but the mechanism and tradeoffs determine when this approach is superior to traditional parsers.