from_scratch.llm
From neural net to language
03

Turning text into numbers

char-level and Byte-Pair Encoding (BPE)
steps/02_language/03_tokenizer.py ► Open as notebook (with output)

Models only understand numbers, so we need a reversible map between text and integer IDs. We build a character tokenizer, then a tiny BPE — the algorithm GPT actually uses, which greedily merges the most frequent adjacent pair into a new token, over and over.

Watch it learn t,h → 'th' → 'the' → ' the'. Fewer tokens per word means more real text fits in the context window — the whole reason BPE beats characters.

merge* = argmax over adjacent pairs of count(a, b) → new tokenBPE greedily merges the most frequent adjacent pair, over and over.
The theory

A tokenizer is a reversible map between text and integer IDs, and its design is a trade-off between vocabulary size and sequence length. Character-level: tiny vocabulary, very long sequences, but never an unknown token. Word-level: short sequences, but a huge vocabulary and an out-of-vocabulary problem for any new word.

Byte-Pair Encoding finds the sweet spot. Starting from raw bytes/characters, it repeatedly merges the most frequent adjacent pair into a new subword token. Frequent chunks like the or ing become single tokens while rare words still decompose into pieces — an information-theoretic win, giving common patterns short codes. Modern LLMs use byte-level BPE for exactly this robustness, which is why fewer tokens per word means more text fits in the context window.

Animation
t · h · e · t · h · eth · e · th · ethe · the
Byte-Pair Encoding merges the most frequent adjacent pair, again and again: t,h → th → the. Fewer tokens carry the same text.
Visual walkthrough
Many small text-like tiles split into raw tokens.
Raw symbolsText first becomes small reversible pieces: characters or bytes.
Repeated adjacent token pairs combining into larger glowing chunks.
Frequent mergesBPE repeatedly merges the most frequent adjacent pair into a larger token.
Compressed token chunks fitting into a context-window rail.
Shorter contextCommon chunks use fewer tokens, so more real text fits into the model window.
The notebook · steps/02_language/03_tokenizer.ipynb — code cells & their output. Open & run on GitHub →
In [1]
from collections import Counter


# --------------------------------------------------------------------------
# 1. Character-level tokenizer
# --------------------------------------------------------------------------
class CharTokenizer:
    """One token per unique character in the training text."""

    def __init__(self, text):
        chars = sorted(set(text))
        self.stoi = {c: i for i, c in enumerate(chars)}
        self.itos = {i: c for c, i in self.stoi.items()}
        self.vocab_size = len(chars)

    def encode(self, text):
        return [self.stoi[c] for c in text]

    def decode(self, ids):
        return "".join(self.itos[i] for i in ids)


# --------------------------------------------------------------------------
# 2. Byte-Pair Encoding (BPE) tokenizer
# --------------------------------------------------------------------------
class BPETokenizer:
    """Learn a vocabulary by repeatedly merging the most common adjacent pair.

    Start with raw bytes (0..255) so ANY text is representable. Then run
    `num_merges` rounds; each round finds the most frequent neighbouring pair
    of token IDs and assigns it a brand-new ID.
    """

    def __init__(self):
        self.merges = {}   # (id_a, id_b) -> new_id, in the order learned
        self.vocab = {i: bytes([i]) for i in range(256)}  # id -> raw bytes

    def _pair_counts(self, ids):
        return Counter(zip(ids, ids[1:]))

    def _merge(self, ids, pair, new_id):
        """Replace every occurrence of `pair` in `ids` with `new_id`."""
        out, i = [], 0
        while i < len(ids):
            if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
                out.append(new_id)
                i += 2
            else:
                out.append(ids[i])
                i += 1
        return out

    def train(self, text, num_merges=20):
        ids = list(text.encode("utf-8"))          # bytes -> initial token IDs
        for k in range(num_merges):
            counts = self._pair_counts(ids)
            if not counts:
                break
            pair = max(counts, key=counts.get)     # most frequent adjacent pair
            new_id = 256 + k
            ids = self._merge(ids, pair, new_id)
            self.merges[pair] = new_id
            # Record what bytes this new token expands to (for decoding).
            self.vocab[new_id] = self.vocab[pair[0]] + self.vocab[pair[1]]
        return self

    @property
    def vocab_size(self):
        return len(self.vocab)

    def encode(self, text):
        ids = list(text.encode("utf-8"))
        # Apply merges in the SAME order they were learned.
        for pair, new_id in self.merges.items():
            ids = self._merge(ids, pair, new_id)
        return ids

    def decode(self, ids):
        raw = b"".join(self.vocab[i] for i in ids)
        return raw.decode("utf-8", errors="replace")


# --------------------------------------------------------------------------
# Demo
# --------------------------------------------------------------------------
In [2]
text = "the theme of the theater is the thunder"

print("=== CharTokenizer ===")
ct = CharTokenizer(text)
ids = ct.encode("the theme")
print("vocab size:", ct.vocab_size)
print("encode('the theme') ->", ids)
print("decode back        ->", repr(ct.decode(ids)))

print("\n=== BPETokenizer ===")
bpe = BPETokenizer().train(text, num_merges=10)
ids = bpe.encode("the theme")
print("vocab size:", bpe.vocab_size, "(256 bytes + learned merges)")
print("encode('the theme') ->", ids)
print("decode back        ->", repr(bpe.decode(ids)))
print(f"'the theme' is {len('the theme')} chars but only {len(ids)} BPE tokens")

print("\nLearned merges (most common pairs became single tokens):")
for pair, new_id in bpe.merges.items():
    piece = bpe.vocab[new_id].decode("utf-8", errors="replace")
    print(f"  {pair} -> {new_id}   = {piece!r}")
Output
=== CharTokenizer ===
vocab size: 14
encode('the theme') -> [12, 5, 3, 0, 12, 5, 3, 7, 3]
decode back        -> 'the theme'

=== BPETokenizer ===
vocab size: 266 (256 bytes + learned merges)
encode('the theme') -> [262]
decode back        -> 'the theme'
'the theme' is 9 chars but only 1 BPE tokens

Learned merges (most common pairs became single tokens):
  (116, 104) -> 256   = 'th'
  (256, 101) -> 257   = 'the'
  (32, 257) -> 258   = ' the'
  (101, 114) -> 259   = 'er'
  (257, 258) -> 260   = 'the the'
  (260, 109) -> 261   = 'the them'
  (261, 101) -> 262   = 'the theme'
  (262, 32) -> 263   = 'the theme '
  (263, 111) -> 264   = 'the theme o'
  (264, 102) -> 265   = 'the theme of'