# bend-bpe-tokenizer Byte-level BPE tokenizers from a Hugging Face `tokenizer.json`, in Bend 2, giving the same ids as Hugging Face's `tokenizers` (`encode(text, add_special_tokens=False)`), and the text back from ids. ```python import bend-bpe-tokenizer@/tok.bend as TK ``` ```python def show(ids: List<&2, U32>) -> String: match ids: case []: "" case i <> t: U32.show(i) ++ " " ++ show(t) def encoded(r: Result<&2, &2, TK.Err, List<&2, U32>>) -> IO(Unit): match r: case Done{ids}: IO.print(show(ids)) case Fail{e}: IO.print("not UTF-8, or a token missing from the vocabulary") def opened(r: Result<&2, &2, String, TK.Tok>) -> IO(Unit): match r: case Done{t}: encoded(TK.encode(t, [72, 101, 108, 108, 111])) # "Hello", as UTF-8 bytes case Fail{why}: IO.print(why) def main() -> IO(Unit): do IO: r : Result<&2, &2, String, TK.Tok> <- TK.open("tokenizer.json") opened(r) ``` ## Which tokenizers Byte-level BPE files of these families, recognized by their pre-tokenizer: | Family | Split pattern | Examples | | - | - | - | | Qwen2 / Qwen3 | `(?i:'s\|'t\|...)\|[^\r\n\p{L}\p{N}]?\p{L}+\|\p{N}\|...` | Qwen2.5, Qwen3, Qwen3-VL | | Qwen3.5 and later | the same, with combining marks in words (`[\p{L}\p{M}]+`) | Qwen3.6 | | Llama 3 | Qwen2's with `\p{N}{1,3}`, and `ignore_merges` | Llama 3, 3.1, 3.2 | | GPT-2 | GPT-2's, from a `ByteLevel` pre-tokenizer with `use_regex` | GPT-2, RoBERTa, BART | The normalizer must be NFC or none, the decoder ByteLevel, and the model BPE without dropout, an unknown token, subword prefixes or suffixes, or byte fallback. Added tokens are matched in the raw text (the longest first) and may not use `lstrip`, `rstrip` or `single_word`. Any other file is refused with the reason. ## API (`tok.bend`) | Definition | What it does | | - | - | | `open(path) -> IO(Result)` | reads a tokenizer.json (its lexing spread over the CPU's threads), or says why it can't | | `load(bytes) -> Result` | the same, from the file's bytes | | `encode(tok, bytes) -> Result>` | the ids of UTF-8 text; `Err` is `BadUtf8{at}` (the offset of the first ill-formed sequence) or `NoToken{token}` | | `decoder(tok)`, `decode(dec, ids) -> List` | the UTF-8 bytes of ids (an added token gives its own text; an unknown id gives nothing) | Encoding is: added tokens found in the raw text, the rest normalized (NFC, if the file says so), split by the family's regex, each piece's UTF-8 bytes mapped to GPT-2's byte-level characters and merged pair by pair, lowest merge rank first (the leftmost on a tie), then each token's id. ## Unicode, as Hugging Face sees it The regex classes (`\p{L}`, `\p{M}`, `\p{N}`, `\s`) and NFC's data (decompositions, combining classes, compositions) are in `tables.bend`, generated from the installed `tokenizers` itself (`dev/classify.py`, then `dev/gen_tables.py`), because its two halves use different Unicode versions: 16.0 for the split regex, an older one (between 7.0 and 12.x) for NFC. Hangul is computed. So characters from scripts newer than its NFC data stay unnormalized, as there. ## Laws `LAWS.bend` states 12 laws and `PROOF.bend` proves them (`bend PROOF.bend` prints ALL PROOFS CHECK; with bend-mathlib 0.8.1.0's list lemmas). Three hold for every input: | Law | Says | | - | - | | `split_partition` | for every family and text, the pieces the pre-tokenizer cuts concatenate back to the text | | `bpe_conserves` | however the ranks fall and however many merges run, the tokens concatenate to the bytes merged | | `added_partition` | for every list of added tokens and text, the plain segments and added-token matches cover the text exactly | The others pin decided behaviour at literal inputs: the longest added token wins; ill-formed UTF-8 (a stray continuation byte, overlong forms, a surrogate, above U+10FFFF, C1, F5, a sequence cut short or broken) is refused with the offset of the bad sequence's first byte, also through `encode`; well-formed UTF-8 round-trips; the byte-level map inverts on all 256 bytes; JSON read in parallel blocks (of 1, 3 or 7 bytes, pretty-printed or minified) parses to what reading it whole gives; a Qwen file is read as its family and an unknown pattern refused; and a decomposed "é" next to an added token encodes and decodes back composed. What the laws leave to tests: that the pieces are cut where the regex cuts them, the merge order, and the Unicode tables. `test/compare.py` checks those against `tokenizers` itself. ## Tested `test/compare.py ENCODE_BINARY TOKENIZER_JSON CORPUS...` encodes a corpus with the Bend tokenizer (`test/encode.bend`, built with `bend test/encode.bend -o encode`) and with `tokenizers`, text by text. Every run below: 0 mismatches. | Tokenizer | Corpus | | - | - | | Qwen3-VL (Qwen2/3 family) | 17,767 texts, 2.9M characters: Unicode's NormalizationTest strings, source code, docs, licences, locale files; and every code point, 1.1M of them, 64 to a text | | Qwen3.6 (Qwen3.5+ family) | the same two corpora | | Llama 3 | the 17,767 texts | | GPT-2 family (Florence-2's BART tokenizer, `lstrip` turned off, minified to one line) | the 17,767 texts | | Qwen3-VL rewritten with its vocabulary on one 3 MB line (a line across 47 blocks) | the 17,767 texts | Before the Bend code, `dev/proto.py` (a Python model of the same algorithm on the same tables) matched `tokenizers` on every code point's NFC, 100,000 random strings of marks and jamo, 200,000 random strings through each family's split, and 60,000 texts (9.8M characters). ## Speed On a 32-thread CPU: opening Qwen's 7 MB tokenizer.json takes about 0.5 s (the file read in 64 KiB blocks lexed in parallel, the vocabulary and merges built into 64 hashed buckets in parallel); encoding then runs at about 80,000 characters a second, 10 ms for a 1,500-character prompt. Hugging Face's Rust loads the same file faster. ## Files | File | What | | - | - | | `tok.bend` | the API: loading and checking a tokenizer.json, encode, decode | | `utf8.bend`, `nfc.bend`, `split.bend`, `specials.bend`, `bpe.bend` | the stages | | `json.bend` | a JSON parser (sequential, or lexed in parallel blocks) | | `hmap.bend`, `tree.bend`, `tables.bend` | the hashed maps, the Unicode trees and their (generated) data | | `LAWS.bend`, `PROOF.bend`, `bend-check` | the laws, their proofs, the checker under a CPU limit | | `test/` | `encode.bend` (encode a corpus) and `compare.py` (against `tokenizers`) | | `dev/` | the generators of `tables.bend` (`classify.py`, `gen_tables.py`, `tables.json`) and the Python model (`proto.py`) | Needs Bend 2.0.40. MIT-0.