Code Lab / Challenge 2

Byte-level BPE tokenizer: train, encode, decode

MediumByte-level BPE: train, encode, decode

The problem, as an interviewer would set it

Implement a byte-level Byte Pair Encoding tokenizer (stdlib only):

class BPETokenizer:
    def train(self, text: str, vocab_size: int) -> None
        Start from the 256 raw bytes. Repeatedly find the most frequent
        adjacent token pair in the corpus and merge it into a new token,
        until the vocab reaches `vocab_size` (or no pairs remain).
        Break frequency ties deterministically.

    def encode(self, text: str) -> list[int]
        Apply the learned merges to arbitrary text. Merges must be applied
        in the ORDER they were learned (lowest merge rank first), not
        greedily left-to-right.

    def decode(self, ids: list[int]) -> str
        Invert encode. decode(encode(s)) == s for ANY string s, including
        text never seen in training (byte-level means no <unk>).
What interviewers look for

Merge-rank order at encode time, byte-level round-trip on any unicode, deterministic tie-breaking

A strong solution: works on raw UTF-8 bytes so any unicode round-trips;
applies merges by training rank at encode time (the classic GPT-2 approach:
repeatedly merge the pair with the lowest rank present); keeps train() and
encode() logic consistent so encoding the training text reproduces the
final training state.

Common mistakes: operating on Python chars instead of bytes (then decode
crashes on unseen characters); merging greedily left-to-right at encode
time (produces different tokens than training did); nondeterministic
tie-breaking (dict order) so two training runs disagree; a full rescan of
the corpus per merge (O(n * merges)) that times out on a big corpus - fine
here, but say how you'd fix it (update pair counts only around each merge
site and pick the next merge from a priority queue).

Follow-up variations: why byte-level vs char-level (no OOV, 256-symbol
base alphabet); regex pre-tokenization (GPT-2 and tiktoken encodings split
text into word, number and punctuation chunks first, so merges never cross
those boundaries - why does that help?); special tokens and why they're
inserted outside BPE; how tokenizer choice affects arithmetic and code
(single-digit vs up-to-3-digit number chunks, whitespace runs in code).

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge