DL0080 Tokenization in LLMs

Explain tokenization in large language models.

Answer

Tokenization is the reversible mapping between raw text and the sequence of integer ids a language model actually consumes, drawn from a fixed vocabulary of size V. Modern LLMs use subword vocabularies that sit between characters (short vocab, very long sequences) and words (huge vocab, unavoidable out-of-vocabulary gaps), and the dominant recipe is byte-level BPE: count adjacent symbol pairs over a training corpus, greedily merge the most frequent pair, and repeat until the vocabulary reaches its target size. Because the base alphabet is the 256 possible bytes rather than Unicode characters, any input is representable and there is no UNK token, at the cost of spending several tokens per character on scripts the merge table never learned. The tokenizer is frozen before pretraining and is effectively part of the architecture: it fixes the embedding matrix and output projection (2Vd parameters), it decides how many model passes a sentence costs, and it determines whether the model sees 1024 as one symbol or three. Most surprising LLM behaviors around arithmetic, non-English cost, and trailing whitespace trace back to this layer rather than to the transformer itself.

(1) Subword Is A Middle Ground: character-level models keep the vocabulary tiny but inflate sequence length, and attention is O(N^2) in that length; word-level vocabularies need hundreds of thousands of entries and still miss rare words and typos.
(2) How BPE Is Trained And Applied: training produces an ordered merge list; encoding replays those merges greedily on each pretokenized chunk, so segmentation is deterministic and not a search over the best split.
(3) Pretokenization Comes First: in the GPT-style recipe a regex splits text on whitespace, punctuation, and digit groups before BPE runs, which is why the leading space belongs to the token (" the" and "the" are different ids) and why, with standard pretokenization, merges do not cross word boundaries; that constraint comes from the pretokenizer rather than from BPE itself, and implementations that skip or relax it (see SuperBPE below) do learn multi-word tokens.
(4) Vocabulary Size Is A Compute Knob: raising V lowers fertility (tokens per word) so each sentence needs fewer forward passes, but it grows the embedding and softmax cost, which is why the field drifted from 32k to 128k vocabularies (Llama 2 → Llama 3) as models got larger.
(5) The Failure Modes Users Notice: digit grouping degrading arithmetic, non-English prompts costing two to three times more tokens for the same content, glitch tokens whose embeddings were barely trained, and special chat-template ids that must never be injectable from user text.

Bar chart of tokens per whitespace word for eight languages under one English-heavy tokenizer: English 1.15, French 1.40, Spanish 1.45, German 1.55, Russian 1.90, Turkish 2.15, Swahili 2.35, Hindi 2.70

Figure 1: Illustrative fertility gap: with a merge table dominated by English text, the same content in Hindi consumes roughly 2.3\times more tokens, so it costs more per request and reaches the context limit sooner.

Two implementation details matter more in production than the choice of merge algorithm. First, digit handling: tokenizers that merge arbitrary digit runs give the model inconsistent units for numbers, so 2024, 202, and 24 share no stable structure and column-wise arithmetic has to be learned per token; Llama 3 and several recent tokenizers instead force digits into groups of at most three, and some research tokenizers split every digit. Second, special tokens such as beginning-of-text and end-of-turn markers are inserted out of band by the chat template, not produced by BPE over user text; if a serving layer lets a user string encode into those ids, the model’s turn structure can be rewritten from inside a prompt. Related traps include unnormalized Unicode (NFC versus NFKC changes ids for accented text), tokenizer and checkpoint version skew, which silently shifts every embedding lookup, and untrained vocabulary rows that surface as glitch tokens the model cannot repeat back.

Mathematical Formulation:
(a,b)^{*} = \arg\max_{(a,b)} c(a,b)
F = \frac{T}{W}
P_{\text{emb}} = 2 V d
C_{\text{word}} = F \cdot (C_{\text{body}} + 2 V d)

Where:

  • (a,b)^{*} is the pair chosen at each BPE training step, and c(a,b) is its frequency as adjacent symbols in the corpus; the merge is appended to an ordered list that encoding later replays.
  • F is fertility: T tokens produced for W whitespace words, measured per language and per corpus, so it is a property of the tokenizer and the text, not of the model.
  • P_{\text{emb}} counts the input embedding plus the untied output projection for vocabulary V and hidden width d; tying the two halves this term but couples input and output geometry.
  • C_{\text{word}} is the compute per word of text, where C_{\text{body}} is the per-token cost of everything except the vocabulary layers; the two V-dependent effects pull in opposite directions, which is why an interior optimum in V exists and grows with model size.
Two panels versus vocabulary size on a log axis: left panel shows tokens per word falling from about 1.72 at 4k vocab to 1.27 at 512k with diminishing returns, right panel shows relative compute per word dipping to a minimum near 33k vocabulary and rising to about 1.65 at 512k

Figure 2: Illustrative trade-off for a 1B-scale model with d = 1024: shorter sequences from a larger vocabulary stop paying for themselves once the 2Vd output-layer cost rivals the transformer body, and the minimum shifts right as d and depth grow.

FeatureByte-level BPEWordPieceUnigram LM
How the vocab is learnedGreedily merge the most frequent adjacent pair, recording an ordered merge listMerge the pair that most increases corpus likelihood under a unigram modelStart from a large candidate set and prune the tokens whose removal costs the least likelihood (EM)
How text is segmentedReplay merges in training order; deterministic and fastLongest-match-first greedy scan, with ## marking continuationsViterbi search for the most probable segmentation, and it can sample splits for subword regularization
Unseen inputNo UNK is possible; the 256-byte alphabet covers all of UnicodeEmits UNK for characters outside the alphabet unless byte fallback is addedByte fallback is optional in SentencePiece and usually enabled
Where you see itGPT-2 onward, Llama, Mistral, QwenBERT and the encoder family that followed itT5, ALBERT, and many multilingual encoders

Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *