GNGiseldo Neo and Alana NeoBooks
Language Models with Python4 / 16

Tokenization and Vocabularies

Objective

This chapter details the fundamental bridge between human language and the numerical representation understood by neural networks. We will explore the theory of subword tokenization, implement the Byte-Pair Encoding (BPE) algorithm from scratch, and discuss the data-preparation architecture for training Large Language Models (LLMs).

4.1 Why Tokenization Is Necessary

Neural networks do not process strings; they process tensors of numbers (floating point or integers). The process of converting text into numbers is called tokenization.

Language models do not process text directly as strings of characters. They operate on discrete units called tokens. Tokenization is the process of converting text into a sequence of tokens that the model can process mathematically.

The granularity of tokenization varies across approaches. At one extreme, we have character-level tokenization, where each character is a token. At the other extreme, we have word-level tokenization, where each word is a token. Most modern LLMs use an intermediate approach called subword tokenization, which splits uncommon words into smaller units while keeping frequent words as single tokens.

4.2 Overview of Byte Pair Encoding (BPE)

The most widely used algorithm for tokenization in LLMs is Byte Pair Encoding (BPE), or some variant of it. Originally developed for data compression, BPE was adapted for natural-language tokenization and offers an excellent balance between granularity and vocabulary size.

BPE works by starting with a vocabulary of individual characters and iteratively merging the most frequent pair of tokens to create new tokens. The process continues until the vocabulary reaches a desired size. The result is a vocabulary that contains both characters and character sequences of varying lengths, from the most frequent whole words to the least frequent subwords.

For example, the word “unbelievably” would be tokenized into smaller units such as [“un”, “believ”, “ably”], since it is unlikely to appear frequently as a single word. The word “the”, on the other hand, would be a single token, since it appears with very high frequency.

4.3 Typical Vocabularies and Their Sizes

The vocabularies used in modern LLMs vary in size, typically between 30,000 and 200,000 unique tokens. Larger vocabularies capture more nuance but require more memory and computation. Smaller vocabularies are more efficient but may force many words to be split into multiple tokens, increasing the length of the input sequence.

Tokenization also contributes to inference cost. Processing text to produce tokens and, in the opposite direction, converting tokens back into text are operations performed in every interaction with the model.

4.4 The Impact of Tokenization on Generation

The way text is tokenized has profound implications for the model’s behavior. Different languages tokenize in radically different ways: languages such as English tokenize relatively well with BPE, while languages such as Chinese or languages with complex writing systems may require specialized tokenizers to achieve comparable efficiency.

The number of tokens in a text also directly affects the computational cost of processing it. Many API services that use LLMs charge based on the number of tokens processed, reflecting the real computational cost of tokenization and the subsequent processing.

4.4.1 The Granularity Dilemma

Historically, there were two main approaches, both with severe limitations for modern models:

  1. Word-level tokenization:
    • Splits the text on spaces.
    • Problem: The vocabulary becomes gigantic (millions of possible words). Words not seen during training become <UNK> (Unknown) tokens, losing semantic information.
  2. Character-level tokenization:
    • Splits the text into individual letters.
    • Problem: The vocabulary is small, but sequences become extremely long, making it harder to model long-term dependencies and increasing computational cost.

4.4.2 The Solution: Subword Tokenization

The modern approach (used by GPT-4, Llama 3, BERT) is subword tokenization. It is based on the principle that frequent words should not be split, but rare words should be decomposed into smaller, meaningful units.

  • Example: The word “tokenization” can be split into ["token", "iza", "tion"].
  • Benefit: It allows a fixed-size vocabulary (e.g., 32k to 100k tokens) capable of representing virtually any word through the composition of subunits.

4.5 Training Byte Pair Encoding (BPE)

BPE is an iterative algorithm that builds a vocabulary by merging the most frequent pairs of characters (or bytes) in the training corpus.

4.5.1 BPE Training Flow

Below, the diagram illustrates the life cycle of training a BPE tokenizer:

Diagram

4.5.2 Execution Example (Trace)

Suppose the corpus: ("hug", 10), ("pug", 5), ("pun", 12), ("bun", 4)

  1. Base: h, u, g, p, n, b
  2. Iteration 1: The pair u, n appears in “pun” and “bun” (12 + 4 = 16 times). It is the most frequent.
    • New token: un.
    • Vocabulary: h, u, g, p, n, b, un.
  3. Iteration 2: The pair u, g appears in “hug” and “pug” (10 + 5 = 15 times).
    • New token: ug.
    • Vocabulary: h, u, g, p, n, b, un, ug.

4.6 Practical Implementation: BPE from Scratch in Python

Next, we implement a simplified BPE to demonstrate the internal logic of string manipulation and statistical counting.

import collections
import re

class SimpleBPE:
    def __init__(self, vocab_size=300):
        self.vocab_size = vocab_size
        self.merges = {} # Stores the merge rules
        self.vocab = {}  # Token -> ID mapping

    def get_stats(self, vocab_counts):
        """Counts the frequency of all adjacent pairs."""
        pairs = collections.defaultdict(int)
        for word, freq in vocab_counts.items():
            symbols = word.split()
            for i in range(len(symbols) - 1):
                pairs[symbols[i], symbols[i+1]] += freq
        return pairs

    def merge_vocab(self, pair, v_in):
        """Applies the merge of the most frequent pair to the current vocabulary."""
        v_out = {}
        bigram = re.escape(' '.join(pair))
        p = re.compile(r'(?<!\S)' + bigram + r'(?!\S)')

        for word in v_in:
            # Replaces 'a b' with 'ab'
            w_out = p.sub(''.join(pair), word)
            v_out[w_out] = v_in[word]
        return v_out

    def train(self, text):
        # 1. Simple pre-tokenization (split on spaces) and counting
        word_freqs = collections.defaultdict(int)
        for word in text.split():
            # Adds spaces between chars to represent the initial split
            # E.g.: "hello" -> "h e l l o"
            word_freqs[" ".join(list(word))] += 1

        num_merges = self.vocab_size - len(set("".join(text.split())))

        print(f"Starting BPE training for {num_merges} merges...")

        # 2. Training loop
        for i in range(num_merges):
            pairs = self.get_stats(word_freqs)
            if not pairs:
                break

            # Finds the most frequent pair
            best = max(pairs, key=pairs.get)
            self.merges[best] = "".join(best)

            # Updates the vocabulary by applying the merge
            word_freqs = self.merge_vocab(best, word_freqs)

            if i % 10 == 0:
                print(f"Iteration {i}: Merge {best} -> {''.join(best)}")

        # Build the final vocabulary (Token -> ID)
        # In practice, we would include special tokens here
        unique_tokens = set()
        for word in word_freqs:
            unique_tokens.update(word.split())

        self.vocab = {token: i for i, token in enumerate(sorted(unique_tokens))}
        print(f"Training complete. Vocabulary size: {len(self.vocab)}")

    def encode(self, text):
        """Tokenizes a new text using the learned rules."""
        # This is a simplified version. A real encoder would apply
        # the merge rules in the same order in which they were learned.
        tokens = []
        for word in text.split():
            word_spaced = " ".join(list(word))

            # Applies merges iteratively (inefficient, purely didactic)
            # In production, an optimized tree or hash map is used
            for pair, merged in self.merges.items():
                bigram = " ".join(pair)
                if bigram in word_spaced:
                    word_spaced = word_spaced.replace(bigram, merged)

            word_tokens = word_spaced.split()
            ids = [self.vocab.get(t, self.vocab.get("<UNK>", 0)) for t in word_tokens]
            tokens.extend(ids)
        return tokens

# --- Usage Example ---
corpus = "low low low low low lower lower newest newest newest wider wider wider"
tokenizer = SimpleBPE(vocab_size=20) # Small vocabulary for testing
tokenizer.train(corpus)

print("\nVocabulary:", tokenizer.vocab)
print("Encode 'lower newest':", tokenizer.encode("lower newest"))

4.7 Preparing the Training Dataset

Having a tokenizer is only the first step. To train an LLM, the data must be structured into tensors with special tokens and context windows.

4.7.1 Special Tokens

A robust vocabulary should include control tokens that do not appear in natural text:

TokenMeaningFunction
[PAD]PaddingFills short sequences to keep the batch size fixed. Usually ID 0.
[UNK]UnknownRepresents characters or subwords the model has never seen.
[BOS]Beginning of SentenceSignals the start of a sequence (crucial for generation).
[EOS]End of SentenceSignals where generation should stop.
[MASK]MaskUsed in BERT-style models for filling in blanks.

4.7.2 Transformation Pipeline: From Text to Tensor

The final process involves normalization, tokenization, and structuring into sliding windows or packing.

Diagram

4.7.3 Context Strategies (Context Window)

When preparing the dataset, continuous text must be sliced to fit the model’s context window (e.g., 4096 tokens).

  1. Truncation: Cut the text if it exceeds the limit.
  2. Sliding window: Create overlapping examples.
    • Example: Text [A, B, C, D, E], window 3.
    • Sample 1: [A, B, C]
    • Sample 2: [B, C, D] (stride=1)
  3. Packing: Concatenate multiple short texts into a single sequence, separated by [EOS], to maximize GPU efficiency (avoiding excessive [PAD]).

4.8 Architecture Considerations

When designing this pipeline for production:

  • Unicode normalization: Use the NFKC form to ensure that visually identical characters have the same byte representation.
  • Byte-level BPE: Models such as GPT-2/3/4 operate at the level of UTF-8 bytes, not Unicode characters. This eliminates the <UNK> token, since any string can be decomposed into bytes.
  • Efficiency: The Python implementation above is educational. In production, use libraries written in Rust (such as Hugging Face tokenizers) that parallelize pair counting and merge application.

4.9 Tokenization Changes the Computational Problem

Two texts with the same number of characters can produce very different numbers of tokens. Code, rare words, emojis, and languages poorly represented in the training corpus tend to be fragmented differently. This affects cost, latency, and how much content fits in the context window.

Consider transformer, which could be a single frequent token or be split into parts such as transform and er. The second representation allows subwords to be reused in terms never seen before, but increases TT, the sequence length. Since dense attention builds a T×TT\times T matrix, small changes in fragmentation can have a quadratic effect on that part of the cost.

Experiment

Tokenize the same sentence in Portuguese and in English with a real tokenizer. Compare the identifiers, the number of tokens, and the reconstruction with decode. Never assume that spaces or accented characters correspond one-to-one to tokens.

4.10 The Contract Between Tokenizer and Model

The tokenizer is part of the model just as much as the weight matrices are. Each ID selects a specific row of the embedding table; changing the vocabulary without adapting that table changes the meaning of every index. For this reason, the checkpoint, the configuration, and the tokenizer files must be versioned together.

Special tokens also need consistent semantics. <bos> may mark the start, <eos> signal the end, <pad> fill batches, and role tokens separate system, user, and assistant messages. If the chat template places these markers in a different order from the one seen in training, quality may drop even if the visible text looks correct.

4.10.1 An Example of Causal Preparation

For IDs [11, 27, 42, 9], autoregressive training can use:

input:  [11, 27, 42]
target: [27, 42,  9]

In a padded batch, artificial positions should not contribute to the loss. An attention mask controls which tokens can be attended to; an ignore_index in the loss function controls which targets will be evaluated. These are different responsibilities.

4.10.2 Robustness at the Byte Level

Byte-based tokenizers can represent any UTF-8 sequence without relying on an unknown token. The advantage is universal coverage; the disadvantage is that texts with rare patterns may fragment into many units. This unequal efficiency should be measured in the language and domain of the application.

Round-trip test

For valid inputs, check that decode(encode(text)) reconstructs the text according to the adopted normalization rules. Run explicit tests with accents, emojis, line breaks, code, and consecutive spaces.