#!/usr/bin/env python3 """Expected outputs of HuggingFace `tokenizers` for text_test's tokenizer.json parity cases. Prints a C++ block (tokenizer.json fixtures as raw strings, then the decode, pre-tokenizer and encode goldens) to paste into tests/text_test.cpp between the "BEGIN/END generated by mk_tokenizer_goldens.py" markers. Needs only `pip install tokenizers` (0.23.2 produced the current block); no model files. python3 tests/mk_tokenizer_goldens.py > /tmp/goldens.inc """ import json import tokenizers from tokenizers import Tokenizer MS = "▁" def cstr(s): """A C++ string literal for `s` (UTF-8 bytes, non-ASCII and controls escaped).""" out = '"' prev_hex = False for b in s.encode("utf-8"): c = chr(b) if c == '"': out += '\\"'; prev_hex = False elif c == "\\": out += "\\\\"; prev_hex = False elif c == "\n": out += "\\n"; prev_hex = False elif c == "\t": out += "\\t"; prev_hex = False elif 0x20 <= b < 0x7F: if prev_hex and c in "0123456789abcdefABCDEF": out += '" "' out += c; prev_hex = False else: out += "\\x%02x" % b; prev_hex = True return out + '"' def added(entries): return [{"id": i, "content": c, "single_word": False, "lstrip": False, "rstrip": False, "normalized": False, "special": sp} for i, c, sp in entries] def ids_cpp(ids): return "{ " + ", ".join(str(i) for i in ids) + " }" # ---------------------------------------------------------------------------- decoders def bpe_model(vocab, byte_fallback=False, unk=None): return {"type": "BPE", "byte_fallback": byte_fallback, "unk_token": unk, "vocab": {t: i for i, t in enumerate(vocab)}, "merges": []} DEC_VOCAB = ["", "", "", "<0xE2>", "<0x82>", "<0xAC>", MS, MS + MS, MS + "Hello", MS + "world", "Hello", "a" + MS + "b", "x", MS + "x", "!"] def llama_like(): return { "added_tokens": added([(0, "", True), (1, "", True), (2, "", True)]), "normalizer": None, "pre_tokenizer": {"type": "Metaspace", "replacement": MS, "prepend_scheme": "first", "split": False}, "decoder": {"type": "Sequence", "decoders": [ {"type": "Replace", "pattern": {"String": MS}, "content": " "}, {"type": "ByteFallback"}, {"type": "Fuse"}, {"type": "Strip", "content": " ", "start": 1, "stop": 0}]}, "model": bpe_model(DEC_VOCAB, byte_fallback=True, unk=""), } def metaspace_dec(scheme): return { "added_tokens": added([(0, "", True), (1, "", True), (2, "", True)]), "pre_tokenizer": {"type": "Metaspace", "replacement": MS, "prepend_scheme": scheme, "split": True}, "decoder": {"type": "Metaspace", "replacement": MS, "prepend_scheme": scheme, "split": True}, "model": bpe_model(DEC_VOCAB, byte_fallback=True, unk=""), } WP_VOCAB = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "hello", "##world", "!", "a", "'", "s", "do", "n't", ",", "x", "##y", ".", "##s"] def wordpiece_dec(cleanup): return { "added_tokens": added([(0, "[PAD]", True), (1, "[UNK]", True), (2, "[CLS]", True), (3, "[SEP]", True)]), "pre_tokenizer": {"type": "BertPreTokenizer"}, "decoder": {"type": "WordPiece", "prefix": "##", "cleanup": cleanup}, "model": {"type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "##", "max_input_chars_per_word": 100, "vocab": {t: i for i, t in enumerate(WP_VOCAB)}}, } BPED_VOCAB = ["hel", "lo", "wor", "ld", "hi", "x", ""] def bpe_decoder(): return { "pre_tokenizer": {"type": "WhitespaceSplit"}, "decoder": {"type": "BPEDecoder", "suffix": ""}, "model": bpe_model(BPED_VOCAB, unk=""), } BL_VOCAB = ["Ġhello", "Ġworld", "Ċ", "x", "Ã", "©"] def bytelevel_dec(): return { "pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True, "use_regex": True}, "decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True, "use_regex": True}, "model": bpe_model(BL_VOCAB), } DECODERS = [ ("llama_like", llama_like(), [[8, 9], [1, 8, 9], [6, 8], [7, 8], [10, 9, 14], [3, 4, 5, 13], [9, 3, 4, 5], [11, 9], [1, 6, 9]]), ("metaspace_always", metaspace_dec("always"), [[8, 9], [7, 12], [11, 13], [10, 9], [1, 8]]), ("metaspace_first", metaspace_dec("first"), [[8, 9], [7, 12], [11, 13], [10, 9]]), ("metaspace_never", metaspace_dec("never"), [[8, 9], [7, 12], [11, 13], [10, 9]]), ("wordpiece_cleanup", wordpiece_dec(True), [[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [5, 4], [2, 4, 16, 3], [7, 8, 9]]), ("wordpiece_raw", wordpiece_dec(False), [[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [5, 4]]), ("bpe_decoder", bpe_decoder(), [[0, 1, 2, 3], [4], [4, 4], [0, 1, 5]]), ("bytelevel", bytelevel_dec(), [[0, 1, 2], [3, 0], [4, 5]]), ] # ---------------------------------------------------------------------------- pre-tokenizers PRE_TEXT = "hello, world!! a,,b €5 → x́y ‿z 12345 don't ©x_y " \ "٣٤ Ⅻ ½ x²  n m ¿q?" PRETOKS = [ ("Whitespace", {"type": "Whitespace"}), ("WhitespaceSplit", {"type": "WhitespaceSplit"}), ("BertPreTokenizer", {"type": "BertPreTokenizer"}), ("Punctuation_Removed", {"type": "Punctuation", "behavior": "Removed"}), ("Punctuation_Isolated", {"type": "Punctuation", "behavior": "Isolated"}), ("Punctuation_MergedWithPrevious", {"type": "Punctuation", "behavior": "MergedWithPrevious"}), ("Punctuation_MergedWithNext", {"type": "Punctuation", "behavior": "MergedWithNext"}), ("Punctuation_Contiguous", {"type": "Punctuation", "behavior": "Contiguous"}), ("Digits_individual", {"type": "Digits", "individual_digits": True}), ("Digits_runs", {"type": "Digits", "individual_digits": False}), ("Metaspace_split_always", {"type": "Metaspace", "replacement": MS, "prepend_scheme": "always", "split": True}), ("Metaspace_split_never", {"type": "Metaspace", "replacement": MS, "prepend_scheme": "never", "split": True}), ("Metaspace_whole_first", {"type": "Metaspace", "replacement": MS, "prepend_scheme": "first", "split": False}), ("Sequence_Whitespace_Digits", {"type": "Sequence", "pretokenizers": [ {"type": "WhitespaceSplit"}, {"type": "Digits", "individual_digits": True}, {"type": "Punctuation", "behavior": "Isolated"}]}), ] def pretok_case(name, pt): """A WordPiece vocabulary of exactly the pieces HF cuts the text into, so the ids name the pieces one for one and any other cut shows as [UNK] or a different id.""" probe = Tokenizer.from_str(json.dumps({ "pre_tokenizer": pt, "model": {"type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "##", "max_input_chars_per_word": 100, "vocab": {"[UNK]": 0}}})) pieces = [w for w, _ in probe.pre_tokenizer.pre_tokenize_str(PRE_TEXT)] vocab = {"[UNK]": 0} for w in pieces: vocab.setdefault(w, len(vocab)) js = {"pre_tokenizer": pt, "model": {"type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "##", "max_input_chars_per_word": 100, "vocab": vocab}} tok = Tokenizer.from_str(json.dumps(js)) ids = tok.encode(PRE_TEXT, add_special_tokens=False).ids assert 0 not in ids, (name, pieces) return js, pieces, ids # ---------------------------------------------------------------------------- Gemma-shaped def gemma_like(): pieces = ["", "", "", "", "", "", ""] pieces += ["<0x%02X>" % b for b in range(256)] base = list("abcdefghijklmnopqrstuvwxyz") + [MS, "\n", "\t", "H", "T", ".", ",", "!", "?", "é", "'"] pieces += base merges = [("h", "e"), ("l", "l"), ("he", "ll"), ("hell", "o"), (MS, "w"), ("o", "r"), (MS + "w", "or"), ("l", "d"), (MS + "wor", "ld"), (MS, "t"), (MS + "t", "h"), (MS + "th", "e"), (MS, "c"), (MS + "c", "a"), (MS + "ca", "t"), (MS, MS), (MS + MS, MS + MS), ("\n", "\n"), (MS, "the"), ("t", "h"), ("th", "e"), ("i", "n"), ("in", "g"), ("e", "d"), (MS, "a"), (MS, "hello"), ("H", "e"), ("He", "ll"), ("Hell", "o"), ("é", "m"), ("o", "j"), ("oj", "i")] vocab = {p: i for i, p in enumerate(pieces)} for a, b in merges: vocab.setdefault(a + b, len(vocab)) js = { "added_tokens": added([(0, "", True), (1, "", True), (2, "", True), (3, "", True), (4, "", False), (5, "", True), (6, "", True)]), "normalizer": {"type": "Replace", "pattern": {"String": " "}, "content": MS}, "pre_tokenizer": {"type": "Split", "pattern": {"String": " "}, "behavior": "MergedWithPrevious", "invert": False}, "post_processor": {"type": "TemplateProcessing", "single": [{"SpecialToken": {"id": "", "type_id": 0}}, {"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "", "type_id": 0}}], "pair": [{"SpecialToken": {"id": "", "type_id": 0}}, {"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "", "type_id": 0}}, {"Sequence": {"id": "B", "type_id": 1}}, {"SpecialToken": {"id": "", "type_id": 1}}], "special_tokens": {"": {"id": "", "ids": [2], "tokens": [""]}, "": {"id": "", "ids": [1], "tokens": [""]}}}, "decoder": {"type": "Sequence", "decoders": [ {"type": "Replace", "pattern": {"String": MS}, "content": " "}, {"type": "ByteFallback"}, {"type": "Fuse"}]}, "model": {"type": "BPE", "dropout": None, "unk_token": "", "continuing_subword_prefix": None, "end_of_word_suffix": None, "fuse_unk": True, "byte_fallback": True, "ignore_merges": False, "vocab": vocab, "merges": [[a, b] for a, b in merges]}, } return js def metaspace_specials(scheme): """Metaspace BPE with special tokens: "first" prepends only where the text starts.""" vocab = {"": 0, "[INST]": 1, MS: 2, "H": 3, "i": 4, MS + "H": 5, "Hi": 6, MS + "Hi": 7, "": 8} return {"added_tokens": added([(0, "", True), (1, "[INST]", True)]), "pre_tokenizer": {"type": "Metaspace", "replacement": MS, "prepend_scheme": scheme, "split": False}, "model": {"type": "BPE", "dropout": None, "unk_token": "", "continuing_subword_prefix": None, "end_of_word_suffix": None, "fuse_unk": False, "byte_fallback": False, "ignore_merges": False, "vocab": vocab, "merges": [[MS, "H"], ["H", "i"], [MS + "H", "i"]]}} # ---------------------------------------------------------------------------- CLIP-shaped CLIP_SPLIT = r"""'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""" def gpt2_alphabet(): """GPT-2's byte -> character map, in CLIP's vocabulary order.""" bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\xa1"), ord("\xac") + 1)) + \ list(range(ord("\xae"), ord("\xff") + 1)) cs = bs[:] n = 0 for b in range(256): if b not in bs: bs.append(b) cs.append(256 + n) n += 1 return [chr(c) for c in cs] CLIP_TRAIN = ("a photo of a cat, a painting of a dog, best quality, masterpiece, 1girl, solo, " "looking at viewer, it's a photograph of the mountains at sunset, don't stop, " "highly detailed digital art, portrait of an astronaut riding a horse, ") * 3 def clip_like(): """CLIP ViT-L/14's tokenizer.json with its vocabulary cut down: the real normaliser, Split, ByteLevel, RobertaProcessing and decoder, the 512 byte tokens with and without the "" end-of-word suffix in CLIP's order, and merges trained here (most frequent pair, then the smallest) over a few prompts, each merged token's id 512 + its rank as in CLIP's own file.""" from tokenizers import normalizers, pre_tokenizers, Regex norm = normalizers.Sequence([normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), normalizers.Lowercase()]) pre = pre_tokenizers.Sequence([ pre_tokenizers.Split(Regex(CLIP_SPLIT), behavior="removed", invert=True), pre_tokenizers.ByteLevel(add_prefix_space=False)]) alpha = gpt2_alphabet() vocab = alpha + [c + "" for c in alpha] words = {} for w, _ in pre.pre_tokenize_str(norm.normalize_str(CLIP_TRAIN)): sym = tuple(list(w[:-1]) + [w[-1] + ""]) words[sym] = words.get(sym, 0) + 1 merges = [] for _ in range(160): pairs = {} for sym, n in words.items(): for a, b in zip(sym, sym[1:]): pairs[(a, b)] = pairs.get((a, b), 0) + n if not pairs: break best = min(pairs, key=lambda k: (-pairs[k], k)) merges.append(best) vocab.append(best[0] + best[1]) nw = {} for sym, n in words.items(): out, i = [], 0 while i < len(sym): if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best: out.append(sym[i] + sym[i + 1]) i += 2 else: out.append(sym[i]) i += 1 nw[tuple(out)] = nw.get(tuple(out), 0) + n words = nw bos, eos = len(vocab), len(vocab) + 1 vocab += ["<|startoftext|>", "<|endoftext|>"] return { "added_tokens": [ {"id": bos, "content": "<|startoftext|>", "single_word": False, "lstrip": False, "rstrip": False, "normalized": True, "special": True}, {"id": eos, "content": "<|endoftext|>", "single_word": False, "lstrip": False, "rstrip": False, "normalized": False, "special": True}], "normalizer": {"type": "Sequence", "normalizers": [ {"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": r"\s+"}, "content": " "}, {"type": "Lowercase"}]}, "pre_tokenizer": {"type": "Sequence", "pretokenizers": [ {"type": "Split", "pattern": {"Regex": CLIP_SPLIT}, "behavior": "Removed", "invert": True}, {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True}]}, "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", eos], "cls": ["<|startoftext|>", bos], "trim_offsets": False, "add_prefix_space": False}, "decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True}, "model": {"type": "BPE", "dropout": None, "unk_token": "<|endoftext|>", "continuing_subword_prefix": "", "end_of_word_suffix": "", "fuse_unk": False, "vocab": {t: i for i, t in enumerate(vocab)}, "merges": [a + " " + b for a, b in merges]}, } CLIP_TEXTS = ["a photo of a cat", "1girl, solo, masterpiece, best quality, (absurdres:1.2), " "looking_at_viewer, hatsune_miku", "A Photograph of the Mountains, it's DON'T stop", "1024x1024 2.5 v1.0", "Café naïve 東京タワー 서울 🍣👩‍👩‍👧 İstanbul ΣΊΣΥΦΟΣ", " many spaces\t\ttabs\n\nnewlines ", "...!!!??? ((()))[[]]", "", "a", "<|startoftext|>a cat<|endoftext|>", "x<|StartOfText|>y", "ab catcat", "photographphotograph", "it'sit's'll"] SPECIAL_TEXTS = ["Hi", "[INST]Hi", "[INST] Hi", "Hi[INST]Hi", "Hi", "Hi Hi[INST]Hi"] GEMMA_TEXTS = ["hello", " hello", "hello world", "hello world", "the cat", "\nthe\n\ncat", " leading", "trailing ", "a\tb", "émoji \U0001F600", "xy", "user\nhello", "Hello, world!", " ", "th the thee", "日本", "zz zz zz", " the", "hello", ""] def main(): print("/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers %s) */" % tokenizers.__version__) print() print("struct DecodeGolden { const char* fixture; std::vector ids; const char* text; };") print("struct PretokGolden { const char* name; const char* json; std::vector ids; };") print("struct EncodeGolden { const char* text; std::vector ids; " "std::vector with_special; };") print() print("const std::vector>& decode_fixtures() {") print(" static const std::vector> v = {") for name, js, _ in DECODERS: print(" { %s, R\"JSON(%s)JSON\" }," % (cstr(name), json.dumps(js, ensure_ascii=False))) print(" };") print(" return v;") print("}") print() print("const std::vector& decode_goldens() {") print(" static const std::vector v = {") for name, js, cases in DECODERS: tok = Tokenizer.from_str(json.dumps(js)) for ids in cases: print(" { %s, %s, %s }," % (cstr(name), ids_cpp(ids), cstr(tok.decode(ids, skip_special_tokens=True)))) print(" };") print(" return v;") print("}") print() print("const char* const kPretokText = %s;" % cstr(PRE_TEXT)) print() print("const std::vector& pretok_goldens() {") print(" static const std::vector v = {") for name, pt in PRETOKS: js, pieces, ids = pretok_case(name, pt) print(" /* %s */" % " | ".join(p.replace("*/", "* /") for p in pieces) .encode("ascii", "backslashreplace").decode()) print(" { %s, R\"JSON(%s)JSON\", %s }," % (cstr(name), json.dumps(js, ensure_ascii=False), ids_cpp(ids))) print(" };") print(" return v;") print("}") print() g = gemma_like() tok = Tokenizer.from_str(json.dumps(g)) print("const char* const kGemmaLike = R\"JSON(%s)JSON\";" % json.dumps(g, ensure_ascii=False)) print() print("const std::vector& gemma_goldens() {") print(" static const std::vector v = {") for t in GEMMA_TEXTS: a = tok.encode(t, add_special_tokens=False).ids b = tok.encode(t, add_special_tokens=True).ids print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b))) print(" };") print(" return v;") print("}") print() print("/* The decode of every Gemma golden with special tokens skipped, as HF reports it. */") print("const std::vector& gemma_decoded() {") print(" static const std::vector v = {") for t in GEMMA_TEXTS: print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids, skip_special_tokens=True))) print(" };") print(" return v;") print("}") print() print("const std::vector>& metaspace_special_fixtures() {") print(" static const std::vector> v = {") for scheme in ["first", "always"]: print(" { %s, R\"JSON(%s)JSON\" }," % (cstr(scheme), json.dumps(metaspace_specials(scheme), ensure_ascii=False))) print(" };") print(" return v;") print("}") print() print("const std::vector>& metaspace_special_goldens() {") print(" static const std::vector> v = {") for scheme in ["first", "always"]: tok = Tokenizer.from_str(json.dumps(metaspace_specials(scheme))) for text in SPECIAL_TEXTS: ids = tok.encode(text, add_special_tokens=False).ids print(" { %s, { %s, %s, {} } }," % (cstr(scheme), cstr(text), ids_cpp(ids))) print(" };") print(" return v;") print("}") print() c = clip_like() tok = Tokenizer.from_str(json.dumps(c)) print("const char* const kClipLike = R\"JSON(%s)JSON\";" % json.dumps(c, ensure_ascii=False)) print() print("const std::vector& clip_goldens() {") print(" static const std::vector v = {") for t in CLIP_TEXTS: a = tok.encode(t, add_special_tokens=False).ids b = tok.encode(t, add_special_tokens=True).ids print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b))) print(" };") print(" return v;") print("}") print() print("/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */") print("const std::vector& clip_decoded() {") print(" static const std::vector v = {") for t in CLIP_TEXTS: print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids, skip_special_tokens=True))) print(" };") print(" return v;") print("}") print() print("/* END generated by mk_tokenizer_goldens.py */") if __name__ == "__main__": main()