okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
8.0 KiB133 linesraw
1"""tools/image/gate/te_tok_cases.py - TEST-ONLY (OWN-5 gate harness): the prompt set of the text-encoder tokenizer gate.
2
3    python -I -B te_tok_cases.py <out dir> [--gguf <te.gguf>]
4
5Writes <out dir>/<name>.txt (the prompt's exact bytes, as the server's write_prompt hands them to sd-cli) and
6<out dir>/cases.json [{"name", "prompt_b64"}].  With --gguf the five token literals that the GGUF lists at the ids
7where stable-diffusion.cpp's own special-token list differs are added as cases too.  The expected ids come from
8sd.cpp itself (stage_hooks.py OWN5_EXIT_AFTER_TOKENS, te_tok_collect.py); this file only chooses the inputs.
9
10Sets: the 8 gate prompts; the two long prompts (about 1,000 and 4,000 tokens); every special literal sd.cpp knows, in
11text; the prompt-weight syntax (A1111 forms, escapes, BREAK, broken weights, a LoRA tag); unicode (CJK, kana, hangul,
12emoji with joiners / flags / skin tones, combining marks, right-to-left scripts, other digits and spaces, case-fold
13traps); empty and whitespace-only prompts; very long words and runs; invalid UTF-8; 300 random prompts from a fixed
14seed over a mixed character pool."""
15from __future__ import annotations
16
17import base64
18import json
19import random
20import sys
21from pathlib import Path
22
23sys.path.insert(0, str(Path(__file__).resolve().parent))
24from run_set import PROMPTS  # noqa: E402
25
26SPECIALS = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>",
27            "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>",
28            "<|image_pad|>", "<|video_pad|>", "<tool_call>", "</tool_call>", "<|fim_prefix|>", "<|fim_middle|>",
29            "<|fim_suffix|>", "<|fim_pad|>", "<|repo_name|>", "<|file_sep|>", "<tool_response>", "</tool_response>",
30            "<think>", "</think>", "<|boi_token|>", "<|bor_token|>", "<|eor_token|>", "<|bot_token|>", "<|tms_token|>"]
31
32
33def long_prompt(want_tokens: int, chars_per_token: float = 3.2) -> str:
34    """The same text family as the step-3 long prompts (te_tok_dump.py), cut by length instead of by a tokenizer."""
35    parts, i = [], 0
36    while sum(len(p) for p in parts) < want_tokens * chars_per_token:
37        parts.append(f"Scene {i + 1}: {PROMPTS[i % len(PROMPTS)]}; frame {i * 37 % 1000}, ratio {i % 7}.{i % 10}\n")
38        i += 1
39    return "".join(parts)
40
41
42def cases(gguf_literals: list[str]) -> list[tuple[str, bytes]]:
43    out: list[tuple[str, bytes]] = []
44
45    def add(name: str, text: str | bytes) -> None:
46        out.append((name, text if isinstance(text, bytes) else text.encode("utf-8")))
47
48    for i, p in enumerate(PROMPTS):
49        add(f"gate_{i}", p)
50    add("long_1000", long_prompt(1000))
51    add("long_4000", long_prompt(4000))
52    for i, s in enumerate(SPECIALS):
53        add(f"special_{i:02d}", f"a photo of {s} a cat{s}")
54    add("special_all", "".join(SPECIALS))
55    add("special_partial", "<|im_start <im_end|> <|im_end <|vision_start|x <think >")
56    for i, s in enumerate(gguf_literals):
57        add(f"gguf_literal_{i}", f"text {s} more{s}")
58    weights = {
59        "w_plain": "normal text", "w_paren": "an (important) word", "w_unbalanced": "(unbalanced",
60        "w_escape_doc": "\\(literal\\]", "w_parens2": "(unnecessary)(parens)",
61        "w_doc_long": "a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).",
62        "w_number": "(cat:1.5) and (dog:0.25) [[bird]]", "w_bad_number": "(cat:1.2.3) (dog:.) (fox:+.) (owl:abc)",
63        "w_signed": "(cat:-0.5) (dog:+2)", "w_colon": "time: 12:30, ratio 3:4", "w_escapes": "\\( \\) \\[ \\] \\\\ \\x \\",
64        "w_break": "a cat BREAK a dog", "w_break2": "BREAK", "w_breakfast": "BREAKFAST at Tiffany's B BB aB",
65        "w_lora": "<lora:foo:0.8> a cat <lora:bar:x>", "w_nested": "((a [b (c:2) d] e))", "w_close_only": "a) b] c",
66        "w_huge": "(a:1e30) (b:1e-30) (c:100000)", "w_weight_space": "(cat: 1.5) (dog :1.5)",
67    }
68    for k, v in weights.items():
69        add(k, v)
70    uni = {
71        "u_cjk": "一只猫坐在窗台上,阳光明媚。东京的夜晚", "u_kana": "ねこがすきです。カタカナとひらがな",
72        "u_hangul": "고양이가 창가에 앉아 있다", "u_emoji": "a cat 🐱 and a dog 🐶 👍🏽 👨\u200d👩\u200d👧\u200d👦 🇯🇵 🏳️\u200d🌈 ❤️",
73        "u_combining": "café cafe\u0301 Z\u0335\u0321a\u0334\u0328l\u0337g\u0336o\u0338 n\u0303",
74        "u_arabic": "قطة تجلس على النافذة ١٢٣ ٤٥", "u_hebrew": "חתול יושב על החלון 2024",
75        "u_mixed_rtl": "the word \u202ereversed\u202c and שלום with مرحبا in English",
76        "u_devanagari": "बिल्ली खिड़की पर बैठी है", "u_thai": "แมวนั่งอยู่บนหน้าต่าง",
77        "u_cyrillic_greek": "Кошка сидит на окне. Η γάτα κάθεται",
78        "u_digits": "0123 ²³ ½ ⅓ Ⅻ ⑳ ٣ ৫ 𝟙𝟚", "u_spaces": "a\u00a0b\u3000c\u2028d\u0085e\u200bf\ufeffg\u2009h\u202fi",
79        "u_casefold": "IT'S it'\u017f IT'S DON'T I'LL WE'VE YOU'RE I'M I'D 'K '\u212a \u0130stanbul ß fi",
80        "u_controls": "a\x01b\x07c\x1fd\x7fe", "u_tabs_newlines": "a\tb\r\nc\rd\n\ne \n f",
81        "u_math": "∑∫√∞ ≠ ≤ ≥ ∀x∈ℝ", "u_symbols": "©®™ § ¶ † ‡ • … ‰ €£¥",
82        "u_astral": "𝔘𝔫𝔦𝔠𝔬𝔡𝔢 𓀀𓀁 𐍈 🀄", "u_softhyphen": "co\u00adoperate",
83    }
84    for k, v in uni.items():
85        add(k, v)
86    for k, v in {"e_empty": "", "e_space": " ", "e_spaces": "     ", "e_newline": "\n", "e_tabs": "\t\t",
87                 "e_crlf": "\r\n\r\n", "e_mixed_ws": " \n \t ", "e_nbsp": "\u00a0", "e_ideo_space": "\u3000"}.items():
88        add(k, v)
89    add("l_word_5000", "a" * 5000)
90    add("l_mixed_word", "".join(random.Random(7).choice("abcdefghijklmnopqrstuvwxyz") for _ in range(3000)))
91    add("l_digits", "1234567890" * 100)
92    add("l_bang", "!" * 1000)
93    add("l_spaces_then_word", " " * 500 + "word")
94    add("l_cjk_run", "猫" * 2000)
95    add("l_pneumono", "pneumonoultramicroscopicsilicovolcanoconiosis " * 20)
96    for k, v in {"x_ff": b"a\xffb", "x_truncated": b"cat \xe4\xb8", "x_overlong": b"a\xc0\xafb",
97                 "x_surrogate": b"a\xed\xa0\x80b", "x_above_max": b"a\xf4\x90\x80\x80b"}.items():
98        add(k, v)
99    pool = (list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") * 6 + list("0123456789") * 3 +
100            list(" " * 20) + list(".,;:!?'\"-_/()[]{}<>|\\@#$%^&*+=~`") + ["\n", "\r", "\t", "\r\n"] +
101            list("猫犬東京日本語中文한국어ひらがなカタカナ") + ["🐱", "👍🏽", "👨\u200d👩\u200d👧", "🇯🇵", "❤️", "\u0301", "\u0308", "\u0335"] +
102            list("قطةשלוםКошкаγάτα") + ["\u00a0", "\u3000", "\u2028", "\u200b", "\u017f", "\u212a", "\u0130", "ß", "fi", "²", "½", "٣", "0"] +
103            ["BREAK", "(", ")", "(x:1.3)", "[", "]", ":0.5)", "\\(", "<|im_", "|>", "<|im_start|>", "<|im_end|>", "<think>",
104             "'s", "'S", "'ll", "'re"])
105    rng = random.Random(20261111)
106    for i in range(300):
107        n = rng.choice([1, 2, 3, 5, 8, 13, 21, 40, 80, 150, 300])
108        add(f"r_{i:03d}", "".join(rng.choice(pool) for _ in range(n)))
109    return out
110
111
112def main(argv=None) -> int:
113    a = sys.argv[1:] if argv is None else argv
114    outd = Path(a[0])
115    lits: list[str] = []
116    if "--gguf" in a:
117        sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
118        from gguf_reader import GGUFFile
119        toks = GGUFFile(Path(a[a.index("--gguf") + 1])).metadata["tokenizer.ggml.tokens"]
120        base = 151643
121        lits = [toks[base + i] for i, s in enumerate(SPECIALS) if len(toks) > base + i and toks[base + i] != s]
122    outd.mkdir(parents=True, exist_ok=True)
123    man = []
124    for name, data in cases(lits):
125        (outd / f"{name}.txt").write_bytes(data)
126        man.append({"name": name, "prompt_b64": base64.b64encode(data).decode()})
127    (outd / "cases.json").write_text(json.dumps(man, ensure_ascii=True))
128    print(f"{len(man)} cases; gguf literals at sd.cpp's differing special ids: {lits}")
129    return 0
130
131
132if __name__ == "__main__":
133    sys.exit(main())