What Is a Tokenizer? How LLMs Split Text Into Tokens (BPE)

By LatestLLM Editorial · Published · Facts verified · 9 min read

Also called: BPE, byte-pair encoding, tokenisation, SentencePiece, tiktoken

Before this: Token

In one line

A tokenizer is the program that splits text into tokens and maps each one to an id, using a vocabulary learned once before the model is trained.

Tokenizer, simply and technically

In plain English

Before a language model can read anything, a separate program called the tokenizer cuts your text into tokens and swaps each one for a number. When the model answers, the same tokenizer turns the numbers it produced back into readable text. The model itself never sees letters at all.

The tokenizer decides which pieces exist. It is built by scanning a huge amount of text and repeatedly gluing together the pairs of characters that appear side by side most often, until it has a list of a few hundred thousand useful pieces. Frequent words end up as single pieces; rare words have to be spelled out from smaller ones.

Think of it like this: A tokenizer works like a shorthand system invented by a court reporter. After transcribing for years, the reporter has a quick symbol for every common word and phrase, and falls back to spelling out unfamiliar names letter by letter. The shorthand is fixed once it is learned: the reporter does not invent new symbols in the middle of a trial.

Everyday example: Same idea, different number of pieces

Two short messages pass through GPT-4o's tokenizer.

Input:

I love strawberries
tokenization

Output:

I | love | strawberries  (3 pieces)
token | ization  (2 pieces)

What it shows: "strawberries" was common enough in the tokenizer's training text to earn its own piece, while "tokenization" is built from "token" plus the familiar ending "ization". The tokenizer reuses pieces it already knows rather than storing every word.

Technically

Most current LLMs use byte-level byte-pair encoding (BPE). Training starts from the 256 possible byte values, counts adjacent symbol pairs over a large corpus, and repeatedly adds the most frequent pair as a new symbol until the target vocabulary size is reached. Encoding applies the learned merges in order; decoding concatenates the bytes of each id. Because the base alphabet is bytes, every input string is representable.

Before merging, a regex pre-tokenizer splits text into chunks, for example separating letters from digits and keeping a leading space attached to a word, so merges never cross chunk boundaries. OpenAI's o200k_base (GPT-4o, and gpt-oss with extra special tokens) has 200,019 entries; DeepSeek-V3 uses byte-level BPE with 129,280 entries; Gemma models use a SentencePiece vocabulary of 262,144 entries.

Technical example: Learning four BPE merges from scratch

Run the BPE training loop on the toy corpus from Sennrich et al. (2016): low x5, lower x2, newest x6, widest x3.

Code (python):

from collections import Counter

words = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
corpus = {tuple(w): n for w, n in words.items()}

def best_pair(corpus):
    pairs = Counter()
    for symbols, n in corpus.items():
        for a, b in zip(symbols, symbols[1:]):
            pairs[a, b] += n
    return pairs.most_common(1)[0]

def merge(corpus, pair):
    out = {}
    for symbols, n in corpus.items():
        s, i = [], 0
        while i < len(symbols):
            if symbols[i:i + 2] == pair:
                s.append(symbols[i] + symbols[i + 1]); i += 2
            else:
                s.append(symbols[i]); i += 1
        out[tuple(s)] = n
    return out

for step in range(1, 5):
    pair, count = best_pair(corpus)
    corpus = merge(corpus, pair)
    print(step, pair, count, list(corpus))

Output:

1 ('e', 's') 9
2 ('es', 't') 9
3 ('l', 'o') 7
4 ('lo', 'w') 7
final: low | low e r | n e w est | w i d est

What it shows: The pair e+s appears 9 times (6 in newest, 3 in widest), so it is merged first, then es+t. After four merges the frequent word "low" is a single symbol and the suffix "est" is reusable across words. A production tokenizer runs the same loop over bytes for about 200,000 merges.

Watch a real tokenizer split your text. Type any text to see it split into coloured tokens with their ids, using GPT-4o's o200k_base tokenizer running locally in the browser. Hover a token to see its id and the exact characters it covers, including the leading space. Live output of the o200k_base byte-level BPE tokenizer (the same encoding gpt-oss builds on).

What a tokenizer does

In plain English: A tokenizer has two jobs. Going in, it turns your text into a list of numbers. Coming out, it turns the model's numbers back into text. It does this the same way every time, so the same sentence always becomes the same numbers for a given model.

Technically:

The tokenizer implements encode: str -> list[int] and decode: list[int] -> str with decode(encode(s)) == s for every string. It is not learned jointly with the network. It is trained once, frozen, and shipped with the weights as files such as tokenizer.json or a tiktoken rank file, and the model's embedding matrix has exactly one row per id.

In chat products the tokenizer also renders the chat template: system, user and assistant turns are wrapped in special tokens before encoding. gpt-oss uses OpenAI's harmony format for this, which is why its vocabulary is padded beyond o200k_base's 200,019 entries.

Go deeper: details for practitioners
  • Because the embedding and output layers are sized to the vocabulary, swapping a tokenizer after pre-training means re-learning those layers. Extending a vocabulary for a new language is possible but requires further training of the new rows.
What is detokenization?

Turning token ids back into text by concatenating the bytes each id stands for.

What is a chat template?

The exact layout of special tokens and role markers a chat model was trained with, applied by the tokenizer before encoding a conversation.

How byte-pair encoding builds a vocabulary

In plain English: Byte-pair encoding starts with single characters and looks for the two that appear next to each other most often. It glues them into one new piece, then looks again. After hundreds of thousands of rounds the list contains whole common words, common word endings like "ing" and "ization", and every single character as a fallback.

Think of it like this: BPE is like a word game where you may only ever stick two existing tiles together, always choosing the pair you have seen most often so far.

Technically:

BPE was introduced for neural machine translation by Sennrich, Haddow and Birch (2016) to handle rare words with a fixed vocabulary. GPT-2 (Radford et al., 2019) made it byte-level: the initial symbols are the 256 byte values rather than Unicode characters, which removes the need for an unknown token. Each merge is recorded with its rank, and encoding greedily applies the lowest-ranked available merge until none applies.

The merge list is the whole model of the tokenizer. Its order reflects corpus statistics, which is why the training mix matters: a tokenizer trained mostly on English produces compact sequences for English and longer ones for under-represented scripts, which in turn raises the cost and lowers the effective context for those languages.

Go deeper: details for practitioners
  • Training on bytes means a single Chinese or Hindi character, which takes three bytes in UTF-8, may need several merges before it becomes one token. If those merges never happened, the character stays split across tokens.
What is a merge rank?

The position of a merge in the learned list. Lower ranks were more frequent in training and are applied first during encoding.

Pre-tokenization and special tokens

In plain English: Before gluing pieces together, the tokenizer first splits text at sensible boundaries, such as between words and numbers, so it never creates strange pieces that run across two words. It also has a small set of reserved markers that mean things like "end of message" rather than any real text.

Technically:

Byte-level BPE tokenizers run a regular expression first. It separates letters, digits, punctuation and whitespace, keeps an optional leading space with the next word, and in o200k_base groups digits into runs of up to three. Merges are applied only inside these chunks, which keeps tokens linguistically sensible and makes encoding fast.

Special tokens are inserted by id and bypass the regex and merges entirely. Tokenizer libraries normally refuse to encode their literal text from user input, so a user cannot forge an end-of-turn marker by typing it.

Technical example: Pre-tokenization keeps digits and words apart

Encode a calendar date with o200k_base.

Input:

2026-11-23

Output:

202 | 6 | - | 11 | - | 23

What it shows: The digit rule caps runs at three digits, so 2026 splits into 202 and 6, and each hyphen is its own chunk.

Go deeper: details for practitioners
  • SentencePiece (Kudo and Richardson, 2018) takes a different route: it treats the input as a raw stream, marks spaces with a visible symbol, and can learn either BPE merges or a unigram language model over pieces. It is common in Google's model families.

Choosing a vocabulary size

In plain English: A bigger vocabulary means more whole words get their own piece, so messages become shorter and cheaper to process. But every extra piece needs its own slot of memory inside the model, so builders pick a size that balances the two.

Technically:

Vocabulary size V sets the embedding matrix at V x d and, unless tied, an output projection of the same size. For gpt-oss that is 201,088 x 2,880, about 579 million parameters per matrix; for Gemma 4 31B it is 262,144 x 5,376, about 1.41 billion, shared between input and output because Gemma ties them. The final softmax also runs over all V entries for every generated token.

Larger vocabularies shorten sequences, which reduces attention cost and stretches the effective context, and they help multilingual coverage. The trend has moved from GPT-2's 50,257 entries to 129K to 262K in current open models, as models grew large enough that the embedding table is a small fraction of total parameters.

What are tied embeddings?

Using the same matrix for the input embedding lookup and the output projection that scores the next token, which saves parameters.

Common misconceptions

  • Myth: The model learns to tokenize while it trains.

    Reality: The tokenizer is trained separately and frozen before model training begins; the network only ever receives its output ids.

  • Myth: Tokenizers split text at spaces and punctuation, like a dictionary.

    Reality: They split into statistically frequent pieces, which can be whole words, word parts, single bytes or a space joined to a word.

  • Myth: Any tokenizer works with any model.

    Reality: A model's embedding rows are tied to its own vocabulary ids, so using a different tokenizer produces meaningless input.

Where you'll see this

Key takeaways

  • The tokenizer is a separate, fixed component that converts text to token ids and back; the neural network only sees the ids.
  • Byte-pair encoding builds the vocabulary by repeatedly merging the most frequent adjacent pair, so common words become single tokens and rare words split into reusable pieces.
  • Working on bytes means any text, in any language or format, can be encoded without an unknown-token placeholder.
  • The vocabulary size is a trade-off: a bigger vocabulary gives shorter sequences but a larger embedding table and output layer.

Frequently asked questions

What is the difference between a token and a tokenizer?

A token is one piece of text with an id. The tokenizer is the program and vocabulary that produce those pieces from text and turn them back into text.

Which tokenizer does GPT-4o use?

GPT-4o uses the o200k_base byte-level BPE encoding, published in OpenAI's open-source tiktoken library.

Why are non-English languages often more expensive?

If a language was less common in the tokenizer's training text, fewer of its words became single tokens, so the same meaning needs more tokens.

What is SentencePiece?

A tokenizer library from Google that works directly on raw text, treats spaces as symbols and supports BPE and unigram vocabularies. Gemma models use it.

Can a tokenizer fail on unusual input?

A byte-level tokenizer cannot fail: any byte sequence can be encoded, at worst one byte per token.

Sources

Facts last verified November 23, 2026.

Next concept: Embedding

Learn next

  • Embedding (Beginner): An embedding is a list of numbers, a vector, that represents a token or a piece of text so that things with similar meaning end up close together.
  • Transformer (Intermediate): A transformer is a neural network built from a stack of identical blocks, each mixing information between tokens with attention and then refining each token on its own.