Part I of Cartesia's From Tokens to Bytes posts sums up Byte Pair Encoding in one sentence: start from the 256 byte values and repeatedly merge the most frequent pair of adjacent tokens on a training corpus until the vocabulary reaches a set size. Implement exactly that on raw UTF-8 bytes, with optional pretoken chunks that no merge may cross.
A token is a bytes object. Every chunk starts as a list of single-byte tokens, so b'hi' starts as [b'h', b'i'].
train_byte_bpe(chunks, vocab_size)
chunks is a list of bytes. Pass [corpus] to train without pretokenization, or the list of pretokens to train with it. A chunk may appear many times and every occurrence counts.vocab_size - 256 merges, or stop earlier when no chunk has two adjacent tokens left:
b'aaa' contributes the pair (b'a', b'a') twice.(left, right) tuple under Python's ordering of bytes, so (b'a', b'b') < (b'a', b'bc') < (b'ab', b'a').[b'a', b'a', b'a'] becomes [b'aa', b'a']), and record (left, right).ValueError if vocab_size < 256.bpe_encode(data, merges)
bytes chunk with a merge list: start from single bytes, then apply each merge in order to the whole sequence, left to right without overlap.bytes tokens ([] for empty input). On a training chunk this reproduces the segmentation the trainer ended with.