From Text to Tokens

Dive into Deep Learning · §8.2

From Text to Tokens
characters vs. words · UTF-8 bytes · byte pair encoding (BPE) · merge trees · regex pre-tokenization · special tokens · production tokenizers

Why Tokenization Is an Integral Part of the Model

Motivation & Core Mental Model

  • Embedding & output parameter footprint: Every token in \mathcal{V} claims a row in \mathbf{E} \in \mathbb{R}^{|\mathcal{V}| \times d} and a column in \mathbf{W}_{\textrm{hq}} \in \mathbb{R}^{h \times |\mathcal{V}|} (89\% of our §8.4 RNN parameters).
  • Effective context horizon (T): Splitting The Time Machine into characters produces 173{,}428 time steps, forcing subject–verb agreement to span dozens of recurrent updates.
  • Open-vocabulary robustness: Splitting into 32{,}775 whole words (4{,}579 types) breaks on any unseen word (out-of-vocabulary, OOV) at test time; subword BPE interpolates with zero OOVs.

Ingesting and Normalizing The Time Machine

Corpus Pipeline

Our running corpus is H. G. Wells’ The Time Machine (~30,000 words, 178,979 UTF-8 bytes). Classical character/word pipelines normalize text aggressively, whereas our byte-level BPE tokenizer processes raw_text losslessly:

class TimeMachine(d2l.DataModule):
    """The Time Machine dataset."""
    def _download(self):
        fname = d2l.download(d2l.DATA_URL + 'timemachine.txt', self.root,
                             '090b5e7e70c295757f55df93cb0a180b9691891a')
        with open(fname) as f:
            return f.read()

data = TimeMachine()
raw_text = data._download()
raw_text[:60]
'The Time Machine, by H. G. Wells [1898]\n\n\n\n\nI\n\n\nThe Time Tra'

Ingesting and Normalizing The Time Machine (cont.)

Corpus Pipeline

def _preprocess(self, text):
    return re.sub('[^A-Za-z]+', ' ', text).lower()

text = data._preprocess(raw_text)
text[:60]
'the time machine by h g wells i the time traveller for so it'

Why Aggressive Normalization Is Brittle: Stripping non-ASCII characters and folding case (re.sub('[^A-Za-z]+', ' ', text).lower()) erases punctuation, numbers, code syntax, and proper-noun distinctions (“Bill” vs. “bill”).

The Granularity Trade-Off: Characters vs. Words

Two Ends of the Spectrum

Character-level and word-level tokenization occupy opposite extremes of the trade-off curve between vocabulary size |\mathcal{V}| and corpus sequence length T:

characters:     27 distinct,  173428 tokens in the corpus
words:        4579 distinct,   32775 tokens in the corpus
  • Characters (|\mathcal{V}| = 27, T = 173{,}428): Tiny output layer and no unknown ASCII letters, but 5.3\times longer sequences where individual tokens carry almost no semantic meaning.
  • Words (|\mathcal{V}| = 4{,}579, T = 32{,}775): Compact sequences with semantically rich tokens, but inflections (“traveller”, “travellers”, “travelled”) fragment counts and unseen test words fall out of vocabulary (OOV).

Classical Indexing: Vocab and the <unk> Fallback

Classical Word & Character Vocabularies

vocab = Vocab(tokens)
indices = vocab[tokens[:10]]
print('indices:', indices)
print('tokens:', vocab.to_tokens(indices))
indices: [3, 9, 2, 1, 3, 5, 13, 2, 1, 13]
tokens: ['t', 'h', 'e', ' ', 't', 'i', 'm', 'e', ' ', 'm']
def build(self, raw_text, vocab=None):
    tokens = self._tokenize(self._preprocess(raw_text))
    if vocab is None: vocab = Vocab(tokens)
    corpus = [vocab[token] for token in tokens]
    return corpus, vocab

corpus, vocab = data.build(raw_text)
len(corpus), len(vocab)
(173428, 28)
  • The <unk> collapse: Mapping every rare (< min_freq) or unseen word to index 0 (<unk>) erases morphological stems and incurs an explicit character-spelling penalty during evaluation (§8.3).

UTF-8 Bytes: A Universal 256-Symbol Base Alphabet

Text as Bytes

s = 'Hello, naïve café: 你好 🚀'
print(len(s), 'characters,', len(s.encode('utf-8')), 'bytes')
for ch in 'a é 你 🚀'.split():
    print(repr(ch), '->', list(ch.encode('utf-8')))
n_bytes = len(raw_text.encode('utf-8'))
print(f'The novella: {n_bytes} bytes, {n_bytes / len(words):.1f} per word')
23 characters, 32 bytes
'a' -> [97]
'é' -> [195, 169]
'你' -> [228, 189, 160]
'🚀' -> [240, 159, 154, 128]
The novella: 178979 bytes, 5.5 per word
  • Zero OOV guarantee: Because a byte takes 2^8 = 256 values, any string in any script, code, or emoji decomposes losslessly into IDs 0..255.
  • Variable byte width: UTF-8 spends 1 byte on ASCII, 2 on Latin diacritics/Greek, 3 on CJK, and 4 on emoji (178{,}979 bytes across the novella).

Byte Pair Encoding (BPE): Greedy Pair Merging

The BPE Algorithm

  • Iterative greedy compression (Sennrich et al., 2016): Start from the 256 single-byte tokens (0..255). At each step, tally all adjacent token pairs, merge the most frequent pair into a new token ID (256, 257, ...), and repeat until reaching |\mathcal{V}|.
  • Corpus length reduction: Replacing a pair of count c everywhere shortens the training sequence by c tokens (minus self-overlaps on runs like 'aaa').
  • Token IDs as merge ranks: Because IDs are assigned sequentially (256, 257, ...), a token’s integer ID records the exact rank order in which its merge was learned.

Hierarchical Merge Trees and Byte Fallback

Subword Generalization

Because later merges combine tokens created by earlier merges ('h' + 'ug' \to 'hug'), a trained BPE vocabulary defines a collection of binary merge trees rooted at the 256 raw bytes:

toy_tok = BPETokenizer(vocab_size=256 + 3)
toy_tok.train('hug pug pun bun hugs hug hug pug')
for (a, b), new_id in toy_tok.merges.items():
    print(f'{toy_tok.vocab[a]} + {toy_tok.vocab[b]} -> '
          f'{toy_tok.vocab[new_id]}')
b'u' + b'g' -> b'ug'
b'h' + b'ug' -> b'hug'
b'hug' + b' ' -> b'hug '
  • Morphological composition: On unseen or inflected text, "hugs" replays merge 1 (u+g \to ug) and merge 2 (h+ug \to hug), segmenting cleanly into stem + suffix [b'hug', b's'].
  • Graceful byte fallback: The rare word "bun" shares no learned merges, so it remains three individual byte tokens [b'b', b'u', b'n'] rather than collapsing to <unk>.

Implementing the Left-to-Right Pair Merge Step

From-Scratch Implementation

BPE training and encoding share one primitive, _merge(ids, pair, new_id):

def _merge(self, ids, pair, new_id):
    """Replace every occurrence of pair in ids by new_id."""
    out, i = [], 0
    while i < len(ids):
        if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
            out.append(new_id)  # Merge the pair and skip past it
            i += 2
        else:
            out.append(ids[i])
            i += 1
    return out
  • Left-to-right non-overlapping semantics: Whenever (ids[i], ids[i + 1]) == pair, we append new_id and advance by i += 2; thus on [a, a, a], merging (a, a) yields [aa, a] rather than overlapping pairs.
  • State layout in BPETokenizer: self.vocab maps each ID 0..vocab_size-1 to its raw bytes sequence (vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]), while self.merges maps (id_a, id_b) -> new_id.

Training BPE with Frequency-Weighted Chunks

From-Scratch Implementation

To train vocab_size - 256 merges, we tally unique pre-tokenized chunks once via collections.Counter and weight each adjacent pair inside a chunk by that chunk’s corpus frequency w:

def train(self, text):
    """Learn vocab_size - 256 merges, most frequent pair first."""
    chunk_freq = collections.Counter(self._chunks(text))
    seqs = [list(chunk.encode('utf-8')) for chunk in chunk_freq]
    for new_id in range(256, self.vocab_size):
        pairs = collections.Counter()
        for seq, w in zip(seqs, chunk_freq.values()):
            for pair in zip(seq, seq[1:]):
                pairs[pair] += w  # A chunk that occurs w times counts w times
        if not pairs:
            break  # nothing left to merge
        pair = max(pairs, key=pairs.get)
        self.merges[pair] = new_id
        self.vocab[new_id] = self.vocab[pair[0]] + self.vocab[pair[1]]
        seqs = [self._merge(seq, pair, new_id) for seq in seqs]

Why Deduplicate Chunks? Once regex pre-tokenization splits a corpus into word chunks, a frequent word like " the" appears thousands of times; weighting pair counts by chunk frequency w processes " the" once per iteration instead of thousands of times.

Encoding New Text Strictly by Merge Rank Order

Encoding & Decoding Mechanics

def _encode_chunk(self, text_bytes):
    ids = [self.byte_ids[b] for b in text_bytes]
    while len(ids) > 1:
        # The lowest-rank merge applicable anywhere in this chunk
        pair = min(zip(ids, ids[1:]),
                   key=lambda p: self.merges.get(p, float('inf')))
        if pair not in self.merges:
            break
        ids = self._merge(ids, pair, self.merges[pair])
    return ids

def encode(self, text, allow_special=False):
    if allow_special and self.specials:
        pat = '(' + '|'.join(regex.escape(s) for s in self.specials) + ')'
        ids = []
        for part in regex.split(pat, text):
            if part in self.specials:
                ids.append(self.specials[part])
            elif part:
                ids.extend(self.encode(part))
        return ids
    return [i for chunk in self._chunks(text)
            for i in self._encode_chunk(chunk.encode('utf-8'))]

def decode(self, ids):
    specials = {i: s.encode('utf-8') for s, i in self.specials.items()}
    data = b''.join(self.vocab[i] if i in self.vocab else specials[i]
                    for i in ids)
    return data.decode('utf-8', errors='replace')

Encoding New Text Strictly by Merge Rank Order (cont.)

Encoding & Decoding Mechanics

To encode an arbitrary byte chunk, _encode_chunk repeatedly merges the adjacent pair with the lowest merge rank (smallest new_id) until no adjacent pair appears in self.merges:

[b'hug', b's']
[b'b', b'u', b'n']
'hug pug hugs'
  • The merge table is the tokenizer: Encoding never consults corpus counts—only merge ranks.
  • Why rank order is mandatory: During training, merge r was learned on sequences where all merges < r had already been exhausted; applying the lowest-rank pair first faithfully retraces training.

What Unconstrained BPE Learns on Wells’ Novella

Empirical Behavior on Prose

Training a 1,024-token BPE vocabulary (1024 - 256 = 768 merges) directly on the raw text of The Time Machine reveals a clear progression from frequent bigrams to domain-specific words:

first: [b'e ', b'th', b'd ', b'in', b't ', b's ', b'an', b'er']
last:  [b'appe', b'vo', b'ering ', b'too ', b'door', b'acro', b'clo', b'after ']
13 tokens: [b'The ', b'Time Traveller ', b's', b'mi', b'le', b'd', b'. A',
    b'r', b'e ', b'you ', b'su', b're', b'?']
  • Earliest merges (256..263): Common English letter pairs and trailing-space endings (b'e ', b'th', b't ', b'in', b'd ', b'er').
  • Final merges (1016..1023): Multi-character stems and recurring thematic words (b'imension', b'Time Traveller ', b'little ').
  • Notice the flaw: Token [b'Time Traveller '] fused two separate words and a trailing space into a single vocabulary entry.

Logarithmic Compression Scaling with Vocabulary Size

Compression vs. Vocabulary Capacity

Because BPE assigns IDs sequentially in training order, retaining only merges with ID < |\mathcal{V}| from a 4,096-token run gives the exact tokenizer of size |\mathcal{V}|:

  • Logarithmic gain per doubling: Plotting UTF-8 bytes per token against \log |\mathcal{V}| from 256 \to 4{,}096 yields an almost straight line: each doubling of |\mathcal{V}| adds roughly 0.5 bytes/token.
  • Diminishing marginal counts: Merge 256 collapses thousands of occurrences of b'e ', whereas merge 4,095 collapses only a handful of occurrences.
  • In-domain overfitting caveat: Evaluating on training text flatters large |\mathcal{V}| because 4,096 merges memorize novella-specific phrases.

Why Unconstrained BPE Leaks Across Word Boundaries

The Pre-Tokenization Motivation

Without boundary constraints, 78 of the 768 learned merges in our 1,024-token vocabulary straddle an internal space across multiple words:

78 tokens cross a word boundary, e.g. [', and ', 'of the ', '. I ', '. Th',
    '. A', '. I', 'in the ', 'ed to ']
  • Why multi-word tokens hurt generalization: Slots spent on 'of the ', 'in the ', and 'to the ' cannot represent content words, and the word "of" is fragmented across dozens of incompatible token IDs depending on what follows it.

Why Unconstrained BPE Leaks Across Word Boundaries (cont.)

The Pre-Tokenization Motivation

regex.findall(BPETokenizer.GPT2_PATTERN,
              "The traveller's clock struck 12,345 times.")
['The',
 ' traveller',
 "'s",
 ' clock',
 ' struck',
 ' 12',
 ',',
 '345',
 ' times',
 '.']
  • GPT-2’s 5-branch regex (GPT2_PATTERN): Splits contractions ('s, 've, 'll), attaches each leading space to its following letter run (?\p{L}+) or digit run (?\p{N}+), isolates punctuation (?[^\s\p{L}\p{N}]+), and confines BPE merges strictly within each chunk.

Regex Pre-Tokenization Pipeline in Production BPE

Pre-Tokenized BPE Results

Passing pattern=BPETokenizer.GPT2_PATTERN eliminates every boundary-crossing composite and reallocates those vocabulary slots to complete words with leading spaces:

boundary-crossing tokens now: 0
longest tokens gained instead: [' Psychologist', 'sychologist', '
    Traveller', ' Morlocks', ' darkness', ' Machine']
first merges: [b' t', b'he', b' a', b'in', b' the', b' s']
  • Zero boundary crossers: len(crossers) drops from 78 \to 0, replaced by clean whole-word tokens like ' Traveller', ' Machine', and ' dimension'.
  • Leading-space convention: Earliest merges become b' t', b' a', b'he', b'in'—attaching the preceding space to the start of a word so decoding never needs heuristic space insertion.

Special Control Tokens and Prompt-Injection Safety

Infrastructure & Security Invariants

print('as plain text:  ', bpe.encode('<bos>the time machine'))
print('as control code:', bpe.encode('<bos>the time machine',
                                     allow_special=True))
print('pad/bos/eos ids:', bpe.pad, bpe.bos, bpe.eos, '| len:', len(bpe))
as plain text:   [60, 98, 111, 115, 62, 341, 513, 680]
as control code: [1025, 341, 513, 680]
pad/bos/eos ids: 1024 1025 1026 | len: 1027
  • ID isolation above BPE merges: Special tokens (<pad>, <bos>, <eos>) sit at IDs 1024..1026, so ordinary byte merges can never synthesize a control ID.
  • Explicit allow_special guard: By default (allow_special=False), "<bos>" encodes as 5 literal ASCII bytes [60, 98, 111, 115, 62], blocking prompt injection of control tokens.

Inside GPT-2’s Production Rank Table (tiktoken)

Production Verification

Production byte-level BPE tokenizers (GPT-2/3/4, Llama 3) store no neural weights—only a byte-string \to rank dictionary, the pre-tokenization regex, and the special-token map:

[(b'\xa0', 254), (b'\xad', 255), (b' t', 256), (b' a', 257), (b'he', 258), (b'in', 259)]
{'<|endoftext|>': 50256}
60 tokens, identical to tiktoken
['The', ' Time', ' Trave', 'ller', ' (', 'for', ' so', ' it']
  • Universal English statistics: GPT-2’s first four merges trained on 40 GB of WebText (b' t', b' a', b'he', b'in' at ranks 256..259) are identical to the first four merges our tokenizer learned on a single 1895 novella.
  • Exact parity: Loading GPT-2’s 50,257 ranks into BPETokenizer.from_tiktoken('gpt2') matches tiktoken token-for-token across prose, decimals, diacritics, currency symbols, and emoji.

In-Domain vs. General Production Compression Ratios

Cross-Tokenizer & Cross-Lingual Fertility

Comparing our 1,024-token novella tokenizer against OpenAI’s 50k gpt2 and 200k o200k_base (GPT-4o) vocabularies highlights domain compression and cross-lingual fertility (tokens per word):

  ours (1k, in-domain):  65741 tokens, 2.72 bytes/token
            gpt2 (50k):  44073 tokens, 4.06 bytes/token
     o200k_base (199k):  42624 tokens, 4.20 bytes/token
 English: 1.14 (gpt2), 1.14 (o200k_base) tokens per word
  German: 2.86 (gpt2), 1.57 (o200k_base) tokens per word
   Greek: 7.33 (gpt2), 1.89 (o200k_base) tokens per word
  • Domain adaptation: Our 1k in-domain BPE reaches 2.72 bytes/token—roughly two-thirds of the compression of vocabularies 50\times and 200\times larger (4.06 and 4.20 bytes/token).
  • The multilingual fertility tax: Under English-centric gpt2, Greek requires 7.33 tokens/word vs. 1.14 for English (6.4\times less text fits in a fixed context window and 6.4\times higher inference cost); multilingual o200k_base cuts Greek fertility to 1.89.

Pitfalls: Place-Value Misalignment & Glitch Tokens

Practical Systems Pitfalls

Subword tokenization choices directly explain two famous behavioral quirks of modern large language models:

for name in ('gpt2', 'o200k_base'):
    e = tiktoken.get_encoding(name)
    print(f'{name}: 12345678 ->',
          [e.decode([t]) for t in e.encode('12345678')])
gpt2: 12345678 -> ['123', '45', '678']
o200k_base: 12345678 -> ['123', '456', '78']
enc.encode(' SolidGoldMagikarp')  # one token for an 18-character string
[43453]
  • Arithmetic & left-to-right digit chunking: o200k_base caps digit runs at 3 characters from left to right, splitting "12345678" into ['123', '456', '78']—misaligned with right-to-left positional place values (12,345,678), forcing carry operations to shift across inconsistent token boundaries.
  • Glitch tokens (' SolidGoldMagikarp'): When a string (such as a high-volume Reddit username) is frequent in the tokenizer’s training scrape but filtered out of the language model’s pretraining corpus, it claims a single token ID (43453) whose embedding row \mathbf{E}_{43453} remains randomly initialized at test time.

Concept Check: BPE Rank Order, Regex & Fertility

Check Your Understanding

Test your understanding of BPE encoding mechanics and production pre-tokenization:

  1. Rank Order vs. Leftmost Pair: Suppose a BPE tokenizer learned two merges in order: ('b', 'c') -> 256 (rank 256) and then ('a', 'b') -> 257 (rank 257). How does the string "abc" segment under (a) the correct lowest-rank rule vs. (b) a naive leftmost-applicable-pair rule? Which matches the end of training?
  2. GPT-2 Pre-Tokenization Trace: Into what exact chunks does BPETokenizer.GPT2_PATTERN split the sentence "I've got 1234 cats!" before BPE merges run?
  3. Context Window Capacity: If an LLM has a 1,024-token context window and uses the gpt2 tokenizer (English fertility 1.14 tokens/word, Greek fertility 7.33 tokens/word), roughly how many English words vs. Greek words fit inside one context window?

Answers:

  1. (a) Lowest-rank rule: Merges ('b', 'c') (rank 256 < 257) first to produce ['a', 'bc'] ([97, 256]), matching training (where every 'bc' was already merged before ('a', 'b') was ever counted). (b) Leftmost rule: Wrongly merges ('a', 'b') first into ['ab', 'c'].
  2. Six chunks: ['I', "'ve", ' got', ' 1234', ' cats', '!'] (contraction split off, leading space attached to each word and digit run, trailing punctuation isolated).
  3. ~898 English words vs. ~140 Greek words: 1024 / 1.14 \approx 898 words in English, compared to 1024 / 7.33 \approx 140 words in Greek—a 6.4\times reduction in effective context length.

Summary: Tokenization Schemes Compared

Section Takeaways

Tokenization Scheme Base Alphabet Vocab Size |\mathcal{V}| (Time Machine) Sequence Length T Out-of-Vocabulary (OOV) Behavior Primary Architectural Trade-Off
Character-Level Normalized ASCII / Unicode chars 27 (normalized) to \sim 150\textrm{k} (Unicode) 173{,}428 None on ASCII; breaks on unseen Unicode scripts Tiny softmax layer, but sequences are 5\times longer and semantically weak
Word-Level Whitespace-split word types 4{,}579 + \texttt{<unk>} (unbounded with corpus) 32{,}775 Unseen words collapse into <unk> Short sequences, but massive softmax layer and severe OOV/inflection sparsity
Raw UTF-8 Bytes Single bytes 0..255 256 (fixed universal) 178{,}979 Zero OOV on any string in any language Universal coverage, but 5.5\times longer sequences (2\text{--}4\times extra for non-ASCII)

Summary: Tokenization Schemes Compared (cont.)

Section Takeaways

Tokenization Scheme Base Alphabet Vocab Size |\mathcal{V}| (Time Machine) Sequence Length T Out-of-Vocabulary (OOV) Behavior Primary Architectural Trade-Off
Unconstrained BPE UTF-8 bytes + greedy pair merges Chosen hyperparameter (e.g., 1{,}024) \sim 61{,}000 Zero OOV (unseen stems fall back to bytes) Over-merges across spaces ('of the '), fragmenting single-word statistics
Pre-Tokenized BPE (GPT-2 / Llama 3) Regex chunks + byte-level BPE + high-ID specials 1{,}024 + 3 (ours) or 50\textrm{k}\text{--}200\textrm{k} (prod) 65{,}741 (2.72 B/tok) Zero OOV + prompt-injection-safe specials Industry standard balancing sequence compression, softmax cost, and open vocabulary