# The laws of bend-bpe-tokenizer. Each is stated over every input where its shape allows (the three partition laws); # the rest pin the decided behaviour at literal inputs. Matching Hugging Face id for id (the tables, NFC, the regexes, # BPE order) is checked by test/compare.py against `tokenizers` itself, not here. import Base import ./utf8.bend as U import ./split.bend as S import ./bpe.bend as B import ./hmap.bend as H import ./specials.bend as A import ./tok.bend as TK import ./json.bend as J # ---- helpers for the literal laws ---- def ascii(s: String) -> List<&2, U32>: match s: case SNil{}: [] case SCon{c, t}: Char.to_u32(c) <> ascii(t) def byte_ok(n: Nat) -> Bool: match n: case 0n: True{} case 1n+ +p: Bool.and(U32.is_eq(B.char_byte(B.byte_char(U32.from_nat(p))), U32.from_nat(p)), byte_ok(p)) # a load's outcome: the family it was read as, or why it was refused def outcome(r: Result<&2, &2, String, TK.Tok>) -> String: match r: case Fail{why}: why case Done{t}: "family " ++ U32.show(TK.tok_fam(t)) def ids_of(r: Result<&2, &2, TK.Err, List<&2, U32>>) -> List<&2, U32>: match r: case Done{ids}: ids case Fail{e}: [] def err_at2(e: TK.Err) -> U32: match e: case TK.BadUtf8{at}: at case TK.NoToken{t}: 4294967294 # the offset a failed encode names (0 for anything else) def err_at(r: Result<&2, &2, TK.Err, List<&2, U32>>) -> U32: match r: case Done{ids}: 4294967295 case Fail{e}: err_at2(e) # encode, then decode def round(r: Result<&2, &2, String, TK.Tok>, bs: List<&2, U32>) -> List<&2, U32>: match r: case Fail{why}: [] case Done{+t}: TK.decode(TK.decoder(t), ids_of(TK.encode(t, bs))) # a tiny Qwen-family tokenizer: four tokens (h, the two byte-level characters of é's UTF-8 bytes C3 A9, and their merge) def tiny(pattern: String) -> List<&2, U32>: ascii("{\"normalizer\": {\"type\": \"NFC\"}, \"pre_tokenizer\": {\"type\": \"Sequence\", \"pretokenizers\": [{\"type\": \"Split\", \"pattern\": {\"Regex\": \"" ++ pattern ++ "\"}, \"behavior\": \"Isolated\", \"invert\": false}, {\"type\": \"ByteLevel\", \"add_prefix_space\": false, \"trim_offsets\": false, \"use_regex\": false}]}, \"decoder\": {\"type\": \"ByteLevel\"}, \"added_tokens\": [{\"id\": 4, \"content\": \"\", \"lstrip\": false, \"rstrip\": false, \"single_word\": false, \"normalized\": false, \"special\": true}], \"model\": {\"type\": \"BPE\", \"dropout\": null, \"unk_token\": null, \"vocab\": {\"h\": 0, \"\\u00c3\": 1, \"\\u00a9\": 2, \"\\u00c3\\u00a9\": 3}, \"merges\": [\"\\u00c3 \\u00a9\"]}}") def qwen_pattern() -> String: "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\\\r\\\\n\\\\p{L}\\\\p{N}]?\\\\p{L}+|\\\\p{N}| ?[^\\\\s\\\\p{L}\\\\p{N}]+[\\\\r\\\\n]*|\\\\s*[\\\\r\\\\n]+|\\\\s+(?!\\\\S)|\\\\s+" # ---- splitting never loses or duplicates text ---- # Guarantees: for every family and every classified text, the pieces the pre-tokenizer cuts, concatenated in order, # are exactly the text. # Why it matters: a piece dropped, repeated or reordered would give ids for a different prompt with no error; this # holds whatever the split rules decide, so a wrong rule can only cut in the wrong place. law split_partition: for +fam: U32 for +xs: List<&2, S.CC> {List.concat(&2, S.CC, S.split(fam, xs)) == xs : List<&2, S.CC>} # ---- merging keeps the bytes ---- # Guarantees: however many merges run and whatever the ranks are, the tokens BPE leaves, concatenated, are the # byte-level characters it started with. # Why it matters: a merge that lost or duplicated a byte would encode a different text; ids could still all be valid. law bpe_conserves: for fuel: Nat for +ranks: H.HM for +ps: List<&2, List<&2, U32>> {List.concat(&2, U32, B.bpe_go(fuel, ranks, ps)) == List.concat(&2, U32, ps) : List<&2, U32>} # ---- added tokens are cut from the text itself ---- # Guarantees: for every list of added tokens and every text, the plain segments and the added-token matches cover # the text exactly, in order. # Why it matters: text around a special token (a chat template's) must reach the tokenizer whole. law added_partition: for +added: List<&2, A.AT> for +xs: List<&2, U32> {A.text_of(A.split_added(added, xs)) == xs : List<&2, U32>} # ---- the longest added token wins ---- # Guarantees: with added tokens (id 1) and b (id 2), "xby" splits as x, b (id 2), y. # Why it matters: Hugging Face matches the longest added token; matching would leave a stray "b". law added_longest: {A.split_added([A.AT{ascii(""), 1}, A.AT{ascii("b"), 2}], ascii("xby")) == [A.SText{ascii("x")}, A.SAdded{2, ascii("b")}, A.SText{ascii("y")}] : List<&2, A.Seg>} # ---- ill-formed UTF-8 is refused, at the right byte ---- # Guarantees: well-formed text of 1- to 4-byte characters decodes and encodes back to the same bytes; a stray # continuation byte, overlong 2-, 3- and 4-byte forms, a surrogate, a code point above U+10FFFF, the bytes C1 and F5, # a sequence cut short and one broken by a non-continuation byte are each refused with the offset of the first byte # of the bad sequence. # Why it matters: decision 6: a prompt file that is not UTF-8 is an error naming where, not a silently changed prompt. law utf8_round: {U.encode(U.decode_ok([104, 195, 169, 226, 130, 172, 240, 159, 152, 128])) == [104, 195, 169, 226, 130, 172, 240, 159, 152, 128] : List<&2, U32>} law utf8_refusals: {[U.decode([97, 128]), U.decode([97, 192, 175]), U.decode([237, 160, 128]), U.decode([97, 98, 244, 144, 128, 128]), U.decode([226, 130]), U.decode([224, 159, 128]), U.decode([240, 143, 128, 128]), U.decode([193, 129]), U.decode([245, 128, 128, 128]), U.decode([104, 226, 40, 161])] == [Fail{1}, Fail{1}, Fail{0}, Fail{2}, Fail{0}, Fail{0}, Fail{0}, Fail{0}, Fail{0}, Fail{1}] : List<&2, Result<&2, &2, U32, List<&2, U32>>>} # Guarantees: encoding "h" followed by the byte FF (never valid in UTF-8) is refused as ill-formed UTF-8 at offset 1. # Why it matters: decision 6 through the public entry point: encode reports where the text is bad, not an id list. law encode_refuses: {err_at(TK.encode_with(TK.load(tiny(qwen_pattern())), [104, 255])) == 1 : U32} # ---- the byte-level map is invertible ---- # Guarantees: every byte 0 to 255 maps to a byte-level character that maps back to it. # Why it matters: decode reads bytes back through this map; two bytes sharing a character would decode wrongly. law byte_level_inverse: {byte_ok(256n) == True{} : Bool} # ---- known families are read, others refused ---- # Guarantees: a Qwen-family tokenizer.json is read as family 0; the same file with any other split pattern is refused # as not a known family. # Why it matters: decision 1: a tokenizer this package cannot reproduce must be refused, not silently mis-tokenized. law family_known: {outcome(TK.load(tiny(qwen_pattern()))) == "family 0" : String} law family_unknown: {outcome(TK.load(tiny("\\\\p{L}+"))) == "the pre-tokenizer is not a known byte-level family's (Qwen2/3, Qwen3.5+, Llama 3, GPT-2)" : String} # ---- reading a file in parallel blocks parses as reading it whole ---- # the text cut into blocks of size bytes, parsed block-parallel def by_blocks(+size: Nat, +bs: List<&2, U32>) -> Result<&2, &2, String, J.J>: J.parse_blocks(J.blocks(List.length(&2, U32, bs), size, bs)) def pretty() -> List<&2, U32>: ascii("{\n \"a\": [1, 22,\n \"x\\ny\"],\n \"bb\": {\"c\": null, \"d\": true}\n}\n") def minified() -> List<&2, U32>: ascii("{\"a\":[1,22,\"x\\ny\"],\"bb\":{\"c\":null,\"d\":true}}") # Guarantees: a pretty-printed JSON text (lines longer than a block, and blocks inside one line) and a minified one # (no newline at all) parse block-parallel, at block sizes 1, 3 and 7 bytes, to the value the one-piece parse gives. # Why it matters: Tok.open lexes a file's blocks in parallel; a block boundary handled wrongly loses or repeats text # (it did, once, for a minified file: a GPT-2 tokenizer.json was refused as "not JSON"). law blocks_agree: {[by_blocks(1n, pretty()), by_blocks(3n, pretty()), by_blocks(7n, pretty()), by_blocks(3n, minified()), by_blocks(7n, minified())] == [J.parse(pretty()), J.parse(pretty()), J.parse(pretty()), J.parse(minified()), J.parse(minified())] : List<&2, Result<&2, &2, String, J.J>>} # ---- encode and decode, through NFC and an added token ---- # Guarantees: with the tiny tokenizer, "h", "e" + U+0301 (é decomposed), "" encodes as h, é (merged), the added # token, and decodes to "hé" with é composed. # Why it matters: decisions 3, 4 and 7 end to end: NFC before the split, added tokens matched, decode the inverse. law round_trip: {round(TK.load(tiny(qwen_pattern())), [104, 101, 204, 129, 60, 120, 62]) == [104, 195, 169, 60, 120, 62] : List<&2, U32>}