tok.bend source
tok.bend on the hub · documented module
# bend-bpe-tokenizer: byte-level BPE tokenizers from a Hugging Face tokenizer.json, giving the ids Hugging Face's# `tokenizers` gives (encode(text, add_special_tokens=False)), and the text back from ids.# import bend-bpe-tokenizer@<version>/tok.bend as TK## Tok.open(path) reads a tokenizer.json of a known family, or says why it can't:# Qwen2/Qwen3, Qwen3.5 and later (words take combining marks), Llama 3, and GPT-2 style (GPT-2, RoBERTa, BART...):# byte-level BPE, normalizer NFC or none, added tokens without lstrip, rstrip or single_word.# encode(tok, bytes) takes UTF-8 text and answers its ids, or the offset of the first ill-formed UTF-8 sequence:# added tokens are found in the raw text (longest first), the rest is normalized (NFC, if the file says so), split# by the family's regex, and each piece's bytes merged by BPE. Unicode is as Hugging Face's tokenizers sees it# (tables.bend, generated from it): Unicode 16.0 for the split, its NFC's own (older) data for normalization.# decoder(tok) and decode(dec, ids) give the UTF-8 bytes of ids (an added token's own text for its id).import Baseimport ./tree.bend as Timport ./tables.bend as TBimport ./utf8.bend as Uimport ./nfc.bend as Nimport ./split.bend as Simport ./bpe.bend as Bimport ./specials.bend as Aimport ./json.bend as Jimport ./hmap.bend as Htype Tok is Data: Tok{fam: U32, nfc: Bool, ignore: Bool, vocab: H.HM, ranks: H.HM, added: List<&2, A.AT>, ct: T.RT, nt: N.NT}type Err is Data: BadUtf8{at: U32} NoToken{token: List<&2, U32>}# ---- loading: what the file must say, and the tables built from it ----def str_is2(j: J.J, +s: String) -> Bool: match j: case J.JStr{cs}: J.key_is(cs, s) case J.JNull{}: False{} case J.JBool{b}: False{} case J.JNum{n, i}: False{} case J.JArr{xs}: False{} case J.JObj{kvs}: False{}def str_is(v: Maybe<&2, J.J>, +s: String) -> Bool: match v: case Some{j}: str_is2(j, s) case None{}: False{}# null, absent, or an empty stringdef is_blank2(j: J.J) -> Bool: match j: case J.JNull{}: True{} case J.JStr{cs}: A.is_prefix(cs, []) case J.JBool{b}: False{} case J.JNum{n, i}: False{} case J.JArr{xs}: False{} case J.JObj{kvs}: False{}def is_blank(v: Maybe<&2, J.J>) -> Bool: match v: case None{}: True{} case Some{j}: is_blank2(j)def bool_of2(j: J.J, d: Bool) -> Bool: match j: case J.JBool{b}: b case J.JNull{}: d case J.JStr{cs}: d case J.JNum{n, i}: d case J.JArr{xs}: d case J.JObj{kvs}: ddef bool_of(v: Maybe<&2, J.J>, d: Bool) -> Bool: match v: case Some{j}: bool_of2(j, d) case None{}: ddef fieldm(m: Maybe<&2, J.J>, +name: String) -> Maybe<&2, J.J>: match m: case None{}: None{} case Some{j}: J.field(j, name)def items2(j: J.J) -> List<&2, J.J>: match j: case J.JArr{xs}: xs case J.JNull{}: [] case J.JBool{b}: [] case J.JNum{n, i}: [] case J.JStr{cs}: [] case J.JObj{kvs}: []def items(v: Maybe<&2, J.J>) -> List<&2, J.J>: match v: case Some{j}: items2(j) case None{}: []def kvs_of2(j: J.J) -> List<&2, J.KV>: match j: case J.JObj{kvs}: kvs case J.JNull{}: [] case J.JBool{b}: [] case J.JNum{n, i}: [] case J.JStr{cs}: [] case J.JArr{xs}: []def kvs_of(v: Maybe<&2, J.J>) -> List<&2, J.KV>: match v: case Some{j}: kvs_of2(j) case None{}: []def str_of(j: J.J) -> List<&2, U32>: match j: case J.JStr{cs}: cs case J.JNull{}: [] case J.JBool{b}: [] case J.JNum{n, i}: [] case J.JArr{xs}: [] case J.JObj{kvs}: []def num_of2(j: J.J) -> U32: match j: case J.JNum{n, i}: n case J.JNull{}: 0 case J.JBool{b}: 0 case J.JStr{cs}: 0 case J.JArr{xs}: 0 case J.JObj{kvs}: 0def num_of(v: Maybe<&2, J.J>) -> U32: match v: case Some{j}: num_of2(j) case None{}: 0# the family of the pre-tokenizer, 4 for none knowndef regex_family(+v: Maybe<&2, J.J>) -> U32: Bool.pick(U32, str_is(v, "(?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+"), 0, Bool.pick(U32, str_is(v, "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"), 1, Bool.pick(U32, str_is(v, "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"), 2, 4)))# a ByteLevel step that only maps bytes (no prefix space; with use_regex it is GPT-2's split)def byte_level(+j: J.J, +regex: Bool) -> Bool: Bool.and(str_is(J.field(j, "type"), "ByteLevel"), Bool.and(Bool.not(bool_of(J.field(j, "add_prefix_space"), True{})), Bool.not(Bool.xor(bool_of(J.field(j, "use_regex"), True{}), regex))))def split_ok(+j: J.J) -> Bool: Bool.and(str_is(J.field(j, "type"), "Split"), Bool.and(str_is(J.field(j, "behavior"), "Isolated"), Bool.not(bool_of(J.field(j, "invert"), True{}))))def is_nil_j(xs: List<&2, J.J>) -> Bool: match xs: case []: True{} case x <> t: False{}def seq_family2(t: List<&2, J.J>, +s1: J.J) -> U32: match t: case []: Bool.pick(U32, byte_level(s1, True{}), 3, 4) case +s2 <> t2: Bool.pick(U32, Bool.and(A.is_prefix([], []), Bool.and(Bool.and(split_ok(s1), byte_level(s2, False{})), is_nil_j(t2))), regex_family(fieldm(J.field(s1, "pattern"), "Regex")), 4)def seq_family(steps: List<&2, J.J>) -> U32: match steps: case []: 4 case +s1 <> t: seq_family2(t, s1)def family(+pre: Maybe<&2, J.J>) -> U32: Bool.pick(U32, str_is(fieldm(pre, "type"), "Sequence"), seq_family(items(fieldm(pre, "pretokenizers"))), seq_family([Maybe.default(&2, J.J, pre, J.JNull{})]))# the vocabulary: token -> id + 1# the vocabulary's entries, halves built at the same time, depth times overdef vocab_go(kvs: List<&2, J.KV>) -> List<&2, H.HE>: match kvs: case []: [] case J.KV{k, v} <> t: H.entry(B.key(k), (num_of2(v) + 1 : U32)) <> vocab_go(t)def vocab_par(depth: Nat, +n: Nat, +kvs: List<&2, J.KV>) -> H.ETr: match depth: case 0n: H.TLeaf{vocab_go(List.take(&2, J.KV, kvs, n))} case 1n+ +d: a b = vocab_par(d, J.half(n), kvs) vocab_par(d, Nat.sub(n, J.half(n)), List.drop(&2, J.KV, kvs, J.half(n))) H.TNode{a, b}# the merges: "a b" -> rank + 1; a merge is "a b" or, in newer files, ["a", "b"]def first_str(xs: List<&2, J.J>) -> List<&2, U32>: match xs: case []: [] case b <> t: str_of(b)def char_bytes(cs: List<&2, U32>) -> List<&2, U32>: match cs: case []: [] case c <> t: B.char_byte(c) <> char_bytes(t)def merge_key2(xs: List<&2, J.J>) -> List<&2, U32>: match xs: case []: [] case a <> t: List.append(&2, U32, str_of(a), 32 <> first_str(t))def merge_key(j: J.J) -> List<&2, U32>: match j: case J.JStr{cs}: cs case J.JArr{xs}: merge_key2(xs) case J.JNull{}: [] case J.JBool{b}: [] case J.JNum{n, i}: [] case J.JObj{kvs}: []# the merges' entries (rank r first), halves built at the same time, depth times overdef ranks_go(ms: List<&2, J.J>, +r: U32) -> List<&2, H.HE>: match ms: case []: [] case x <> t: H.entry(B.key(merge_key(x)), (r + 1 : U32)) <> ranks_go(t, (r + 1 : U32))def ranks_par(depth: Nat, +n: Nat, +r: U32, +ms: List<&2, J.J>) -> H.ETr: match depth: case 0n: H.TLeaf{ranks_go(List.take(&2, J.J, ms, n), r)} case 1n+ +d: a b = ranks_par(d, J.half(n), r, ms) ranks_par(d, Nat.sub(n, J.half(n)), (r + U32.from_nat(J.half(n)) : U32), List.drop(&2, J.J, ms, J.half(n))) H.TNode{a, b}# an added token, if it has no option this tokenizer can't honourdef added_ok(+a: J.J, +nfc: Bool) -> Bool: Bool.not(Bool.or(Bool.or(bool_of(J.field(a, "lstrip"), False{}), bool_of(J.field(a, "rstrip"), False{})), Bool.or(bool_of(J.field(a, "single_word"), False{}), Bool.and(nfc, bool_of(J.field(a, "normalized"), False{})))))def added_all(as: List<&2, J.J>, +nfc: Bool) -> Bool: match as: case []: True{} case +a <> t: Bool.and(added_ok(a, nfc), added_all(t, nfc))def added_go(as: List<&2, J.J>) -> List<&2, A.AT>: match as: case []: [] case +a <> t: A.AT{str_of(Maybe.default(&2, J.J, J.field(a, "content"), J.JNull{})), num_of(J.field(a, "id"))} <> added_go(t)def why_not(+root: J.J, +fam: U32, +nfc_ok: Bool) -> Maybe<&2, String>: Bool.pick(Maybe<&2, String>, Bool.not(str_is(fieldm(J.field(root, "model"), "type"), "BPE")), Some{"the model is not BPE"}, Bool.pick(Maybe<&2, String>, Bool.not(nfc_ok), Some{"the normalizer is not NFC or none"}, Bool.pick(Maybe<&2, String>, U32.is_eq(fam, 4), Some{"the pre-tokenizer is not a known byte-level family's (Qwen2/3, Qwen3.5+, Llama 3, GPT-2)"}, Bool.pick(Maybe<&2, String>, Bool.not(str_is(fieldm(J.field(root, "decoder"), "type"), "ByteLevel")), Some{"the decoder is not ByteLevel"}, Bool.pick(Maybe<&2, String>, Bool.not(Bool.and(Bool.and(is_blank(fieldm(J.field(root, "model"), "dropout")), is_blank(fieldm(J.field(root, "model"), "unk_token"))), Bool.and(Bool.and(is_blank(fieldm(J.field(root, "model"), "continuing_subword_prefix")), is_blank(fieldm(J.field(root, "model"), "end_of_word_suffix"))), Bool.not(Bool.or(bool_of(fieldm(J.field(root, "model"), "byte_fallback"), False{}), bool_of(fieldm(J.field(root, "model"), "fuse_unk"), False{})))))), Some{"the BPE model uses dropout, an unknown token, subword affixes or byte fallback"}, Bool.pick(Maybe<&2, String>, Bool.not(added_all(items(J.field(root, "added_tokens")), str_is(fieldm(J.field(root, "normalizer"), "type"), "NFC"))), Some{"an added token uses lstrip, rstrip, single_word, or normalization"}, None{}))))))# the two maps, built at the same timedef build_maps(+fam: U32, +root: J.J, +kvs: List<&2, J.KV>, +ms: List<&2, J.J>) -> Tok: v r = H.build(H.flat(vocab_par(6n, List.length(&2, J.KV, kvs), kvs))) H.build(H.flat(ranks_par(6n, List.length(&2, J.J, ms), 0, ms))) Tok{fam, str_is(fieldm(J.field(root, "normalizer"), "type"), "NFC"), bool_of(fieldm(J.field(root, "model"), "ignore_merges"), False{}), v, r, added_go(items(J.field(root, "added_tokens"))), TB.classes(), N.NT{TB.combining(), TB.decompositions(), TB.compositions()}}def build(why: Maybe<&2, String>, +root: J.J, +fam: U32) -> Result<&2, &2, String, Tok>: match why: case Some{w}: Fail{w} case None{}: Done{build_maps(fam, root, kvs_of(fieldm(J.field(root, "model"), "vocab")), items(fieldm(J.field(root, "model"), "merges")))}def nfc_ok(+n: Maybe<&2, J.J>) -> Bool: Bool.or(is_blank(n), str_is(fieldm(n, "type"), "NFC"))def load2(+fam: U32, +root: J.J) -> Result<&2, &2, String, Tok>: build(why_not(root, fam, nfc_ok(J.field(root, "normalizer"))), root, fam)def load_json(+root: J.J) -> Result<&2, &2, String, Tok>: load2(family(J.field(root, "pre_tokenizer")), root)def load_parsed(r: Result<&2, &2, String, J.J>) -> Result<&2, &2, String, Tok>: match r: case Done{root}: load_json(root) case Fail{why}: Fail{"not JSON: " ++ why}# a tokenizer from the bytes of its tokenizer.jsondef load(bs: List<&2, U32>) -> Result<&2, &2, String, Tok>: load_parsed(J.parse_par(bs))# ---- encoding ----def classify(+ct: T.RT, cs: List<&2, U32>) -> List<&2, S.CC>: match cs: case []: [] case +c <> t: S.CC{c, T.rt_find(ct, c)} <> classify(ct, t)def piece_cps(xs: List<&2, S.CC>) -> List<&2, U32>: match xs: case []: [] case x <> t: S.cp(x) <> piece_cps(t)def err_tok(r: Result<&2, &2, List<&2, U32>, List<&2, U32>>) -> Result<&2, &2, Err, List<&2, U32>>: match r: case Done{ids}: Done{ids} case Fail{t}: Fail{NoToken{t}}# results joined, the first failure keptdef join2(xs: List<&2, U32>, b: Result<&2, &2, Err, List<&2, U32>>) -> Result<&2, &2, Err, List<&2, U32>>: match b: case Fail{e}: Fail{e} case Done{ys}: Done{List.append(&2, U32, xs, ys)}def join(a: Result<&2, &2, Err, List<&2, U32>>, rest: Unit -> Result<&2, &2, Err, List<&2, U32>>) -> Result<&2, &2, Err, List<&2, U32>>: match a: case Fail{e}: Fail{e} case Done{xs}: join2(xs, rest(Unit{}))def pieces_ids(+ignore: Bool, +ranks: H.HM, +vocab: H.HM, ps: List<&2, List<&2, S.CC>>) -> Result<&2, &2, Err, List<&2, U32>>: match ps: case []: Done{[]} case p <> t: join(err_tok(B.piece_ids(ignore, ranks, vocab, U.encode(piece_cps(p)))), u => pieces_ids(ignore, ranks, vocab, t))def tok_fam(t: Tok) -> U32: match t: case Tok{fam, nfc, ignore, vocab, ranks, added, ct, nt}: famdef maybe_nfc(on: Bool, +nt: N.NT, cs: List<&2, U32>) -> List<&2, U32>: match on: case True{}: N.nfc(nt, cs) case False{}: csdef text_ids(+fam: U32, +nfc: Bool, +ignore: Bool, +vocab: H.HM, +ranks: H.HM, +ct: T.RT, +nt: N.NT, cs: List<&2, U32>) -> Result<&2, &2, Err, List<&2, U32>>: pieces_ids(ignore, ranks, vocab, S.split(fam, classify(ct, maybe_nfc(nfc, nt, cs))))def seg_ids(+fam: U32, +nfc: Bool, +ignore: Bool, +vocab: H.HM, +ranks: H.HM, +ct: T.RT, +nt: N.NT, s: A.Seg) -> Result<&2, &2, Err, List<&2, U32>>: match s: case A.SAdded{id, cs}: Done{[id]} case A.SText{cs}: text_ids(fam, nfc, ignore, vocab, ranks, ct, nt, cs)def segs_ids(+fam: U32, +nfc: Bool, +ignore: Bool, +vocab: H.HM, +ranks: H.HM, +ct: T.RT, +nt: N.NT, ss: List<&2, A.Seg>) -> Result<&2, &2, Err, List<&2, U32>>: match ss: case []: Done{[]} case s <> rest: join(seg_ids(fam, nfc, ignore, vocab, ranks, ct, nt, s), u => segs_ids(fam, nfc, ignore, vocab, ranks, ct, nt, rest))def encode_tok(t: Tok, cs: List<&2, U32>) -> Result<&2, &2, Err, List<&2, U32>>: match t: case Tok{fam, nfc, ignore, vocab, ranks, added, ct, nt}: segs_ids(fam, nfc, ignore, vocab, ranks, ct, nt, A.split_added(added, cs))def encode_cps(t: Tok, r: Result<&2, &2, U32, List<&2, U32>>) -> Result<&2, &2, Err, List<&2, U32>>: match r: case Fail{at}: Fail{BadUtf8{at}} case Done{cs}: encode_tok(t, cs)# the ids of UTF-8 textdef encode(t: Tok, bs: List<&2, U32>) -> Result<&2, &2, Err, List<&2, U32>>: encode_cps(t, U.decode(bs))# ---- decoding ----def str_cps(s: String) -> List<&2, U32>: match s: case SNil{}: [] case SCon{c, r}: Char.to_u32(c) <> str_cps(r)def dec_go(ps: List<&2, Sigma<&2, &2, String, _ => U32>>, m: Map<&2, List<&2, U32>>) -> Map<&2, List<&2, U32>>: match ps: case []: m case (k, v) <> t: dec_go(t, Map.set(&2, List<&2, U32>, m, U32.show((v - 1 : U32)), char_bytes(str_cps(k))))def dec_added(as: List<&2, A.AT>, m: Map<&2, List<&2, U32>>) -> Map<&2, List<&2, U32>>: match as: case []: m case A.AT{cs, id} <> t: dec_added(t, Map.set(&2, List<&2, U32>, m, U32.show(id), U.encode(cs)))# id -> bytes, for decodedef decoder(t: Tok) -> Map<&2, List<&2, U32>>: match t: case Tok{fam, nfc, ignore, vocab, ranks, added, ct, nt}: dec_added(added, dec_go(H.pairs(vocab), Map.new(&2, List<&2, U32>)))def dec_one(r: Map<&2, List<&2, U32>> & List<&2, U32>) -> List<&2, U32>: match r: case (m, bs): bs# the UTF-8 bytes of ids (an unknown id gives nothing)def decode(+d: Map<&2, List<&2, U32>>, ids: List<&2, U32>) -> List<&2, U32>: match ids: case []: [] case i <> t: List.append(&2, U32, dec_one(Map.get(List<&2, U32>, [], d, U32.show(i))), decode(d, t))# encode with a loaded tokenizer, or a refusal at offset 0 when there is none (for LAWS.bend)def encode_with(r: Result<&2, &2, String, Tok>, bs: List<&2, U32>) -> Result<&2, &2, Err, List<&2, U32>>: match r: case Done{+t}: encode(t, bs) case Fail{why}: Fail{BadUtf8{0}}# ---- reading a file ----def got_bytes(r: File & Result<&1, &1, U32 & String, List<&2, U32>>, acc: List<&2, List<&2, U32>>) -> File & List<&2, List<&2, U32>>: match r: case (f, Done{bs}): (f, bs <> acc) case (f, Fail{e}): (f, acc)# blocks of 2^16 bytes from offset at, n of them (last first)def read_more(fa: File & List<&2, List<&2, U32>>, go: File -> List<&2, List<&2, U32>> -> IO(File & List<&2, List<&2, U32>>)) -> IO(File & List<&2, List<&2, U32>>): match fa: case (f, acc): go(f, acc)def read_blocks(n: Nat, f: File, +at: U32, acc: List<&2, List<&2, U32>>) -> IO(File & List<&2, List<&2, U32>>): match n: case 0n: IO.pure(File & List<&2, List<&2, U32>>, (f, acc)) case 1n+m: do IO<File & List<&2, List<&2, U32>>>: r : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_at(f, at, 65536) read_more(got_bytes(r, acc), f2 => a2 => read_blocks(m, f2, (at + 65536 : U32), a2))def size_of(r: File & Result<&1, &1, U32 & String, U32>) -> File & U32: match r: case (f, Done{n}): (f, n) case (f, Fail{e}): (f, 0)def load_read(fb: File & List<&2, List<&2, U32>>) -> IO(Result<&2, &2, String, Tok>): match fb: case (f, +bs): do IO<Result<&2, &2, String, Tok>>: x : Unit <- File.close(f) return load_parsed(J.parse_blocks(List.reverse(&2, List<&2, U32>, bs)))def opened(r: File & U32) -> IO(Result<&2, &2, String, Tok>): match r: case (f, +n): do IO<Result<&2, &2, String, Tok>>: fb : File & List<&2, List<&2, U32>> <- read_blocks(U32.to_nat(((n + 65535 : U32) / 65536 : U32)), f, 0, []) load_read(fb)def open_file(r: Result<&1, &1, U32 & String, File>, +path: String) -> IO(Result<&2, &2, String, Tok>): match r: case Fail{e}: IO.pure(Result<&2, &2, String, Tok>, Fail{"can't open " ++ path}) case Done{f}: do IO<Result<&2, &2, String, Tok>>: s : File & Result<&1, &1, U32 & String, U32> <- File.size(f) opened(size_of(s))# a tokenizer from a tokenizer.json file, read in blocks that are lexed at the same timedef open(+path: String) -> IO(Result<&2, &2, String, Tok>): do IO<Result<&2, &2, String, Tok>>: r : Result<&1, &1, U32 & String, File> <- File.open(path, "r") open_file(r, path)