Skip to content
ImagineWorld

Tokenization

node_idnode-book_building-frontier-llm-from-scratch_chapter-05-tokenization
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleTokenization
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Part II — Data and Tokenization

Tokenization is where text becomes numbers, and it is the most quietly consequential design choice in the whole pipeline. The tokenizer fixes the model’s vocabulary, its effective sequence length, how it handles code and other languages, and even a surprising share of its arithmetic and spelling failures. Get it wrong and nothing downstream can fully recover. This chapter builds a real byte-pair-encoding tokenizer from scratch — train, encode, decode — then surveys how the major model families differ, with numbers.

There are three obvious ways to turn text into tokens, and all three are bad. Characters give a tiny vocabulary but enormous sequences, so the model wastes its limited context and compute on trivially predictable letters. Words give short sequences but a gigantic, open-ended vocabulary that can never cover new words, names, or typos. Raw bytes generalize perfectly but, like characters, produce very long sequences. The winning compromise is subwords: frequent words become single tokens, rare words split into reusable pieces, and nothing is ever truly out-of-vocabulary because the pieces bottom out at bytes. Table 5.1 summarizes the trade-off the vocabulary size V controls.

GranularityVocabularySequence lengthOut-of-vocab?
Characterstiny (~100)very longnever
Wordshuge, open-endedshortconstantly
Bytes256longestnever
Subwords (BPE)tunable (32K–256K)moderatenever (falls back to bytes)

Table 5.1 — The tokenization trade-off, governed by vocabulary size

A larger vocabulary shortens sequences (cheaper attention, more text per context) but enlarges the embedding and output-projection matrices and spreads training signal over more, rarer tokens. Modern models sit anywhere from 32,000 to 256,000 tokens; Section 5.4 shows who chose what.

Byte-pair encoding (BPE) starts from the 256 possible bytes and repeatedly merges the most frequent adjacent pair into a new token, growing the vocabulary one merge at a time. Training records the ordered list of merges; encoding replays them; decoding inverts them. The entire algorithm is three short functions and a class. First, the two helpers — count adjacent pairs, and apply a single merge:

def get_stats(ids):
"""Count how often each adjacent pair occurs."""
counts = {}
for pair in zip(ids, ids[1:]): # consecutive pairs
counts[pair] = counts.get(pair, 0) + 1
return counts
def merge(ids, pair, idx):
"""Replace every occurrence of `pair` with the new token `idx`."""
out, i = [], 0
while i < len(ids):
if i < len(ids) - 1 and ids[i] == pair[0] and ids[i+1] == pair[1]:
out.append(idx); i += 2 # consume the pair
else:
out.append(ids[i]); i += 1
return out

Python — bpe.py: counting pairs and applying a merge

The tokenizer itself wraps these in train, encode, and decode. Note how training simply loops “find the top pair, mint a new id, merge,” and how encoding greedily applies the learned merges in the order they were created:

class BPETokenizer:
def train(self, text, vocab_size):
assert vocab_size >= 256
ids = list(text.encode("utf-8")) # start from raw bytes 0..255
self.merges = {} # (int, int) to new id
self.vocab = {i: bytes([i]) for i in range(256)}
for k in range(vocab_size - 256):
stats = get_stats(ids)
if not stats: break
pair = max(stats, key=stats.get) # most frequent adjacent pair
idx = 256 + k
ids = merge(ids, pair, idx)
self.merges[pair] = idx
self.vocab[idx] = self.vocab[pair[0]] + self.vocab[pair[1]]
def encode(self, text):
ids = list(text.encode("utf-8"))
while len(ids) >= 2:
stats = get_stats(ids)
# merge the pair whose merge was learned earliest
pair = min(stats, key=lambda p: self.merges.get(p, float("inf")))
if pair not in self.merges: break
ids = merge(ids, pair, self.merges[pair])
return ids
def decode(self, ids):
raw = b"".join(self.vocab[i] for i in ids)
return raw.decode("utf-8", errors="replace")

Python — bpe.py: a complete byte-level BPE tokenizer

That is a genuinely working tokenizer. Train it on a corpus, and common sequences like " the" or "tion" become single tokens; encode any string and it round-trips through decode exactly, because the vocabulary bottoms out at bytes and nothing is ever unrepresentable. Table 5.2 traces the first few merges on a tiny toy input to make the loop concrete.

MergeMost frequent pairNew tokenBecomes
1('t','h')th“th e th eme th en th ere”
2('th','e')the“the the me the n the re”
3('the',' ')the_“the_ the_me the_n the_re”

Table 5.2 — BPE merges on the toy corpus “the theme then there” (illustrative)

Each step replaces the single most frequent adjacent pair everywhere, so high-frequency strings collapse into one token first. Real training runs tens of thousands of these merges over billions of bytes.

Two refinements separate the toy above from production tokenizers like GPT’s. First, operating on bytes rather than Unicode code points keeps the base alphabet at exactly 256 symbols while still representing every possible character, emoji, and control sequence — the “byte-level” in byte-level BPE. Second, a pre-tokenizer uses a regular expression to split text into chunks (words, numbers, punctuation runs) before BPE, and merges are never allowed to cross chunk boundaries. This stops the tokenizer from gluing a word to its trailing space-and-next-word, and it is why GPT-style tokenizers handle digits and contractions sensibly. Rather than point at it, here is that production version, reproduced from minbpe’s regex.py. Two pieces matter: the GPT-4

split pattern — the exact regular expression GPT-4 uses to chop text into chunks — and a RegexTokenizer whose encode applies BPE to each chunk independently, so a merge can never reach across a chunk boundary:

import regex as re
# the exact GPT-4 pre-tokenizer split pattern
GPT4_SPLIT = (
r"""'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}+|"""
r"""\p{N}{1,3}| ?[^\s\p{L}\p{N}]++[\r\n]*|\s*[\r\n]|\s+(?!\S)|\s+"""
)
class RegexTokenizer:
def __init__(self, pattern=GPT4_SPLIT):
self.compiled = re.compile(pattern)
self.merges = {} # learned during train()
def _encode_chunk(self, text_bytes):
ids = list(text_bytes)
while len(ids) >= 2:
stats = get_stats(ids)
pair = min(stats, key=lambda p: self.merges.get(p, float("inf")))
if pair not in self.merges:
break
ids = merge(ids, pair, self.merges[pair])
return ids
def encode(self, text):
ids = []
for chunk in re.findall(self.compiled, text): # split FIRST
ids.extend(self._encode_chunk(chunk.encode("utf-8")))
return ids

Python — karpathy/minbpe · regex.py (reproduced, MIT licence)

The split-before-merge order is the whole trick. Because re.findall first breaks the text into chunks — a run of letters, a run of one to three digits, a run of punctuation, a space-led word — and BPE then runs within each chunk, the tokenizer can never learn a token that glues a word to the space and word after it, and it always treats numbers in small, regular groups. Reading the pattern slowly repays the effort: '(?i:[sdmt]|ll|ve|re) keeps English contractions like 's and 'll together; \p{L}+ matches runs of letters in any script; \p{N}{1,3} caps digit groups at three so numbers tokenize consistently; and the trailing clauses handle whitespace and newlines. This single regular expression is responsible for a large share of how sensibly a GPT-style model handles code, numbers, and non-English text. The tiktoken library implements the same encoding in Rust for production speed and ships OpenAI’s cl100k and o200k vocabularies ready to use.

5.3 SentencePiece and the Unigram Alternative

Section titled “5.3 SentencePiece and the Unigram Alternative”

BPE is not the only game. The Unigram language-model tokenizer, implemented in Google’s SentencePiece, works the other way around: it starts from a large candidate vocabulary and iteratively removes the tokens that contribute least to the likelihood of the corpus, keeping a probabilistic model that can score multiple segmentations of the same string. SentencePiece also treats the input as a raw stream (spaces become a visible ▁ marker), so it needs no language-specific pre-tokenization — convenient for multilingual training. In practice BPE and Unigram perform comparably; the Llama and Gemma families historically used SentencePiece, while the GPT, Qwen, and DeepSeek lines use byte-level BPE. The mental model — frequent strings become tokens, rare strings fragment — is the same either way.

5.4 Building Your Own Tokenizer, and How the Big Models Differ

Section titled “5.4 Building Your Own Tokenizer, and How the Big Models Differ”

A deployable tokenizer needs more than merges. It needs special tokens — sentinels like beginning-of-sequence, end-of-sequence, padding, and the role markers that delimit a chat (system, user, assistant) — assigned reserved ids outside the learned range. It needs a chat template: the exact string format, including those markers, that turns a structured conversation into the single token stream the model was trained on. Getting the template byte-for-byte right at inference is a frequent, silent source of quality loss, because the model is acutely sensitive to formats it saw during alignment (Part VI).

The families we track make markedly different vocabulary choices, and the numbers (Table 5.3) have real consequences: a larger vocabulary fits more text per context and helps non-English and code, at the cost of bigger embedding and output matrices.

FamilyMethodVocab sizeNotes
GPT-2byte-level BPE~50,257the original byte-level BPE
GPT-3.5 / GPT-4 (cl100k)byte-level BPE~100,277via tiktoken
GPT-4o / 4.1 (o200k)byte-level BPE~200,019better multilingual & code
FamilyMethodVocab sizeNotes
Llama 1 / 2SentencePiece BPE32,000small, English-leaning
Llama 3 / 4byte-level BPE128,256tiktoken-style, much larger
DeepSeek-V3byte-level BPE~129,000code- and Chinese-aware
Qwen2 / Qwen3byte-level BPE~151,900strong multilingual coverage
Gemma 2 / 3SentencePiece256,000very large, broad multilingual

Table 5.3 — Tokenizer choices across model families (approximate vocabulary sizes)

Sizes are approximate and include reserved special tokens, which differ by version; treat them as orders of magnitude. The trend mirrors the architectures: vocabularies have grown roughly fivefold since GPT-2 as labs invest in multilingual and code performance.

Training a real, fast tokenizer in this exact format takes only a few lines with Hugging Face’s tokenizers library — the same serialized tokenizer.json format that frontier models ship. Reproduced here is the complete recipe for a byte-level BPE tokenizer of your own:

from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
trainer = trainers.BpeTrainer(
vocab_size=32000,
special_tokens=["<|endoftext|>", "<|user|>", "<|assistant|>"],
)
tok.train(["corpus.txt"], trainer)
tok.save("tokenizer.json") # same format frontier models ship

Python — huggingface/tokenizers: train a byte-level BPE (reproduced, Apache 2.0)

That file — the merges, the vocabulary, the special tokens — is exactly what you would find inside a released model’s tokenizer directory. To inspect a frontier one, open DeepSeek-V3’s tokenizer.json alongside its tokenizer_config.json (which holds the special tokens and the chat template); having written the training code above, those files read as the output of a process you now understand end to end. The special tokens you reserve here — the role markers in particular — are the seam between the tokenizer and the chat format the model is aligned to in Part VI, which is why they are declared at training time and never changed afterward.

Key point The tokenizer is a model decision, not a preprocessing afterthought. It sets the vocabulary, the sequence length, the multilingual and code competence, and the chat format the model is forever sensitive to. When you build the capstone in Chapter 30, you will train the tokenizer first and freeze it — everything else depends on it.

With text reduced to tokens, the model still needs something to read. The next chapter builds the other half of the input pipeline: how to source, clean, deduplicate, and pack the trillions of tokens a modern model is pretrained on.

The dominant tokenizer for modern language models is byte-pair encoding (BPE), and its training algorithm is simple enough to state in full. Starting from individual bytes or characters, it repeatedly finds the most frequent adjacent pair across the corpus and merges it into a single new symbol, growing a vocabulary of subwords one merge at a time:

def learn_merges(corpus, num_merges):
vocab = [list(word) for word in corpus]
merges = []
for _ in range(num_merges):
pairs = count_adjacent_pairs(vocab) # (a, b) -> frequency
best = max(pairs, key=pairs.get) # most frequent pair
vocab = apply_merge(vocab, best) # replace a b with ab
merges.append(best)
return merges

Python — tok/bpe.py: learning merges (illustrative)

The result is a vocabulary that spends its budget where it pays. Common words become single tokens because their characters merge early and often; rare words fragment into a few subword pieces; and a word never seen before still tokenizes, because in the worst case it falls back to bytes. This is the balance BPE strikes between two bad extremes — a character vocabulary that makes sequences punishingly long, and a word vocabulary that cannot represent anything outside it. The size of the learned vocabulary is itself a design lever with downstream cost: every token in it adds a row to the embedding table and the output head (Section 16.5), so a larger vocabulary shortens sequences at the price of more parameters, a trade every model makes deliberately.

Frequent merges, graceful fallback BPE merges the most common pairs first, so frequent words become single tokens and rare ones fragment predictably — with bytes as the floor, nothing is ever out-of-vocabulary. Vocabulary size then trades sequence length against embedding parameters.

Tokenization sits beneath everything the model does, and its quirks are the source of a surprising number of model failures — failures that look like reasoning errors but are really artifacts of how text was chopped into tokens. They are worth knowing precisely because they are invisible until they bite.

Numbers are the classic case. Depending on the vocabulary, “123” might be a single token while “1234” splits into “123” and “4” or some other irregular pieces, so the model sees no consistent representation of magnitude — which is part of why arithmetic is harder for language models than their other abilities would suggest. Whitespace and code are similarly sensitive: a leading space can change a token entirely, and indentation-significant code is fragile under a tokenizer not designed for it. Multilingual text pays an uneven tax: a tokenizer trained mostly on English fragments other scripts into far more tokens per word, so the same sentence in a non-Latin language can cost several times the context and compute (Section 16.5). There are even pathological “glitch tokens” — rare strings that appeared oddly in the tokenizer’s training but barely in the model’s — that trigger bizarre behavior. The practical lesson is that when a model fails in a strange, brittle way on numbers, formatting, or a particular language, the tokenizer is a prime suspect, and inspecting how the input was actually tokenized is the first diagnostic step.

Many “model” bugs are tokenizer bugs Inconsistent number splitting, whitespace sensitivity, a heavy token tax on non-English scripts, and rare glitch tokens all produce failures that look like reasoning errors. When behavior is strangely brittle, check the tokenization first.

5.7 Byte-Level, Character, and Word Tokenization

Section titled “5.7 Byte-Level, Character, and Word Tokenization”

Subword tokenization (Section 5.3) is a compromise, and its merits are clearest against the extremes it sits between. Tokenization can be done at any granularity, and the choice trades two quantities against each other: vocabulary size and sequence length.

At one extreme is character (or byte) level: every character is a token. The vocabulary is tiny and there is no out-of-vocabulary problem — any string can be represented — but sequences become very long, since a single word is many tokens, and the model must assemble all meaning from the smallest possible pieces, spending capacity and context length to do so. At the other extreme is word level: each word is a token. Sequences are short, but the vocabulary balloons to hundreds of thousands of entries, and any rare or newly coined word that was not in the vocabulary cannot be represented at all — the out-of-vocabulary problem. Subword tokenization (Section 5.4) threads between them: common words become single tokens while rare ones split into sub-word pieces, so the vocabulary stays manageable, sequences stay reasonably short, and nothing is out-of-vocabulary because any word can be built from its parts. Byte-level subword schemes push this further, operating on raw bytes so that even unusual characters and scripts are representable, eliminating the out-of-vocabulary problem entirely. This is why nearly every modern model uses subword tokenization: it occupies the practical sweet spot of the granularity spectrum, capturing the best of both extremes while avoiding the worst of each.

Subword is the sweet spot of the granularity spectrum Character level means a tiny vocabulary but very long sequences; word level means short sequences but a huge vocabulary and out-of-vocabulary failures. Subword tokenization sits between — manageable vocabulary, short sequences, nothing unrepresentable — which is why it is universal.