How a Tokenizer Turns Text into Tokens
Why tokenizers use subwords, how they learn a vocabulary, and what that means for errors, languages, characters, and context length.
Contents
- Why not use whole words or characters
- How a BPE tokenizer learns its subwords
- What else a real tokenizer does
- Which alternatives to BPE exist
- What determines tokenizer quality
- What happens with errors, symbols, and languages
- Why spelling and counting letters can be difficult
- Summary: what Embedding receives
- References
Before a conversation enters the network, the application serializes it with instructions, messages, and role labels. The result is still text. A tokenizer splits it into pieces and replaces each one with an integer: its id in a vocabulary.
The tokenizer is not interpreting the message. It applies a procedure built in advance and returns a sequence such as this one, using a toy vocabulary:
| Text piece | Token id |
|---|---|
Hi | 0 |
! | 4 |
Hello | 1 |
How | 6 |
With that vocabulary, Hi! becomes [0, 4]. The model still has no representation of meaning, just two identifiers. But this split shapes everything that follows: which information is directly exposed, how many positions the network must process, and how much text fits in the context window.
Why not use whole words or characters
Assigning an id to every word seems like the obvious choice. Real text quickly exposes the problem: names, inflections, plurals, code, misspellings, and words that did not exist when the vocabulary was built. A closed dictionary of words keeps meeting new entries. Growing it forever does not solve the problem either. The model must learn a larger table, and rare words often appear too few times to estimate their representations well.
Characters offer the opposite extreme. A small vocabulary can represent almost any text, but sequences become much longer. The network must process every letter and reconstruct recurring units that were already visible as words or fragments in the original text.
Subwords are the compromise. A frequent word such as Hello can occupy one token, while a rare word can be assembled from known pieces without necessarily falling back to every letter. Sennrich, Haddow, and Birch popularized this approach in machine translation, using byte-pair encoding, or BPE, to handle rare words and open vocabularies [1]. The method proved useful far beyond translation because it kept the vocabulary finite without excluding all new text.
How a BPE tokenizer learns its subwords
Byte-pair encoding is a compression technique later adapted to build vocabularies. Its central operation is simple: when two adjacent symbols frequently occur together, replace them with a new symbol that represents their merger. A frequent sequence then occupies one unit instead of two.
Despite the name, the initial symbols in tokenization can also be Unicode characters rather than bytes. A “pair” is not a pair of words, but two adjacent units in whatever representation we are using. Training BPE does not mean training a neural network: there are no gradients or weights to update, only frequencies to count and mergers to record.
Before a real tokenizer adds normalization and preprocessing details, the basic procedure is:
- Start with characters or bytes as the initial symbols.
- Count adjacent pairs and find the most frequent one.
- Merge its occurrences into a new symbol and record that rule.
- Repeat until the chosen vocabulary size is reached.
For example, suppose the corpus contains ab abc ab abcd. Ignoring word separators, we start with these sequences:
a b | a b c | a b | a b c d
The pair a b occurs four times, more than any other. The first merger creates the symbol ab, and the corpus becomes:
ab | ab c | ab | ab c d
If we continue, the pair ab c occurs twice and can produce abc. The vocabulary now contains more than letters: it stores the frequent combinations ab and abc, along with the order in which the mergers must be applied.
That order matters when processing new text. The tokenizer does not choose fragments for their meaning or retrain itself on every prompt; it replays the learned rules. Frequent mergers let common words become compact tokens, while rare words are assembled from smaller fragments.
Because the vocabulary and merger order are fixed, the same string normally produces the same segmentation every time. The tokenizer does not seek a different split based on the conversation’s topic.
There is no universal “token for Hello”. One tokenizer may store it whole, another may split Hell and o, and a third may use a different token when the word has a leading space. Capitalization, spaces, and line breaks are part of the input and can change the ids.
What else a real tokenizer does
BPE is only one part of the processing. A complete implementation can be organized as a chain of stages:
text
→ normalization
→ pre-tokenization
→ subword model
→ post-processing and special tokens
→ ids
Normalization can change capitalization or Unicode forms before segmentation. Without it, two strings that look identical can produce different ids: café may contain é as one unit or e followed by a combining accent. Normalization and segmentation are different operations.
Pre-tokenization establishes certain boundaries before applying the subword model, for example by separating spaces or punctuation. Our ab example ignores those boundaries; a real implementation may prevent mergers from crossing words or treating the whole prompt as one string.
Post-processing adds or recognizes special tokens. This includes start and end markers, padding tokens used to equalize batches, and labels such as <|assistant|>. These tokens are usually added explicitly to the vocabulary so they do not fragment. Their function does not come from BPE: the application assigns them a role, and the model learns the associated patterns during training.
The tokenizer also performs the reverse operation. After the model generates ids, detokenization turns them back into text. This is not the decoding rule that chooses which token to generate. Some control tokens mark an ending or structure the conversation and are omitted from the visible text.
Which alternatives to BPE exist
BPE is our main example, not a mandatory definition of tokenization. WordPiece also builds a subword vocabulary, but selects units according to their usefulness for a probabilistic model of the corpus rather than just the pair’s frequency. A unigram model uses another strategy: start with many candidates and remove the least useful ones according to the probabilistic cost of segmenting the data.
SentencePiece belongs at another level. It is an implementation that can train BPE or unigram models directly from raw sentences without requiring prior word segmentation [2]. That is especially useful for languages that do not mark boundaries with spaces. It does not remove frequency differences in the corpus, but it avoids language-specific pre-tokenization.
Even with a fixed vocabulary, several segmentations can be valid. Subword regularization exploits that ambiguity by sampling different splits during neural model training, reducing dependence on any single one [3]. Deterministic segmentation therefore describes normal inference, not every possible training procedure.
What determines tokenizer quality
Vocabulary size has a cost. A large vocabulary can represent more complete words and produce shorter sequences, but it needs more embedding rows and more LM head outputs. A small vocabulary shrinks those tables at the cost of splitting text into more positions. There is no optimal size independent of language, data, model width, and compute budget.
The corpus leaves another mark. Frequent sequences earn compact representations; infrequent ones fragment more. Two tokenizers using the same algorithm can behave very differently if one was trained mainly on English prose and the other on code or multilingual text.
Comparing tokenizers requires more than counting their entries. We need to measure at least:
- Coverage: how much text they can represent without falling back to
<unk>. - Fertility and compression: how many tokens they need per word or per comparable amount of text.
- Distribution: which languages, domains, or content types fragment more.
- Downstream result: how the model trained on that representation changes in quality, not just speed.
Once chosen, the tokenizer usually stays fixed while the model is trained and used. Replacing it is not like swapping an isolated formatting function. It changes the input ids, the number of embedding rows required, and the vocabulary outputs. The model must adapt to that new mapping.
What happens with errors, symbols, and languages
A spelling error does not activate a spelling corrector. The tokenizer applies the same rules it uses for every other input. If no token covers the whole word, it falls back to smaller pieces. These segmentations are illustrative rather than the rules of a particular model:
| Input | Possible segmentation | What changes for the model |
|---|---|---|
Hello | Hello | A frequent form may occupy one token. |
Helo | Hel + o | The misspelling may arrive as several pieces. |
Modbus_CRC16() | Mod + bus + _ + CRC + 16 + ( + ) | Code identifiers and punctuation are fragmented too. |
🕷️ | One or more Unicode or byte tokens | An emoji does not necessarily occupy one position. |
An unfamiliar symbol does not create a new vocabulary row during the conversation. Three similar-sounding mechanisms are worth distinguishing:
- Byte-level BPE: starts with bytes to cover any text, but still merges them into learned subwords.
- Byte fallback: represents input the vocabulary does not cover with byte tokens.
- Byte models: process bytes directly without a learned subword vocabulary.
A tokenizer without complete coverage may use <unk>; in that case, some of the original distinction is lost. Bytes preserve a representation of the string, although it may need more positions.
Languages pose the same coverage problem on a larger scale. If the tokenizer’s corpus contains little text in a language, a sentence in that language may need more tokens than an equivalent sentence elsewhere. It consumes the context window sooner and requires more work to process and generate. Token count is not a neutral measure of text length across languages.
Why spelling and counting letters can be difficult
Even if we can reverse the conversion, the model does not necessarily receive a list of characters. If Hello arrives as one id, its five letters do not appear as five separate inputs. To spell it or count its characters, the network must recover a structure that exists in the original text but is not directly exposed in that initial representation.
The distinction resembles seeing ultraviolet light versus measuring it. Some birds detect it and we do not, yet we can build instruments that measure it. Lack of direct access does not make the information unreachable.
A 2025 study found that several LLMs could spell tokens accurately even though the embedding layer did not encode all their character information. Some of that information, especially after the first letter, was reconstructed in intermediate and higher layers [4]. The same study found difficulties with more complex character-level tasks. Recovering letters in some cases does not make the initial representation equivalent to always receiving text character by character.
When that recovery is insufficient, the application can separate letters before sending them or use a tool to count them. The input architecture can change too. ByT5 processes bytes directly and improves spelling- and pronunciation-sensitive tasks at the cost of longer sequences [5]. Byte Latent Transformer starts with bytes and groups them into dynamically sized patches, avoiding a fixed subword vocabulary [6]. These alternatives show that subword tokenization is a compromise, not an inevitable property of every language model.
Summary: what Embedding receives
After this step, the serialized text has become a sequence of ids. The tokenizer has fixed which pieces form the input, which identifier each piece receives, and how many positions the network must process.
The numbers themselves carry no meaning or measure of similarity. Giving Hi id 0 and Hello id 1 does not make them more similar than any other pair. Each id is an address in the vocabulary. Embedding uses that address to retrieve the token’s learned vector, where the numerical representation used by later blocks begins.
References
- Sennrich, Haddow, and Birch, “Neural Machine Translation of Rare Words with Subword Units,” ACL 2016 (opens in a new tab).
- Kudo and Richardson, “SentencePiece: A Simple and Language Independent Subword Tokenizer and Detokenizer for Neural Text Processing,” EMNLP 2018 (opens in a new tab).
- Kudo, “Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates,” 2018 (opens in a new tab).
- Hiraoka and Inui, “Spelling-out is not Straightforward: LLMs’ Capability of Tokenization from Token to Characters,” Findings of EMNLP 2025 (opens in a new tab).
- Xue et al., “ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models,” TACL 2022 (opens in a new tab).
- Pagnoni et al., “Byte Latent Transformer: Patches Scale Better Than Tokens,” 2024 (opens in a new tab).