AI
What Is a Tokenizer? How LLMs Split Text Into Tokens
What a tokenizer is and how it works: BPE, WordPiece and SentencePiece, a worked example, vocab sizes of popular LLMs, and why tokenization affects cost.
A tokenizer is the component that turns text into a sequence of numbers a language model can process, and turns the model's numbers back into text. It splits input into tokens (whole words, pieces of words, single characters or bytes) using a fixed vocabulary learned before the model was trained, then maps each token to an integer ID. Every LLM tokenizer is paired with one model: the same sentence produces different tokens, and a different token count, in GPT, Llama or Gemma.
This guide explains what a tokenizer is and how it works step by step, the types of tokenization in NLP, how the main subword algorithms (BPE, WordPiece, Unigram and SentencePiece) differ, a worked BPE example you can follow by hand, a comparison of popular models' tokenizers, the difference between an LLM tokenizer vs embedding layer, and why tokenization affects cost, multilingual quality and odd model behaviour.
What Is a Tokenizer?
What is a tokenizer, in plain terms? It's a translator between human text and model input. Neural networks work on numbers, not letters, so before a model sees your prompt, the tokenizer:
- splits the text into tokens, such as
["Token", "izers", " split", " text", "."], - looks up each token's integer ID in its vocabulary, such as
[3, 1729, 4251, 1495, 13](illustrative IDs), - adds any special tokens the model expects, such as start-of-text or chat role markers.
The model then predicts the next token ID, and the tokenizer decodes the IDs it generates back into text. The tokenizer is not a neural network and has no understanding of meaning: it applies fixed rules and a fixed vocabulary that were learned from a large text sample before the model's own training began. That's also why a model and its tokenizer can't be swapped independently: the model learned what ID 1729 means, and a different tokenizer would assign that ID to something else.
If you want the practical side of tokens (how many words a token is, how token pricing and context windows work), our guide to LLM tokens covers that. This post is about the machinery that produces them.
How a Tokenizer Works, Step by Step
Modern tokenizer libraries, such as Hugging Face's tokenizers, describe the process as a four-stage pipeline:
- Normalization. Clean the raw text: Unicode normalization, optionally lowercasing or stripping accents. Many LLM tokenizers do very little here so that the original text can be reproduced exactly.
- Pre-tokenization. Split the text into rough chunks, typically on whitespace and punctuation, often with rules for numbers and contractions. GPT-style tokenizers use a regular expression for this step.
- The model. Apply the learned algorithm (for example BPE merges) to break each chunk into tokens from the vocabulary.
- Post-processing. Add special tokens (beginning of sequence, separators, chat template markers) and produce the final IDs plus extras such as attention masks.
Decoding runs the other way: IDs to tokens to text. Byte-level tokenizers can decode any sequence back to the exact original bytes, which is why they never produce an "unknown" token.
Types of Tokenization in NLP
There are four main types of tokenization in NLP, distinguished by the size of the unit they split text into.
| Type | Unit | Example: "unbelievable!" | Vocabulary size | Pros | Cons |
|---|---|---|---|---|---|
| Word | Whole words and punctuation | unbelievable, ! | Very large (hundreds of thousands) | Intuitive, short sequences | Unknown words, huge vocab, poor with typos and new terms |
| Character | Single characters | u, n, b, e and so on | Small (hundreds) | No unknown words | Very long sequences, little meaning per token |
| Subword | Frequent words whole, rare words in pieces | un, believ, able, ! | Medium (30,000 to 260,000) | Balance of length and coverage | Splits can look arbitrary |
| Byte-level subword | Subwords built from raw bytes | Like subword, falls back to bytes for anything unseen | Medium | Handles any text, emoji or language | Non-Latin scripts can need many tokens |
Classic NLP pipelines (for example in NLTK or spaCy) also use sentence tokenization, splitting a document into sentences, and word tokenization for tasks such as part-of-speech tagging and named entity recognition. Our natural language processing guide shows where tokenization sits in those pipelines.
Every major LLM uses subword tokenization, usually byte-level, because it keeps sequences reasonably short while still representing any input.
Subword Algorithms: BPE, WordPiece, Unigram and SentencePiece
Four names come up constantly. Three are algorithms; one is a library.
Byte Pair Encoding (BPE). Originally a 1994 data-compression technique by Philip Gage, adapted for neural machine translation by Sennrich, Haddow and Birch in 2016. It starts from individual characters (or bytes) and repeatedly merges the most frequent adjacent pair into a new token, until the vocabulary reaches a target size. GPT-2 introduced byte-level BPE, starting from the 256 possible byte values, which is what the GPT family, Llama 3, Qwen and DeepSeek use.
WordPiece. Developed at Google (Schuster and Nakajima, 2012) and used by BERT. It also builds up from characters, but chooses merges by how much they improve the likelihood of the training data rather than by raw frequency. Word-internal pieces are marked with ##, so BERT tokenizes "GPU" in lowercase as gp, ##u.
Unigram. Proposed by Taku Kudo in 2018. It works in the opposite direction: start with a large candidate vocabulary and repeatedly remove the tokens whose loss hurts the overall likelihood least. Because it's probabilistic, it can sample different segmentations of the same text, which helps as a training regulariser.
SentencePiece. A library by Kudo and Richardson (2018) that implements both BPE and Unigram. Its key idea is to treat the input as a raw stream, including spaces (represented as ▁), so it needs no language-specific pre-tokenization. That makes it popular for multilingual models such as T5, Llama 2 and Gemma.
Worked Example: Training BPE on a Tiny Corpus
Here's BPE by hand. The training corpus has four words with these counts: low (5), lower (2), newest (6) and widest (3). We start with single characters and count how often each adjacent pair appears, weighted by word frequency.
| Merge | Most frequent pair | Count | Words after the merge |
|---|---|---|---|
| Start | (characters only) | l o w · l o w e r · n e w e s t · w i d e s t | |
| 1 | e + s | 9 (6 in newest + 3 in widest) | l o w · l o w e r · n e w es t · w i d es t |
| 2 | es + t | 9 | l o w · l o w e r · n e w est · w i d est |
| 3 | l + o | 7 (5 + 2) | lo w · lo w e r · n e w est · w i d est |
| 4 | lo + w | 7 | low · low e r · n e w est · w i d est |
| 5 | n + e | 6 | low · low e r · ne w est · w i d est |
(At merge 1, s + t also had a count of 9; real implementations break ties with a fixed rule, and here the first pair found wins.)
After five merges, the vocabulary holds the characters plus five new tokens: es, est, lo, low, ne. Now encode a word that was never in the corpus, lowest. The tokenizer applies the learned merges in order: e s becomes es, es t becomes est, l o becomes lo, and lo w becomes low. The result is two tokens, low + est. That's the strength of subword tokenization: unseen words are built from meaningful pieces seen in training. A real LLM tokenizer does exactly this, with tens or hundreds of thousands of merges learned from billions of words.
LLM Tokenizer Comparison
Each model family has its own LLM tokenizer, and vocabulary sizes have grown over time. These figures come from the models' published configuration files and the tiktoken library:
| Model or encoding | Algorithm / library | Vocabulary size |
|---|---|---|
| BERT base (uncased) | WordPiece | 30,522 |
| GPT-2 | Byte-level BPE | 50,257 |
| Llama 2 | SentencePiece BPE | 32,000 |
GPT-4, GPT-3.5 Turbo (cl100k_base) | Byte-level BPE (tiktoken) | about 100,000 |
| Llama 3 | Byte-level BPE (tiktoken-based) | 128,256 |
| DeepSeek-V3 | Byte-level BPE | 129,280 (model vocab) |
| Mistral NeMo ("Tekken") | Byte-level BPE (tiktoken-based) | 131,072 |
| Qwen3 | Byte-level BPE | 151,936 (model vocab, padded) |
GPT-4o, GPT-4.1, GPT-5, o-series (o200k_base) | Byte-level BPE (tiktoken) | about 200,000 |
gpt-oss (o200k_harmony) | Byte-level BPE (tiktoken) | 201,088 (model vocab) |
| Gemma 3 | SentencePiece | 262,144 |
Why the growth? A bigger vocabulary means common words and multi-word chunks become single tokens, so the same text needs fewer tokens. That gives a longer effective context and faster generation. The cost is a larger embedding table and output layer in the model, and rarer tokens that get less training. Model vocabularies are sometimes padded to a round number for hardware efficiency, so the configured size can exceed the number of tokens actually used.
LLM Tokenizer vs Embedding
People often mix up the two, so here's the LLM tokenizer vs embedding distinction in one line: the tokenizer turns text into integer IDs, and the embedding layer turns each ID into a vector of numbers that carries meaning.
| Tokenizer | Embedding layer | |
|---|---|---|
| Input | Text | Token IDs |
| Output | Integer IDs | Vectors (for example 4,096 numbers per token) |
| Learned how | Counting statistics before model training | Gradient descent during model training |
| Part of the neural network? | No | Yes, the first layer |
| Knows meaning? | No | Yes, similar tokens get similar vectors |
The first layer of every LLM is a lookup table with one row per vocabulary entry. ID 1729 selects row 1729, and that vector flows into the transformer. Separate embedding models, used for search and retrieval, follow the same pattern with their own tokenizer; our embeddings guide explains how those vectors are compared.
Why Tokenizers Matter
Cost and context limits. API prices and context windows are counted in tokens, so the tokenizer decides how much text fits and what it costs. The same prompt can produce a noticeably different token count on two providers' models.
Languages are not treated equally. A NeurIPS 2023 study by Petrov and colleagues found that the same text translated into different languages can differ in tokenized length by up to 15 times, and that GPT-4's tokenizer needed about 3 times as many tokens for Arabic as for English. Speakers of those languages pay more, wait longer and fit less into the context window. Larger, more multilingual vocabularies narrow the gap but don't close it.
Spelling and counting. Models see tokens, not letters. Asked how many r's are in "strawberry", a model has to reason about characters hidden inside two or three tokens, which is why such questions trip them up.
Numbers and code. How digits are grouped into tokens affects arithmetic, and how whitespace is handled affects code. Many recent tokenizers split numbers into single digits or short groups and include tokens for runs of spaces and tabs.
Leading spaces. In GPT-style tokenizers, " hello" and "hello" are different tokens. That's why prompt formatting details, such as a trailing space, can change outputs.
Glitch tokens. Tokens that appear in the tokenizer's training text but almost never in the model's training data get poorly trained embeddings. Researchers found in 2023 that strings such as " SolidGoldMagikarp" made early GPT models behave strangely for exactly this reason.
Using a Tokenizer in Python
You can inspect tokenization yourself. OpenAI's open-source tiktoken library implements its encodings:
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # encoding used by GPT-4o-class models
ids = enc.encode("Tokenizers split text into pieces.")
print(len(ids), ids)
print([enc.decode([i]) for i in ids]) # see each token as text
print(enc.decode(ids)) # round-trips to the original string
enc = tiktoken.encoding_for_model("gpt-4o") # look up the encoding by model nameFor open models, Hugging Face's transformers loads the exact tokenizer that ships with each model:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
print(tok.tokenize("I have a new GPU!")) # WordPiece pieces, with ## marking word-internal parts
print(tok("I have a new GPU!")["input_ids"]) # IDs, including [CLS] and [SEP]For chat models, use the tokenizer's chat template (apply_chat_template) rather than formatting role markers by hand, because each model expects its own special tokens.
Should You Train Your Own Tokenizer?
Almost never for an existing model: a pretrained model only works with the tokenizer it was trained with. You'd train a new one when pretraining a model from scratch, or for a domain where general tokenizers waste many tokens, such as a new language, DNA sequences or a specialised notation. Libraries such as Hugging Face tokenizers and SentencePiece can train one on your corpus in minutes. The main decision is vocabulary size: bigger means shorter sequences and a bigger model.
Adding a handful of new tokens to an existing model (for example domain terms or special markers) is possible, but the model's embedding table has to be resized and the new rows trained, usually during fine-tuning.
Common Tokenizer Mistakes
- Using the wrong tokenizer for a model. IDs will map to the wrong embeddings and output becomes nonsense.
- Estimating limits with word counts. Count tokens with the model's own tokenizer before sending long prompts.
- Assuming tokens are the same across providers. Budget and context calculations don't transfer between models.
- Forgetting special tokens and chat templates, which shifts the model away from the format it was trained on.
- Adding tokens without resizing the embedding matrix, which crashes training or produces garbage.
- Ignoring non-English costs when planning a multilingual product.
FAQ
What does a tokenizer do in an LLM?
It converts text into the integer token IDs the model reads, adds special tokens, and converts the model's output IDs back into text. It decides how text is split, how many tokens a prompt uses and how the model "sees" words.
Is the tokenizer part of the model?
It ships with the model and must match it, but it isn't part of the neural network. It's a separate, rule-based component learned before training. The model's first layer, the embedding table, is built around the tokenizer's vocabulary.
How many tokens is a word?
For English text with modern tokenizers, a common word is usually one token and longer or rarer words two or more. Other languages, code and numbers often need more tokens per word.
Can you change a model's tokenizer?
Not without retraining. The model learned what each ID means, so a new tokenizer would require retraining at least the embedding layer, and usually much more.
What's the difference between tokenization and embedding?
Tokenization splits text into tokens and assigns IDs. Embedding maps those IDs to dense vectors that capture meaning. Tokenization comes first; embedding is the first step inside the model.