8.2  From Text to Tokens

Most sequences we model in this chapter are text, which introduces a challenge that the synthetic numerical series of Section 8.1 did not: neural networks operate on vectors of numbers, whereas text arrives as a raw string of characters. Before we can train any language model, we must decide how to segment a string into tokens (the atomic units treated as observations \(x_t\)) and how to map each token to a numerical index. This seemingly mundane preprocessing choice has far-reaching consequences: it determines the size of the model’s embedding and output layers, the sequence length of every document the model reads, and even how hard tasks such as arithmetic turn out to be. Splitting The Time Machine into individual characters forces a model to step through roughly 170,000 time steps; splitting it into whole words requires an output class for each of about 4,600 distinct words while still breaking on any word not seen during training. For this reason, every modern language model ships with a dedicated tokenizer, and it is best to think of the tokenizer as an integral part of the model itself.

We begin by comparing character-level and word-level tokenization, which lie at opposite ends of the trade-off between vocabulary size and sequence length. We then drop down to raw bytes as a universal base alphabet and learn a subword vocabulary directly from data using byte pair encoding (BPE), the scheme underlying the GPT family of models (Sennrich et al. 2016; Radford et al. 2019). Our from-scratch implementation is only a few dozen lines of Python, yet it reproduces GPT-2’s production tokenizer token for token.

8.2.1 Reading the Dataset

Throughout this chapter, our running corpus is H. G. Wells’ The Time Machine, a novella of just over 30,000 words. Although real-world pretraining corpora run to trillions of tokens, this dataset is rich enough to exhibit the statistical properties of natural language while remaining small enough to tokenize in seconds. The _download method below fetches the book and reads the raw text into a single string.

import collections
import re
import tiktoken
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'

Classical NLP pipelines normalized raw text aggressively—stripping out punctuation, folding all letters to lowercase, and only then splitting the cleaned string into tokens. We keep a simple normalization step here for the character- and word-level comparisons below, as well as for later sections that still use those pipelines. Still, such preprocessing is undeniably crude: it discards informative signals (capitalization distinguishes “Bill” from “bill”) and bakes in brittle assumptions about which characters matter. By contrast, the byte-level tokenizer we construct later in this section requires no normalization whatsoever.

@d2l.add_to_class(TimeMachine)
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'

8.2.2 Characters, Words, and Bytes

8.2.2.1 Characters and Words

Because a sequence model processes one token per time step, the two most natural choices of token are individual characters and whole words. Let us examine both, starting with characters.

@d2l.add_to_class(TimeMachine)
def _tokenize(self, text):
    return list(text)

tokens = data._tokenize(text)
','.join(tokens[:30])
't,h,e, ,t,i,m,e, ,m,a,c,h,i,n,e, ,b,y, ,h, ,g, ,w,e,l,l,s, '

Splitting on whitespace produces word tokens instead. For each scheme, we count both the number of distinct token types (which sets the vocabulary size) and the total number of tokens in the corpus (which sets the sequence length).

words = text.split()
print(f'characters: {len(set(tokens)):>6} distinct, '
      f'{len(tokens):>7} tokens in the corpus')
print(f'words:      {len(set(words)):>6} distinct, '
      f'{len(words):>7} tokens in the corpus')
characters:     27 distinct,  173428 tokens in the corpus
words:        4579 distinct,   32775 tokens in the corpus

Character-level tokenization of our normalized text requires only 27 symbols and can never encounter an unknown letter, yet it stretches the novella across more than 170,000 time steps, forcing any long-range dependency, such as agreement between a subject and its verb, to span dozens of steps. Word-level tokenization compresses the same text into roughly one-fifth as many tokens, each carrying far more semantic content. Even on this short novella, however, splitting into words already yields thousands of distinct types, and the vocabulary grows continually with the corpus: every proper name, typographical error, and inflection (“traveller”, “travellers”, “travelled”) claims its own entry, most of which appear only once or twice (Section 8.3). Worse still, any word absent from the training set is out of vocabulary (OOV) at test time. Figure 8.2.1 illustrates this fundamental trade-off: enlarging the vocabulary shortens the resulting sequences, and the central design question is where along this spectrum to operate. Subword tokenizers allow us to choose that operating point flexibly, and most of the remainder of this section is devoted to building one.

Figure 8.2.1: Tokenization granularities on one trade-off curve: a larger vocabulary encodes the same text in fewer tokens. Bytes never fall out of vocabulary; a fixed word list does. Byte pair encoding interpolates between the extremes.

8.2.2.2 From Tokens to Indices

Before moving to subwords, let us complete the classical pipeline, which several later sections of the book still use. Because neural networks operate on integer indices rather than strings, character and word pipelines rely on a vocabulary object that assigns each distinct token an index, sorted from most to least frequent, and maps unseen tokens to a reserved <unk> entry. Rare tokens occurring fewer than min_freq times can also be pruned to keep the vocabulary compact, falling back to <unk> as well.

class Vocab:
    """Vocabulary for text."""
    def __init__(self, tokens=(), min_freq=0, reserved_tokens=()):
        # Flatten a 2D list if needed
        if tokens and isinstance(tokens[0], list):
            tokens = [token for line in tokens for token in line]
        # Count token frequencies
        counter = collections.Counter(tokens)
        self.token_freqs = sorted(counter.items(), key=lambda x: x[1],
                                  reverse=True)
        # The list of unique tokens, ordered by descending frequency.
        # Reserve <unk> at index 0 so vocab[0] is the unknown token.
        self.idx_to_token = ['<unk>'] + list(reserved_tokens) + [
            token for token, freq in self.token_freqs
            if freq >= min_freq and token not in reserved_tokens]
        self.token_to_idx = {token: idx
                             for idx, token in enumerate(self.idx_to_token)}

    def __len__(self):
        return len(self.idx_to_token)

    def __getitem__(self, tokens):
        if not isinstance(tokens, (list, tuple)):
            return self.token_to_idx.get(tokens, self.unk)
        return [self.__getitem__(token) for token in tokens]

    def to_tokens(self, indices):
        if isinstance(indices, (list, tuple)) or getattr(indices, 'ndim', 0):
            return [self.idx_to_token[int(index)] for index in indices]
        return self.idx_to_token[int(indices)]

    @property
    def unk(self):  # Index for the unknown token
        return self.token_to_idx['<unk>']

To test Vocab, we build a vocabulary over our character tokens, map the first ten characters to integer indices, and invert them with vocab.to_tokens.

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']

The build convenience method packages this entire classical pipeline (preprocessing, tokenizing, and indexing) into a single call that returns the corpus of integer indices alongside its vocabulary.

@d2l.add_to_class(TimeMachine)
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)

8.2.2.3 Text as Bytes

To interpolate smoothly between characters and words, we first need a base alphabet capable of representing every possible string. Characters themselves are surprisingly ill-suited for this role: Unicode defines roughly 150,000 characters across scripts, diacritics, mathematical symbols, and emoji, so a character-level vocabulary ceases to be small as soon as we step beyond plain English. Modern tokenizers drop one level lower. Every string stored on a computer is ultimately represented as a sequence of bytes under a character encoding, almost universally UTF-8. Because a single byte takes one of only \(2^8 = 256\) values, a byte-level base vocabulary contains just 256 symbols and can never encounter an out-of-vocabulary input: any string, in any language, complete with punctuation, code, or typos, decomposes cleanly into bytes.

UTF-8 achieves this universality through a variable-length encoding that uses one byte for standard ASCII characters and up to four bytes for less common scripts and symbols.

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

The price of this universal alphabet is sequence length. Our novella expands to nearly 180,000 bytes (more than five tokens per word), and because accented letters such as “é” require two bytes, Chinese characters three, and emoji four, raw byte sequences stretch non-English text even further. Everything that follows preserves the universality of bytes while compressing sequences back down to manageable lengths.

8.2.3 Byte Pair Encoding

8.2.3.1 The Merge Rule

Byte pair encoding (BPE) began as a compression scheme: replace the most frequent pair of adjacent bytes by a new symbol, and repeat (Gage 1994). Sennrich et al. (2016) applied the same rule to the characters inside words to obtain subword units for machine translation, and GPT-2 returned it to raw bytes (Radford et al. 2019). This byte-level variant is the one we build. It begins with the 256 single-byte symbols and grows its vocabulary greedily: at each iteration, it counts every adjacent pair of tokens in the training corpus, merges the most frequent pair into a single new token, and repeats until the vocabulary reaches its target size. Because each merge shortens the corpus by exactly the number of occurrences it replaces, BPE acts as a greedy compression algorithm whose learned vocabulary forms a dictionary of the corpus’s most common recurring fragments.

Tracing the algorithm by hand makes its behavior transparent. Consider a toy corpus containing five distinct words across eight occurrences:

hug pug pun bun hugs hug hug pug

The raw corpus is 32 bytes long. The most frequent adjacent pair is (u, g), appearing six times (inside “hug”, “pug”, and “hugs”), so the first merge introduces the new token ug. After substituting ug everywhere, the most frequent adjacent pair becomes (h, ug), and the process continues:

step most frequent pair count new token corpus length
0 (start from bytes) 32
1 u, g 6 ug 26
2 h, ug 4 (tie) hug 22
3 hug, ' ' 3 (tie) 'hug ' 19

Note that steps 2 and 3 involve ties: (ug, ' ') also appears four times at step 2, while (' ', p) and (' ', hug) also appear three times at step 3. Following standard convention, we break ties in favor of the pair that occurs earliest in the corpus.

Two important properties emerge directly from this trace. First, merges compose hierarchically: because hug is formed from h and ug, the learned vocabulary defines a merge tree over the byte alphabet (Figure 8.2.2), allowing any unseen text to be segmented by replaying the learned merges. The word “hugs”, for instance, splits cleanly into hug and s, while the rare word “bun” remains three raw bytes—any substring untouched by learned merges simply falls back to individual bytes. Second, notice that step 3 fused a word with its trailing space. While a trailing space is benign on its own, nothing prevents subsequent merges from attaching the beginning of the following word as well. On a real corpus, unconstrained BPE readily creates multi-word tokens, a flaw we remedy shortly.

Figure 8.2.2: The first three merges learned on the toy corpus form a tree over the byte alphabet. New text reuses the tree: “hugs” becomes two tokens, while unseen fragments fall back to bytes.

8.2.3.2 Implementation

We implement the BPE algorithm in three concise pieces. First, the BPETokenizer class holds the tokenizer’s state: token ids 0 through 255 represent raw bytes, and each learned merge receives the next available integer id, so ids double as merge ranks (a smaller id indicates an earlier merge). The dictionary merges maps each merged pair of ids to its new id, while vocab maps every id to its corresponding byte string. The pattern and specials arguments, along with byte_ids, come into play later in this section and can be ignored for the moment. We also import the regex package, an extension of Python’s standard re module that supports Unicode character classes (such as \p{L} for any letter) needed for pre-tokenization.

import regex

class BPETokenizer:
    """Byte-level BPE tokenizer trained by iterated most-frequent-pair
    merges.

    Token ids 0..255 are raw bytes; learned merges get ids
    256..vocab_size-1; special tokens sit above those and are never
    produced by BPE itself. `pattern` is an optional pre-tokenization
    regex: text is split into chunks and merges never cross chunk
    boundaries.
    """

    GPT2_PATTERN = (r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+"
                    r"| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+")

    def __init__(self, vocab_size=1024, pattern=None,
                 specials=('<pad>', '<bos>', '<eos>')):
        self.vocab_size, self.pattern = vocab_size, pattern
        self.merges = {}                                  # (id, id) -> new id
        self.vocab = {i: bytes([i]) for i in range(256)}  # id -> bytes
        self.byte_ids = list(range(256))                  # byte value -> id
        self.specials = {s: vocab_size + i for i, s in enumerate(specials)}

    def __len__(self):
        return self.vocab_size + len(self.specials)

    @property
    def pad(self):
        return self.specials['<pad>']

    @property
    def bos(self):
        return self.specials['<bos>']

    @property
    def eos(self):
        return self.specials['<eos>']

    def _chunks(self, text):
        return [text] if self.pattern is None else regex.findall(
            self.pattern, text)

Both training and encoding depend on a single core operation: replacing every occurrence of a target pair of adjacent ids with the id of their merged token. The helper _merge scans left to right, writing new_id and advancing by two whenever pair matches, and copying one id otherwise. Consequently, on the string aaa, the pair (a, a) is replaced once on the left rather than overlappingly.

@d2l.add_to_class(BPETokenizer)
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

Training repeats the same loop we traced by hand: count all adjacent pairs, merge the most frequent pair everywhere, and record the resulting rule. Just as in the trace, ties are broken in favor of whichever pair was seen first—the exact behavior of Python’s max. One practical optimization is that identical text chunks are stored only once, with their pair counts weighted by the chunk’s frequency in the corpus. Before pre-tokenization, the entire corpus is a single chunk with weight 1; once pre-tokenization breaks text into words, a common word is processed once instead of thousands of times. Production BPE trainers go further by updating pair counts incrementally around each merge; here we simply recount after each step, trading speed for clarity.

@d2l.add_to_class(BPETokenizer)
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]

Training BPETokenizer for three merges (vocab_size=256 + 3) on our toy corpus and inspecting toy_tok.merges reproduces the three merge steps from our hand trace above:

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 '

8.2.3.3 Encoding and Decoding

Training produces a merge table. To encode new text, we start from its raw UTF-8 bytes and repeatedly merge the adjacent pair with the lowest merge rank until no adjacent pair appears in the table. Notice that encoding consults only the merge ranks—never corpus counts—so it is a pure function of the learned table: the tokenizer is completely defined by its merge ranks. Applying the lowest-ranked merge first faithfully retraces training, because each training merge was learned on text where all earlier merges had already been applied (a property formalized in the exercises). Decoding is simpler still: every token id maps directly to a byte sequence, so we concatenate the bytes and decode them as UTF-8, using errors='replace' so that any partial or malformed byte sequence emitted by a generative model degrades gracefully instead of raising an exception.

@d2l.add_to_class(BPETokenizer)
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

@d2l.add_to_class(BPETokenizer)
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'))]

@d2l.add_to_class(BPETokenizer)
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')

On the toy tokenizer, encoding matches our hand trace and decoding recovers the original string cleanly.

print([toy_tok.vocab[i] for i in toy_tok.encode('hugs')])
print([toy_tok.vocab[i] for i in toy_tok.encode('bun')])
toy_tok.decode(toy_tok.encode('hug pug hugs'))
[b'hug', b's']
[b'b', b'u', b'n']
'hug pug hugs'

8.2.3.4 Training on The Time Machine

To see what BPE learns from real prose, we train it on The Time Machine. Because token lists and generated passages often exceed the width of a printed page, we first define a small printing helper that wraps long lines neatly for use here and throughout the rest of the book.

import textwrap

def print_wrapped(*args, width=76):
    """Print like `print`, folding each line to the width of a page."""
    for line in ' '.join(str(a) for a in args).split('\n'):
        print(textwrap.fill(line, width, subsequent_indent='    '))

We now train a 1,024-token vocabulary directly on the raw, unnormalized text of the novella. The earliest merges capture common letter pairs, whereas the final merges assemble whole words from Wells’ prose. Notice, however, that one token in the encoded sample below is the two-word composite "Time Traveller ", spaces and all—an artifact we examine next.

tok = BPETokenizer(vocab_size=1024)
tok.train(raw_text)
merged_ids = list(tok.merges.values())
print('first:', [tok.vocab[i] for i in merged_ids[:8]])
print('last: ', [tok.vocab[i] for i in merged_ids[-8:]])
ids = tok.encode('The Time Traveller smiled. Are you sure?')
print_wrapped(len(ids), 'tokens:', [tok.vocab[i] for i in ids])
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'?']

How much shorter does a sequence become as we enlarge the vocabulary? Because merges are numbered in the exact order they are learned, any smaller BPE vocabulary is a prefix of a larger one trained on the same corpus: retaining only merges with id strictly below \(|\mathcal{V}|\) reproduces the exact tokenizer we would have obtained by stopping training at size \(|\mathcal{V}|\). A single training run therefore lets us sweep vocabulary sizes from 256 up to 4,096. Below, we measure compression in bytes per token on the first 10,000 characters of the novella (exercise 5 evaluates held-out text).

big = BPETokenizer(vocab_size=4096)
big.train(raw_text)
excerpt = raw_text[:10000]
sizes = [256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096]
ratios = []
for v in sizes:
    sub = BPETokenizer(vocab_size=v)  # the first v - 256 merges of big
    sub.merges = {p: i for p, i in big.merges.items() if i < v}
    sub.vocab = {i: b for i, b in big.vocab.items() if i < v}
    ratios.append(len(excerpt.encode('utf-8')) / len(sub.encode(excerpt)))
d2l.plot(sizes, [ratios], 'vocabulary size', 'bytes per token',
         xscale='log')

Each doubling of the vocabulary buys roughly a constant gain in compression, so bytes per token grows approximately logarithmically with vocabulary size. This scaling follows directly from the greedy merge rule: early merges such as "e ", "th", and "d " collapse thousands of occurrences apiece, whereas the 4,000th merge collapses only a handful. We should be careful, however, not to extrapolate this curve blindly to production vocabularies of 50,000 to 200,000 tokens. The upper end of our plot is flattered because we evaluated on the same text used to train the tokenizer, where a 4,096-token vocabulary has memorized words and phrases specific to The Time Machine. On general English prose, production vocabularies typically achieve four to five bytes per token—roughly one token per word—as we verify below, devoting their extra capacity to rarer words, source code, and (in multilingual vocabularies such as o200k_base) other languages.

8.2.3.5 Pre-Tokenization

The composite "Time Traveller " is hardly an isolated case. Alongside true word fragments, our unconstrained tokenizer accumulates dozens of tokens that straddle word boundaries:

crossers = [v.decode('utf-8', 'replace') for i, v in tok.vocab.items()
            if i >= 256 and b' ' in v.strip(b' ')]
print_wrapped(len(crossers), 'tokens cross a word boundary, e.g.',
              crossers[:8])
78 tokens cross a word boundary, e.g. [', and ', 'of the ', '. I ', '. Th',
    '. A', '. I', 'in the ', 'ed to ']

Although multi-word merges like "of the " help compress the training text, they are brittle composites: they consume vocabulary slots on fixed phrases while fragmenting the statistical evidence for their constituent words (since "of" now appears scattered across many distinct tokens). Every production BPE tokenizer therefore inserts a pre-tokenization stage before merging. A regular expression first splits the input string into chunks, and BPE is trained and applied strictly within each chunk so that merges never cross chunk boundaries. GPT-2’s pattern (Radford et al. 2019), stored as BPETokenizer.GPT2_PATTERN, consists of five branches:

's|'t|'re|'ve|'m|'ll|'d        common English contractions, split off
| ?\p{L}+                      a run of letters, with its leading space
| ?\p{N}+                      a run of digits, with its leading space
| ?[^\s\p{L}\p{N}]+            a run of punctuation or other symbols
|\s+(?!\S)|\s+                 remaining whitespace

This pattern encodes three deliberate conventions: each word retains its leading space (" the" rather than "the ") so that spacing travels with the word itself; letters, digits, and punctuation are separated into distinct chunks so that numbers and symbols never fuse onto words; and common English contractions are split off as standalone chunks.

regex.findall(BPETokenizer.GPT2_PATTERN,
              "The traveller's clock struck 12,345 times.")
['The',
 ' traveller',
 "'s",
 ' clock',
 ' struck',
 ' 12',
 ',',
 '345',
 ' times',
 '.']

Enabling pre-tokenization requires only passing pattern to BPETokenizer; Figure 8.2.3 illustrates the full pipeline from raw text to token ids. Compared with the unconstrained run, every boundary-crossing composite vanishes, freeing those vocabulary slots for complete words paired with their leading spaces. The earliest merges now attach frequent letters to leading spaces (" t", " a") or join common letter pairs ("he", "in").

bpe = BPETokenizer(vocab_size=1024, pattern=BPETokenizer.GPT2_PATTERN)
bpe.train(raw_text)
crossers = [v for i, v in bpe.vocab.items()
            if i >= 256 and b' ' in v.strip(b' ')]
print('boundary-crossing tokens now:', len(crossers))
gained = sorted(set(bpe.vocab.values()) - set(tok.vocab.values()),
                key=lambda v: (-len(v), v))
print_wrapped('longest tokens gained instead:',
              [v.decode('utf-8', 'replace') for v in gained[:6]])
print('first merges:', [bpe.vocab[i] for i in list(bpe.merges.values())[:6]])
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']
Figure 8.2.3: Pre-tokenization in action on a real sentence. The regex first cuts the text into chunks: words with their leading spaces, digit runs, and punctuation. BPE merges are then applied within each chunk, and can never cross a chunk boundary.

8.2.4 Special Tokens

Training and serving pipelines also require a small set of control tokens that carry meaning for the infrastructure rather than the text itself: <pad> pads shorter sequences to a common batch length, <bos> marks the start of a sequence, and <eos> lets a model signal that generation has finished (the decoders of Section 8.6 watch for it as a stopping cue). Our BPETokenizer places these special ids above the BPE range—a deliberate safety invariant ensuring that ordinary text can never accidentally encode to a special token. Otherwise, any document or user message containing the literal characters "<eos>" could inject a control signal directly into the model’s input stream, a classic vector for prompt injection in which untrusted user text is interpreted as a system instruction. Accordingly, our encode method treats special token strings as ordinary bytes unless the caller explicitly passes allow_special=True, mirroring tiktoken’s allowed_special guard (which raises an error by default).

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

8.2.5 Tokenizers in the Wild

8.2.5.1 The Rank Table of a Production Tokenizer

Most widely deployed language models, including the GPT family and Llama from version 3 onward, rely on byte-level BPE tokenizers built along these exact lines, simply trained on vastly larger corpora. GPT-2’s tokenizer (Radford et al. 2019) is stored compactly as a lookup table mapping each token’s byte sequence to its merge rank, paired with the pre-tokenization regex and special-token registry; there is no neural network inside it. (Other subword families, such as WordPiece or Unigram, additionally store text normalization rules or token probabilities used to pick among competing segmentations.) OpenAI’s tiktoken library ships GPT-2’s rank table directly. Below, we inspect entries right across the boundary between single bytes and learned merges—noting that the leading underscore on _mergeable_ranks indicates an internal attribute whose name may change across library releases.

enc = tiktoken.get_encoding('gpt2')
print(list(enc._mergeable_ranks.items())[254:260])
print(enc._special_tokens)
[(b'\xa0', 254), (b'\xad', 255), (b' t', 256), (b' a', 257), (b'he', 258), (b'in', 259)]
{'<|endoftext|>': 50256}

Ranks 0 through 255 correspond to the individual bytes in a permuted order (GPT-2 lists printable ASCII characters first), followed from rank 256 onward by the learned merges in training order—the exact same layout as our BPETokenizer. Remarkably, GPT-2’s first four merges learned from 40 gigabytes of web text (" t", " a", "he", and "in") are identical to the first four merges bpe learned from a single nineteenth-century novella, reflecting the stability of the most frequent English character patterns.

8.2.5.2 Verifying Our Implementation

Because a BPE tokenizer is completely specified by its rank table, we can load GPT-2’s published ranks straight into our own BPETokenizer encoder. Each rank becomes a token id, and the 256 single-byte entries define the byte permutation. Since the published table records only the final bytes of each token rather than the pair of parents that formed it, we reconstruct each merge pair by replaying all lower-ranked merges on the token’s bytes until exactly two pieces remain. The reconstruction details below can be skimmed; the key point is the verification cell that follows.

@d2l.add_to_class(BPETokenizer)
@classmethod
def from_tiktoken(cls, name):
    """Load a published bytes->rank table (e.g. 'gpt2') into our encoder."""
    import tiktoken  # lazy: d2l itself does not require tiktoken
    enc = tiktoken.get_encoding(name)
    ranks = enc._mergeable_ranks
    tok = cls(vocab_size=len(ranks), pattern=enc._pat_str, specials=())
    tok.specials = dict(enc._special_tokens)
    tok.vocab = {rank: b for b, rank in ranks.items()}
    tok.byte_ids = [ranks[bytes([b])] for b in range(256)]
    for token, rank in ranks.items():
        if len(token) > 1:  # recover which pair merged into this token
            parts = [bytes([b]) for b in token]
            while len(parts) > 2:
                a, b = min(zip(parts, parts[1:]),
                           key=lambda p: ranks.get(p[0] + p[1],
                                                   float('inf')))
                i = list(zip(parts, parts[1:])).index((a, b))
                parts[i:i + 2] = [a + b]
            tok.merges[ranks[parts[0]], ranks[parts[1]]] = rank
    return tok

On a test paragraph mixing prose, numbers, accented characters, currency symbols, and an emoji, our encoder matches tiktoken token for token—an assertion checked automatically whenever this book is built.

ours = BPETokenizer.from_tiktoken('gpt2')
para = ('The Time Traveller (for so it will be convenient to speak of '
        'him) was expounding a recondite matter to us; his pale grey '
        'eyes shone and twinkled. Prices rose 3.5% in 1895, and naïve '
        'café patrons paid £12,345 more! 🚀')
assert ours.encode(para) == enc.encode(para)
print(len(ours.encode(para)), 'tokens, identical to tiktoken')
print([ours.vocab[i].decode('utf-8', 'replace')
       for i in ours.encode(para)[:8]])
60 tokens, identical to tiktoken
['The', ' Time', ' Trave', 'ller', ' (', 'for', ' so', ' it']

How well do large production vocabularies compress The Time Machine? Below, we compare our 1,024-token tokenizer against GPT-2’s 50,257-token vocabulary and o200k_base, the roughly 200,000-token vocabulary used by GPT-4o.

rows = [('ours (1k, in-domain)', len(bpe.encode(raw_text)))]
for name in ('gpt2', 'o200k_base'):
    e = tiktoken.get_encoding(name)
    rows.append((f'{name} ({len(e._mergeable_ranks) // 1000}k)',
                 len(e.encode(raw_text))))
for name, n in rows:
    print(f'{name:>22}: {n:>6} tokens, {n_bytes / n:.2f} bytes/token')
  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

Even though our vocabulary is 50 to 200 times smaller, it achieves roughly two-thirds of their compression ratio because it was trained specifically on this novella. Like any statistical model, a tokenizer is a compression model of its training distribution and performs best on text resembling the corpus it was built from.

8.2.5.3 Fertility, Digits, and Glitch Tokens

The average number of tokens a tokenizer spends per word in a given language is known as its fertility. Because GPT-2’s tokenizer was trained primarily on English web text, translating the very same sentence into three languages yields starkly different token counts:

sentences = {
    'English': 'The time traveller returned after many years.',
    'German': 'Der Zeitreisende kehrte nach vielen Jahren zurück.',
    'Greek': 'Ο ταξιδιώτης του χρόνου επέστρεψε μετά από πολλά χρόνια.'}
for lang, s in sentences.items():
    gpt2, o200k = [len(tiktoken.get_encoding(e).encode(s)) / len(s.split())
                   for e in ('gpt2', 'o200k_base')]
    print(f'{lang:>8}: {gpt2:.2f} (gpt2), {o200k:.2f} (o200k_base) '
          'tokens per word')
 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

Under GPT-2’s tokenizer, a Greek word consumes roughly seven tokens (each Greek letter takes two UTF-8 bytes and very few Greek merges were learned), compared with roughly one token per English word. Consequently, a 1,024-token context window holds about 900 English words but only about 140 Greek words, making inference both slower and more expensive for non-English users. By contrast, the multilingual o200k_base vocabulary brings Greek fertility down to roughly two tokens per word.

Numbers reveal how subtle tokenization details reshape what a model must learn. Whereas GPT-2 splits digit sequences wherever BPE happened to discover frequent fragments, newer tokenizers cap digit chunks at three characters during pre-tokenization so that segmentation is more uniform:

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']

Even so, neither segmentation aligns with the columns of positional arithmetic, which groups digits from right to left into ones, tens, and hundreds. Under a left-to-right three-digit cap, "12345678" splits into "123", "456", and "78", forcing a language model to perform carries across misaligned boundaries. This mismatch is a well-known contributor to arithmetic errors in language models, and helps explain why inserting standard thousands separators ("12,345,678") can make numerical tasks easier.

Finally, a vocabulary entry is only as reliable as the model’s exposure to it during training. Early GPT-2 and GPT-3 vocabularies included tokens such as " SolidGoldMagikarp"—a Reddit username that appeared frequently enough in the tokenizer’s training corpus to earn a dedicated merge, yet was largely absent from the language model’s pretraining data. Such a glitch token can still be produced from user prompts even though its embedding vector received almost no gradient updates; prompted to repeat it, early models often responded with evasions or unrelated words.

enc.encode(' SolidGoldMagikarp')  # one token for an 18-character string
[43453]

8.2.6 Summary

A tokenizer bridges raw text and the integer sequences consumed by neural networks. Its vocabulary size governs a core trade-off between sequence length and output-layer size, while fixed word vocabularies additionally break on unseen words. Byte-level BPE begins with the 256 single-byte symbols, eliminating out-of-vocabulary inputs altogether, and greedily merges the most frequent adjacent token pairs until the target vocabulary size is reached. Because encoding replays learned merges strictly in rank order, the merge table alone defines the tokenizer. In practice, a pre-tokenization regex prevents merges from crossing word boundaries, and special control tokens are assigned ids above the BPE range so that ordinary text cannot synthesize them. GPT-2’s production tokenizer follows this exact construction at larger scale, and our implementation reproduces it token for token; its varying fertility across languages, its digit-splitting quirks, and its glitch tokens are all direct consequences of its training data and merge rules. In the next section, we turn to modeling the token sequences that a tokenizer produces.

8.2.7 Exercises

  1. Encoding by rank. Suppose a BPETokenizer with vocab_size=258 has learned exactly two merges: (b, c) with id 256, and then (a, b) with id 257. The rank rule of _encode_chunk always applies the lowest-ranked applicable merge. The leftmost rule always merges the leftmost adjacent pair that appears in the merge table.

    1. Segment the string “abc” under each of the two rules.
    2. Give the segmentation that every occurrence of “abc” in the training corpus had at the end of training, and say which rule agrees with it.
  2. [code] Special-token round trip. Section 8.2.4 places special tokens above the BPE id range so that ordinary text can never produce them. Construct a BPETokenizer whose specials add a document separator <sep> to the three defaults, and train it on raw_text. Let x be two short documents joined by <sep>.

    1. Encode x once with and once without allow_special=True, and check that both id sequences decode to x.
    2. Re-encode the decoded text once with allow_special=True and once without it. Which of the two id sequences from the previous sub-problem does each re-encoding reproduce? State what this implies for a pipeline that decodes a model’s output and later feeds the text back in as input.
    3. tiktoken raises an error when a special string appears in text that is not allowed to contain it, whereas encode treats the string as plain bytes. Give one situation in which each policy is preferable.

    Adapted from Andrej Karpathy, minbpe, Step 4.

  3. [code] Digit chunking. Tokenize the addition prompts “1234+5678=”, “1234+567=” and “567+678=” and their sums “6912”, “1801” and “1245” with the gpt2 and o200k_base encodings of tiktoken, writing out the token boundaries of each number.

    1. Under the three-digit cap of o200k_base, label each digit token with the place values (ones, tens, hundreds, thousands) it covers. For each prompt, state whether the tokens at matching positions of the two summands and of the sum cover the same place values. Explain what goes wrong for a model that adds token by token when they do not.
    2. Propose a pre-tokenization rule that aligns tokens with place value, and state one drawback of your rule.
  4. Glitch tokens. Section 8.2.5.3 attributes a glitch token to a string that was frequent in the tokenizer’s training corpus but rare in the language model’s.

    1. Why does the merge rule of BPETokenizer.train turn such a string into a single token rather than several fragments, and what role does pre-tokenization play in fixing the token’s extent?
    2. Propose a test that flags glitch tokens given the trained embedding table and the model’s training corpus, and state what each of the two inputs contributes.
  5. [code] Pre-tokenization ablation. ● Split raw_text into its first 90% and its last 10%. On the first part, train two 4,096-token tokenizers that differ only in the pattern: one without a pattern, as big was trained, and one with BPETokenizer.GPT2_PATTERN.

    1. List the 20 longest tokens learned by each tokenizer, and mark those that span more than one word.
    2. Measure which of the two compresses the first part better, and explain the outcome in terms of the merge rule.
    3. Measure bytes per token of both tokenizers on the last 10%. Which tokenizer loses the larger fraction of its compression on this held-out text, and which compresses it better? Relate both answers to the tokens you listed.