Byte-level BPE tokenizers, English and French (4,096 tokens), written from scratch

Two byte-pair encoding tokenizers of the GPT-2 kind (regex pre-split, merges learned from the 256 bytes), trained with a from-scratch implementation: one on an English novel (Pride and Prejudice), one on a French one (Le Comte de Monte-Cristo, tome I, first 80 %). Both are public-domain texts from Project Gutenberg.

They are small and meant to show how BPE behaves, not to serve a production model.

Try them in your browser: layeser.github.io โ€บ ML from scratch (type any text, see the two segmentations side by side).

What the measurements say

Bytes per token against vocabulary size

  • No unknown word, by construction: every text is bytes, and the 256 bytes are in the vocabulary. A word-level vocabulary of the same size, built from the same novel, misses 13.5 % of the words of an unseen book.
  • A language absent from training costs tokens: the English tokenizer needs 69 % more tokens than the French one for the same French text (534 against 316 tokens per 1,000 characters).

Tokens per 1000 characters by training language

Files

tokenizer_en.json, tokenizer_fr.json: {"pattern": regex, "merges": [[a, b], ...], "special_tokens": []}. Token ids 0โ€“255 are the bytes; merge number k creates token 256 + k. Encoding a chunk applies, among the pairs present, the merge learned first, until none applies.

Use them in Python

import json
import regex  # pip install regex (the pattern uses \p{L} and \p{N})
from huggingface_hub import hf_hub_download

tok = json.load(open(hf_hub_download("layeser/bpe-tokenizers-en-fr", "tokenizer_en.json")))
split = regex.compile(tok["pattern"])
rank = {tuple(p): 256 + k for k, p in enumerate(tok["merges"])}
vocab = [bytes([i]) for i in range(256)]
for a, b in tok["merges"]:
    vocab.append(vocab[a] + vocab[b])

def encode(text):
    out = []
    for chunk in split.findall(text):
        ids = list(chunk.encode("utf-8"))
        while len(ids) > 1:
            pair = min(zip(ids, ids[1:]), key=lambda p: rank.get(p, float("inf")))
            if pair not in rank:
                break
            new, merged, i = rank[pair], [], 0
            while i < len(ids):
                if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
                    merged.append(new); i += 2
                else:
                    merged.append(ids[i]); i += 1
            ids = merged
        out += ids
    return out

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

ids = encode("Mr. Darcy found the ballroom intolerable.")
print(len(ids), [vocab[i].decode("utf-8", errors="replace") for i in ids])
assert decode(ids) == "Mr. Darcy found the ballroom intolerable."

Code and licence

Training code, tests (the incremental training learns exactly the merges of the textbook algorithm) and explainer: github.com/Layeser/ai-portfolio โ€บ ml-from-scratch (docs/bpe_tokenizer.md). MIT licence. Training texts: Project Gutenberg, public domain.

Author: Sekou Kaba

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Space using layeser/bpe-tokenizers-en-fr 1

Collection including layeser/bpe-tokenizers-en-fr