BPE Tokenizer

October 10, 2026 (2w ago)

Stack: Python, regex, pytest, mypy, GitHub Actions, semantic-release · Repo: Axeloooo/bpe-tokenizer

Problem

This is byte-level byte pair encoding built from first principles: learn merges from a corpus, turn text into token ids, and turn ids back into text, using the same splitting rules as the GPT-4 tokenizer.

The scope is deliberately narrow. It trains its own merges; it does not load cl100k_base, depend on tiktoken or claim output equivalence with either.

Architecture diagram

  corpus.txt
      |
      v
  CLI  (__main__.py)   train | encode | decode
      |
      +--------------------------+
      v                          v
  RegexTokenizer             BasicTokenizer
  GPT-4 / GPT-2 split        whole text, one stream
      |                          |
      v                          |
  UTF-8 byte chunks              |
      |                          |
      +------------+-------------+
                   v
        get_stats + merge loop     (merges never cross chunks in Regex)
                   |
                   v
        merges: pair -> id 256+i  --> vocab: id -> bytes
                   |
                   v
        JSON model file (version 1) <-- special tokens (Python API)
                   |
                   +--> loaded again by the CLI for encode / decode

A shared Tokenizer base holds the merge table, the vocabulary and JSON save/load. RegexTokenizer splits text into chunks first and pools pair statistics across them. Encoding applies the earliest-learned merge available; decoding concatenates vocabulary bytes. The CLI never registers special tokens, so they are used through the Python API.

Key decisions

Challenges

Results

Links