Skip to content

Chapter 4 · Tokenization and Vocabulary

4.1 Why do LLMs use subword tokenization? ★★

One-sentence answer

A model can only process discrete token IDs, and tokenization decides which units the text is cut into. Word-level tokenization makes the vocabulary enormous and still runs into words that are not in it; character-level tokenization makes sequences far too long, with each token carrying almost no meaning. Subword tokenization is the compromise: frequent words stay whole and rare words are split into meaningful pieces, which balances vocabulary size, sequence length and out-of-vocabulary words.

I will address three aspects: where tokenization sits in the model, what goes wrong at the two extremes of words and characters, and why subwords are the better compromise.

(1) Tokenization turns text into IDs the model can process, and its granularity determines both vocabulary size and sequence length.

A model cannot read text directly. On the input side, the tokenizer cuts the text into tokens, each token maps to an ID in the vocabulary, and that ID is used to look up a vector in the embedding table; on the output side, the LM head computes the probability of the next token over the whole vocabulary. The granularity of tokenization therefore directly determines two key quantities. One is the vocabulary size \(V\), which sets the parameter count of the embedding table and the LM head, as well as the cost of the softmax at every step. The other is the sequence length, which sets the cost of attention (quadratic in length), how much content fits into a given context window, and how many decoding steps it takes to generate the same content. The two pull in opposite directions: coarser units mean a larger vocabulary and shorter sequences, and finer units mean a smaller vocabulary and longer sequences.

(2) Both extremes, word-level and character-level tokenization, have serious problems.

  • Word-level tokenization: One token per word gives clear meaning, but inflections (run, runs, running), compounds, names, typos and new words keep appearing, so the vocabulary has to be huge, and the model will still meet words that are not in it (out-of-vocabulary, OOV), which can only be replaced by [UNK], losing the information entirely. Moreover, run and running become two unrelated tokens, so the model cannot share knowledge between them.
  • Character-level tokenization: The vocabulary is tiny and there is no OOV, but sequences become very long; for English they are about 4 times longer than with subwords. The cost of attention therefore rises sharply, a context window holds far less content, and the number of decoding steps multiplies; moreover, a single character carries almost no meaning, so the model has to spend more layers assembling characters into meaningful units.

(3) Subword tokenization allocates granularity by frequency, and so gets the best of both.

Subword tokenization keeps frequent words whole as single tokens and splits rare words into a few meaningful pieces, for example unhappiness into un + happi + ness. Common stems and affixes are then shared across words; as long as the base units cover every character (or every byte, see 4.3), any text can be tokenized and OOV never occurs; and the vocabulary can be kept between tens of thousands and a couple of hundred thousand entries. In effect, it is a compression scheme that assigns code length by frequency: common strings get a single token, while rare strings fall back to smaller pieces. Modern tokenizers average about 4 characters per token on English; the Llama 3 tokenizer, for example, achieves 3.94 characters per token (Dubey et al. 2024).

In summary: subword tokenization is essentially a compression scheme that allocates granularity by frequency, keeping both vocabulary size and sequence length in a reasonable range without any OOV.

Going deeper: comparing the three granularities, and how to measure tokenizer efficiency

(1) Comparing the three granularities.

Word-level Character-level Subword
Vocabulary size Enormous, and never complete Tiny Manageable (about 30K to 250K)
Out-of-vocabulary words Yes, replaced by [UNK] None None (provided the base units cover every character or byte)
Sequence length Shortest Longest (about 4 times subwords for English) Moderate
Meaning of a single token Complete Almost none Complete for common words, meaningful pieces for rare ones
Sharing across inflections None Yes, but the model must compose it Yes, through shared stems and affixes

(2) Tokenizer efficiency is usually measured by the compression rate.

The compression rate is usually expressed as characters per token or bytes per token; the larger it is, the fewer tokens the same text needs. It has to be measured separately for each language and domain, because the same tokenizer can compress English, Chinese and code very differently (see 4.4).

Follow-up questions

Follow-up 1: If character-level tokenization has no OOV, why not train the model directly on bytes or characters?

Because the sequences are too long and the compute cost is too high. Byte-level sequences are about 4 times longer than subword sequences, attention cost grows quadratically with length, and the same compute reads far less text. This direction is still actively researched, however: ByT5 (Xue et al. 2021) trains directly on UTF-8 bytes, and the Byte Latent Transformer (Pagnoni et al. 2024) uses no fixed vocabulary at all, instead grouping bytes dynamically into patches according to the entropy of the next-byte prediction, with long patches for predictable stretches and short patches for hard ones; at the 8B scale it matches the tokenizer-based Llama 3 while being more efficient at inference and more robust to noisy input. Mainstream LLMs, however, still use subword tokenization.

Follow-up 2: Is the tokenizer trained together with the model?

No. The tokenizer is trained separately before the model, on a sample of the corpus with a statistical algorithm (such as BPE, see 4.2), and then frozen; the model then learns embeddings for that vocabulary's IDs. This has two consequences: the tokenizer and the model are bound together, so switching tokenizers is like switching dictionaries and all the old embeddings become useless; and the mix of languages and domains in the tokenizer's training corpus decides which text it compresses well (see 4.4).

Follow-up 3: Can perplexities of models with different tokenizers be compared directly?

No. Perplexity is averaged per token, and the larger the vocabulary, the more text each token covers, so each token is harder to predict and perplexity is naturally higher, which does not mean the model is worse. Comparisons across tokenizers should convert to a byte-normalized metric such as bits-per-byte (see Chapter 2 of the LLM Training Pipeline direction).

Common mistakes

  • Do not say that subword tokenization has no OOV by nature: This holds only when the base units cover every character or byte; a BPE whose base units are characters still produces OOV on characters it never saw in training, which is exactly the problem byte-level BPE solves (see 4.3).
  • Do not equate tokens with words: In English a token averages about 4 characters, and many words are split into several tokens; in Chinese a token may be a word, a single character, or even part of one character's bytes.
  • Do not say that a larger vocabulary is always better: A larger vocabulary makes the embedding and output layer more expensive and makes rare tokens harder to train well (see 4.4).

4.2 How does BPE work, and how does it differ from WordPiece and Unigram? ★★

One-sentence answer

BPE starts from characters (or bytes) and repeatedly finds the most frequent adjacent token pair in the corpus and merges it into a new token, until the vocabulary reaches its target size, producing a vocabulary and an ordered list of merge rules; to tokenize, it applies those merge rules in the order they were learned. WordPiece also merges bottom-up, but chooses the pair that most increases the corpus likelihood; Unigram goes the other way, starting from a large vocabulary, pruning top-down the tokens whose removal hurts the corpus likelihood least, and taking the most probable segmentation. SentencePiece is a library that implements BPE and Unigram, not a new algorithm.

I will address three aspects: how BPE is trained and how it tokenizes, how WordPiece and Unigram differ from it, and what SentencePiece actually is.

(1) BPE builds its vocabulary by repeatedly merging the most frequent adjacent token pair.

BPE (Byte Pair Encoding) was originally a data-compression algorithm, and Sennrich et al. (2015) brought it into NLP. Training starts by splitting every word in the corpus into single characters, so the initial vocabulary is the set of all characters; it then counts every adjacent token pair in the corpus, merges the most frequent pair into a new token, adds it to the vocabulary and records this merge rule, and repeats until the vocabulary reaches the preset size. For example, if newest and widest appear often in the corpus, e and s are adjacent most often, so es is merged first, and then es and t merge into est; if low and lower are also common, l + o merges into lo and lo + w into low. Then even though lowest never appeared in the training corpus, it can be split into low + est. Training produces a vocabulary and an ordered list of merge rules. To tokenize new text, it is first split into characters, and the merge rules are applied in the order they were learned until nothing more can be merged. The process is deterministic: the same text always gets the same split. BPE is simple, fast and compresses well, with frequent fragments naturally becoming tokens; its limitations are that merging is purely greedy by frequency, so the resulting split does not always match linguistic intuition, and each word has only one possible segmentation.

(2) WordPiece and Unigram differ from BPE in their selection criterion and in the direction of construction.

  • WordPiece also merges bottom-up, but selects by likelihood gain rather than frequency: WordPiece (Schuster & Nakajima 2012) is the tokenizer used by BERT, with a vocabulary of about 30K. At each step it merges the pair that most increases the likelihood of the training corpus, which in practice is often approximated by "the co-occurrence count divided by the product of the two parts' individual counts" (the formula is in "Going deeper" below). Two fragments that are each very common are therefore not merged merely because they happen to be adjacent often; only fragments that "almost always appear together" are merged. When tokenizing, WordPiece starts at the beginning of a word and greedily matches the longest fragment in the vocabulary each time, with fragments inside a word carrying a ## prefix, e.g. playing becomes play + ##ing.
  • Unigram prunes top-down and is itself a probabilistic model: Unigram (Kudo 2018) starts from a large candidate vocabulary (for example, all frequent substrings) and assumes each token occurs independently with its own probability. A word can be split in many ways, the probability of a split is the product of its tokens' probabilities, and tokenization uses dynamic programming to find the most probable split. Training estimates each token's probability with the EM algorithm, then computes how much the corpus likelihood would drop if each token were removed, deletes the batch of tokens whose removal hurts least in each round, and continues until the vocabulary shrinks to the target size. Because it is a probabilistic model, the same word can be sampled into different splits according to their probabilities, and deliberately using different splits during training (subword regularization) makes the model more robust to how text is segmented.

(3) SentencePiece is a library, and its most important design choice is to treat the space as an ordinary character.

SentencePiece (Kudo & Richardson 2018) is often mentioned together with Unigram, but it is actually a tokenization library that implements both BPE and Unigram. Its most important design choice is to treat the input as a raw stream of characters, with the space treated as an ordinary symbol (replaced by ▁), so the text does not need to be pre-split on spaces. It therefore works just as well for languages such as Chinese and Japanese that do not separate words with spaces, without any language-specific preprocessing; and tokenization is fully reversible, since joining the tokens and turning ▁ back into spaces recovers the original text exactly. For example, T5 uses SentencePiece's Unigram, and Llama 1 and Llama 2 use SentencePiece's BPE.

In summary: the three algorithms differ in direction (BPE and WordPiece merge bottom-up, Unigram prunes top-down) and in criterion (BPE looks at frequency, WordPiece and Unigram at corpus likelihood); most mainstream LLMs today use BPE, more specifically byte-level BPE (see 4.3).

Going deeper: the WordPiece and Unigram formulas, and a comparison of four schemes

(1) The WordPiece merge score.

\[ \mathrm{score}(a, b) = \frac{\mathrm{count}(ab)}{\mathrm{count}(a) \times \mathrm{count}(b)} \]

Here \(\mathrm{count}(ab)\) is how often fragments \(a\) and \(b\) appear adjacent, and \(\mathrm{count}(a)\) and \(\mathrm{count}(b)\) are how often each fragment appears on its own. If \(a\) and \(b\) are each very common, the denominator is large, and even frequent adjacency does not give a high score; the score is high only when they rarely appear apart and almost always appear together. BPE effectively looks only at the numerator.

(2) The Unigram segmentation probability.

\[ P(x_1, \dots, x_k) = \prod_{i=1}^{k} p(x_i), \qquad x^* = \arg\max_{x \in S(w)} P(x) \]

Here \(w\) is the word to segment, \(S(w)\) is the set of all its possible segmentations, \(x = (x_1, \dots, x_k)\) is one segmentation, \(p(x_i)\) is the probability of token \(x_i\), and \(x^*\) is the most probable segmentation, found with Viterbi dynamic programming.

(3) Comparing four schemes.

BPE WordPiece Unigram Byte-level BPE
Direction Bottom-up merging Bottom-up merging Top-down pruning Bottom-up merging
Criterion Most frequent adjacent pair Adjacent pair with the largest likelihood gain Tokens whose removal reduces likelihood least Most frequent adjacent pair
Segmentation Apply merges in order, deterministic Greedy longest match Most probable split, can also sample Apply merges in order, deterministic
Unseen characters OOV possible [UNK] possible OOV possible (byte fallback helps) Never: 256 bytes cover everything
Used by Original subword machine translation BERT T5 (via SentencePiece) GPT-2 and later GPT models, Llama 3, Qwen, DeepSeek

Follow-up questions

Follow-up 1: Why does BPE tokenize by applying merges in their training order, rather than simply taking the longest match in the vocabulary?

Because the merge order encodes priority, and only merging in the same order reproduces the segmentations the model saw in training. The model was trained on token sequences produced by BPE, so tokenization at inference must match exactly; with longest match, the same word might be split into a different set of tokens, and even if all of them are in the vocabulary, the model has rarely seen that combination and performs worse. Merging in order also guarantees that every intermediate token is in the vocabulary.

Follow-up 2: What are subword regularization and BPE-dropout?

They deliberately use different segmentations during training to make the model robust to how text is split. Subword regularization (Kudo 2018) uses Unigram's probabilistic model to sample different splits of the same word; BPE-dropout (Provilkov et al. 2019) randomly skips some merges during BPE tokenization, so the same word appears with several splits. They improve robustness to typos and rare words in machine translation, but are rarely used in mainstream LLM pretraining; DeepSeek-V3's practice of randomly splitting some merged tokens during training follows a similar idea (see 4.4).

Follow-up 3: What should you watch out for when training a tokenizer?

The key points are a representative training corpus and a few rules fixed in advance. The training corpus should cover the languages, code and math the model will handle, in sensible proportions, or the corresponding text will be split into many small pieces; the pre-tokenization rules (for example how digits are grouped and how whitespace is handled, see 4.3 and 4.4) must be decided beforehand; and special tokens should be reserved, such as the tokens that mark roles and boundaries in a chat template. After training, the compression rate should be measured per language and domain, and one should check for tokens that are common in the tokenizer's corpus but almost absent from the model's training corpus, since their embeddings will be under-trained and can cause abnormal outputs (see 4.4).

Common mistakes

  • Do not describe SentencePiece as an algorithm on a par with BPE: It is a library that implements BPE and Unigram.
  • Do not say that BPE picks different segmentations depending on context: The same string always gets the same split; it is Unigram that can sample several splits.
  • Do not describe WordPiece's merge criterion as raw frequency: It uses the likelihood gain, i.e. co-occurrence relative to the two parts' individual frequencies.
  • Do not say that Unigram merges bottom-up: It starts from a large vocabulary and prunes top-down.

4.3 What problem does byte-level BPE solve? ★

One-sentence answer

A BPE whose base units are characters produces OOV whenever it meets a character it did not see in training (a rare character, an emoji, another script), and Unicode has about 150K characters, far too many to put all of them into the base vocabulary. Byte-level BPE (introduced with GPT-2) switches the base unit to UTF-8 bytes: every string is a sequence of the 256 possible bytes, so any input can be encoded and OOV disappears entirely. The costs are that a rare character that was never merged takes several tokens, and that a single token may be only part of a character's bytes.

I will address three aspects: the problem it solves, how it works, and what it costs.

(1) The problem: when the base units are characters, the base vocabulary cannot cover every Unicode character.

BPE's initial vocabulary is the set of all characters, and OOV can be ruled out only if the base units cover every character in the input. Unicode, however, contains about 150K characters spanning many scripts, symbols and emoji. Putting all of them into the base vocabulary would use up most of the vocabulary budget, even though the vast majority of them are extremely rare; putting in only the common ones means any character unseen in training can only map to [UNK]. For an LLM that has to handle multilingual text, code, emoji and even garbled text, this problem comes up all the time in practice.

(2) How it works: use the 256 bytes as the base vocabulary, and pre-tokenize before merging.

Under UTF-8, any text is a sequence of bytes: an ASCII character takes 1 byte, a common CJK character takes 3 bytes, and an emoji usually takes 4 bytes. Byte-level BPE (Radford et al. 2019) uses these 256 possible bytes as the initial vocabulary and then learns merge rules on byte sequences just as ordinary BPE does, so common characters, words and word pieces are gradually merged into single tokens. Whatever the input, the worst case is to fall back to one token per byte, so OOV never happens. GPT-2's vocabulary has 50,257 entries, and later GPT models, Llama 3, Qwen and DeepSeek all adopted this scheme. Another important detail is pre-tokenization: before running BPE, a regular expression splits the text into categories such as letter runs, digit runs, punctuation and whitespace, and merges happen only within each piece. Otherwise BPE might learn tokens like dog., dog! and dog? that glue words to punctuation and waste vocabulary; pre-tokenization is also where the grouping of digits is controlled (see 4.4).

(3) The costs: rare characters get longer, and a single token is not necessarily a whole character.

Because the base unit is the byte, a CJK character that has not been merged into a single token needs 2 to 3 tokens. Whether byte-level BPE is friendly to a given language therefore depends on that language's share of the tokenizer's training corpus: if the share is high enough, common characters and words are merged into single tokens; if it is too low, the text is split into many small pieces, making sequences longer and costs higher. Moreover, a token may contain only part of a character's bytes, which is not valid UTF-8 when decoded on its own. Streaming output therefore has to buffer such bytes until they form a complete character before displaying it, and the occasional invalid byte sequence the model generates has to be replaced by a placeholder at decoding time.

In summary: byte-level BPE uses the byte as a universal base unit, trading a little extra sequence length for complete coverage of any input, which is why it has become the dominant scheme today.

Going deeper: UTF-8 byte lengths, pre-tokenization rules, and byte fallback

(1) Byte lengths of different characters under UTF-8.

Character type Example UTF-8 bytes
ASCII letters, digits and punctuation a, 7, ? 1
Accented Latin letters é 2
Common CJK characters U+4E2D (the character for "middle") 3
Emoji A smiley face 4

(2) Pre-tokenization rules.

GPT-2's pre-tokenization regex splits text into a few kinds of pieces: English contractions (such as 's and 'll), letter runs with an optional leading space, digit runs, punctuation runs, and whitespace. The leading space is attached to the following word, so " dog" and "dog" are two different tokens, the former appearing mid-sentence and the latter at the start of a sentence. The GPT-4 tokenizer (cl100k_base) additionally limits each digit piece to at most 3 digits, a rule Llama 3 kept.

(3) Byte-level BPE versus byte fallback.

Byte-level BPE Character-level BPE + byte fallback
Base units 256 bytes Characters
Unseen characters Encoded as bytes anyway Fall back to byte tokens such as <0xE4>
Can OOV occur? No No
Used by GPT models from GPT-2 on, Llama 3, Qwen, DeepSeek Llama 1, Llama 2 (SentencePiece BPE)

Follow-up questions

Follow-up 1: How does byte-level BPE differ from SentencePiece's byte fallback?

Both eliminate OOV; they differ in where bytes appear. In byte-level BPE, every token is fundamentally a byte sequence and bytes are the base units; in byte fallback, the base units are still characters, and only a character missing from the vocabulary is broken into several byte tokens. LLaMA took the approach of "splitting all numbers into individual digits and falling back to bytes to decompose unknown UTF-8 characters" (Touvron et al. 2023), whereas Llama 3 switched to a tiktoken-based byte-level BPE.

Follow-up 2: Why pre-tokenize, and what are the side effects?

Pre-tokenization keeps merges from crossing category boundaries, which saves vocabulary, but it also prevents tokens from spanning words. Without it, every combination of a word with punctuation or spaces competes for a slot in the vocabulary; with it, a token is at most one whole word. The side effect is that fixed expressions such as "by the way" can never become a single token. SuperBPE (Liu et al. 2025) first learns subwords in the usual way and then drops whitespace pre-tokenization and keeps merging, learning "superword" tokens that span several words; with a 200K vocabulary, it encodes the same text with up to 33% fewer tokens on average, and its 8B model also improves the average across 30 downstream tasks.

Follow-up 3: Why does streaming output sometimes show garbled text or "half a character"?

Because a token may be only part of a character's bytes. For example, if the 3 bytes of a CJK character are split across two tokens, decoding only the first token yields an incomplete UTF-8 sequence. The right approach is to buffer bytes on the decoding side and emit them only once they form a complete character.

Common mistakes

  • Do not say that byte-level BPE has a vocabulary of only 256 tokens: 256 is just the set of base units; on top of them are tens of thousands to over two hundred thousand merged tokens.
  • Do not say that byte-level BPE is inherently unfriendly to Chinese: As long as the tokenizer's training corpus contains enough Chinese, common characters and words are merged into single tokens; the root cause is the corpus mix.
  • Do not say that every token decodes to valid text: A token may be only part of a character's bytes.

4.4 How do you choose the vocabulary size, and what problems does tokenization cause? ★★

One-sentence answer

A larger vocabulary means the same text needs fewer tokens, so the context holds more content, training and inference are more efficient, and multilingual coverage improves; the costs are that the parameters and compute of the embedding and output layer grow linearly with the vocabulary, and rare tokens are harder to train well. Vocabulary size should therefore match the model's scale and language coverage, and the recent trend is toward ever larger vocabularies, from Llama 2's 32K to about 250K for Qwen3.5. Tokenization also causes inconsistent digit splits, difficulty with character-level tasks, unfair token costs across languages, and tokens wasted on whitespace in code.

I will address three aspects: the benefits and costs of vocabulary size, how to choose it and the recent trend, and the typical problems tokenization causes.

(1) Vocabulary size is a trade-off between sequence length on one side and output-layer cost and the training quality of rare tokens on the other.

The larger the vocabulary, the longer the text fragment each token can represent and the fewer tokens the same content needs, which brings a chain of benefits: a context window of the same length holds more content, the same training compute "reads" more text, generating the same content takes fewer decoding steps, and multilingual text gets better coverage. For example, Llama 3 enlarged the vocabulary from Llama 2's 32K to 128K, raising English compression from 3.17 to 3.94 characters per token (Dubey et al. 2024). The costs grow as well, however. The embedding table and the LM head each have \(V \times d\) parameters (\(V\) is the vocabulary size and \(d\) the hidden dimension), and the LM head computes logits and a softmax over the whole vocabulary at every position, so compute and memory grow linearly with \(V\); this is especially visible for small models, where, for example, the embedding of Llama 3.2 1B accounts for about a fifth of all parameters (its input and output share one embedding matrix). Moreover, the larger the vocabulary, the rarer the tokens at its tail, the fewer updates they receive in training and the worse their embeddings are learned, to the point that some "broken tokens" were almost never seen in training, such as the famous SolidGoldMagikarp, which makes the model behave strangely. Land & Bartolo (2024) found that such under-trained tokens are widespread across many open models.

(2) Vocabulary size should grow with model scale, and the recent trend is toward ever larger vocabularies.

Tao et al. (2024) studied scaling laws for vocabulary size systematically and found that the optimal vocabulary size grows with the compute budget, so larger models deserve larger vocabularies; by their estimate, the optimal vocabulary for Llama 2 70B should have been at least 216K, 7 times its actual 32K. Industry practice follows the same trend: about 50K for GPT-2, 32K for Llama 2, about 100K for GPT-4, 128K for Llama 3, about 200K for Llama 4, and about 260K for Gemma 3; Qwen3.5, released in 2026, enlarged its vocabulary from about 150K to about 250K, which the team reports raises encoding and decoding efficiency by 10% to 60% for most languages, while the number of supported languages and dialects grew from 119 to 201 (Qwen Team 2026). Multilingual coverage is clearly one of the main forces behind larger vocabularies. Note that the tokenizer and the model are bound together: the embedding and LM head are learned against one vocabulary's IDs, so the vocabulary is usually fixed before pretraining, and changing it afterwards requires continued training (see Follow-up 1 below).

(3) Tokenization decides what the model actually "sees", and many seemingly strange failures trace back to it.

  • Inconsistent digit splits hurt arithmetic: Early BPE merged digits by frequency, so splits were irregular: 1234 might be one token while 1235 became 12 + 35, and the same digit position lands in different positions within tokens for different numbers, which makes digit-wise operations such as carrying hard to learn. There are two common fixes: splitting every digit into its own token (LLaMA, PaLM, Gemma 3), which makes splits fully consistent at the cost of longer number sequences; or allowing groups of at most three digits (GPT-4, Llama 3), a compromise between length and consistency. Singh & Strouse (2024) found that GPT-3.5 and GPT-4 group digits in threes from left to right by default, and that forcing right-to-left grouping with commas at inference, so that the digits of the addends and the result line up, raises addition accuracy substantially.
  • Character-level tasks are hard: The model sees tokens, not letters; strawberry may be just two or three tokens, so questions such as "how many r's are in this word", spelling and reversing strings are surprisingly hard, because the model has to remember which letters make up each token.
  • Token costs are unfair across languages: Tokenizers are usually trained mainly on English, so text in other languages gets split into more pieces. Petrov et al. (2023) found that the same content translated into different languages can differ in token count by up to 15 times. Users of those languages therefore pay more in API costs, fit less content into the same context window and get slower generation, and in training each token carries less meaning, so quality is often worse.
  • Whitespace in code wastes tokens: Code contains lots of spaces and indentation, and the GPT-2 tokenizer encoded runs of spaces one by one, so Python indentation wasted many tokens. Codex added dedicated tokens for whitespace runs of different lengths, cutting the tokens needed for code by about 30% (Chen et al. 2021), and later tokenizers widely adopted similar handling.

In summary: choosing the vocabulary size is essentially a trade-off between sequence length and output-layer cost, and the vocabulary should grow with model scale and language coverage; meanwhile, the way digits, whitespace and multilingual text are split directly affects how the model performs on arithmetic, spelling, multilingual tasks and code.

Going deeper: the parameter and compute budget of the vocabulary, the vocabularies of various models, and digit-splitting schemes

(1) Parameters and compute due to the vocabulary.

\[ P_{\text{emb}} = V \times d, \qquad \text{FLOPs}_{\text{head}} \approx 2\,V d \ \text{(per token)} \]

Here \(P_{\text{emb}}\) is the parameter count of one embedding matrix and \(\text{FLOPs}_{\text{head}}\) the forward compute of the LM head per token. For Llama 3.2 1B, \(V = 128{,}256\) and \(d = 2048\), so the embedding has about 263M parameters, about 21% of the total (about 1.24B); Llama 3 8B has \(d = 4096\), and its two embedding matrices, input and output, total about 1.05B parameters, about 13%. The same vocabulary thus takes a larger share in a small model. Training also faces a memory problem: the logits tensor for all positions of a micro-batch has size "number of tokens × \(V\)", e.g. about 4 GB for 8K tokens, a 128K vocabulary and fp32 storage, so training with large vocabularies usually relies on chunked or fused cross-entropy kernels that avoid materializing the full logits at once (e.g. Wijmans et al. 2024).

(2) The vocabularies of representative models.

Model Vocabulary size Notes
GPT-2 (Radford et al. 2019) 50,257 Introduced byte-level BPE
Llama 2 (Touvron et al. 2023) 32K SentencePiece BPE, digits split individually, byte fallback
GPT-4 (cl100k_base) About 100K Digits grouped in at most threes
Llama 3 (Dubey et al. 2024) 128K tiktoken's 100K tokens plus 28K added specifically for non-English languages
DeepSeek-V3 (DeepSeek-AI 2024) 128K Byte-level BPE, with pre-tokenization rules and training data tuned for multilingual compression
Qwen3 (Yang et al. 2025) About 150K Byte-level BPE
Llama 4 (Meta 2025) About 200K
Gemma 3 (Gemma Team 2025) About 260K The same SentencePiece tokenizer as Gemini 2.0, digits split individually, more balanced for non-English languages
Qwen3.5 (Qwen Team 2026) About 250K Enlarged from about 150K; supports 201 languages and dialects

(3) Digit-splitting schemes.

Scheme Used by Pros Cons
Free merging by frequency GPT-2 Shortest sequences Inconsistent splits; digit positions cannot align
One token per digit LLaMA, PaLM, Gemma 3 Fully consistent splits Longest number sequences
Groups of at most three, left to right GPT-4, Llama 3 Compromise between length and consistency Digit positions misalign across numbers of different lengths
Groups of at most three, right to left Enforced with commas at inference (Singh & Strouse 2024) Digits align by thousands Requires special handling

Follow-up questions

Follow-up 1: Can you extend the vocabulary of an already-trained model, and how?

Yes, but it must be combined with continued training. You add the new tokens to the vocabulary and add corresponding rows for them in the embedding and the LM head, commonly initialized as the average of the embeddings of the old subwords that make up each new token, and then continue pretraining on the relevant corpus so that the new embeddings realign with the rest of the model. For example, Chinese-LLaMA added about 20K Chinese tokens to LLaMA's vocabulary and then continued pretraining on Chinese text, substantially shortening Chinese sequences (Cui et al. 2023). How to avoid forgetting during continued pretraining is covered in Chapter 4 of the LLM Training Pipeline direction.

Follow-up 2: Why does output get worse when a prompt ends with a space or half a word?

Because the model rarely saw such a cut token boundary during training. For example, if the tokenizer always merges "space + word" into one token, a prompt that ends in a lone space presents the model with an "isolated space token" that almost never occurs in training, and the continuation is prone to errors; this is called the token boundary bias (Lundberg 2023). DeepSeek-V3's tokenizer added merged "punctuation + line break" tokens, which improves compression but also introduces this problem, especially for multi-line few-shot prompts that do not end with a line break; to address it, they randomly split a share of these merged tokens during training so that the model sees more boundary cases (DeepSeek-AI 2024).

Follow-up 3: Does a large vocabulary make training noticeably slower?

Not much for large models, but noticeably for small ones. The LM head costs about \(2Vd\) per token, while the whole model costs about \(2N\) (\(N\) is the parameter count). For an 8B model with a 128K vocabulary, the LM head is about 6% of forward compute; for a 1B model the share is much higher. The other bottleneck is the memory for logits, usually handled by computing the cross-entropy in chunks.

Common mistakes

  • Do not say that a larger vocabulary is always better: In small models the embedding share becomes too high and rare tokens are under-trained; vocabulary size should match model scale.
  • Do not attribute LLMs' weak arithmetic entirely to reasoning ability: The way digits are split has a significant effect on its own (Singh & Strouse 2024).
  • Do not say that switching tokenizers is just a preprocessing change: The embedding and LM head are bound to the vocabulary's IDs, so switching tokenizers requires retraining or extensive continued training.
  • Do not compare token counts or perplexities directly across tokenizers: Normalize by bytes or characters instead.