okami.mom/strata

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

Niko1221Merge f-ci-green-0215: the four red GitHub checks (cmake-cpu on MSVC, py-tools on a CRLF checkout and on macOS, the Windows snapshot time)b749503db

main
4.3 KiB90 linesraw
1"""tools/test_te_tokenizer.py - our Qwen-Image text-encoder tokenizer (src/image/te/qwen2_tok.cpp) against the token ids
2stable-diffusion.cpp 2988060 built for the same prompts.
3
4The expected ids were recorded from sd.cpp itself (tools/image/gate/te_tok_collect.py: a stage-hook build of sd-cli that
5dumps the ids LLMEmbedder::encode_prompt hands its text encoder) for every case of tools/image/gate/te_tok_cases.py and
6stored in tools/image/gate/data/te_tok_expected.json.  The test needs no GPU, no sd.cpp and no model file: it compiles
7the tokenizer with the system C++ compiler and gives it only the merges those cases use
8(tools/image/gate/data/te_tok_merges.txt, with their ranks in the full 151,387-merge list).
9
10    python -m pytest tools/test_te_tokenizer.py"""
11import base64
12import json
13import shutil
14import struct
15import subprocess
16import tempfile
17import unittest
18from pathlib import Path
19
20ROOT = Path(__file__).resolve().parents[1]
21DATA = ROOT / "tools" / "image" / "gate" / "data"
22CXX = shutil.which("g++") or shutil.which("c++") or shutil.which("clang++")
23
24
25@unittest.skipUnless(CXX, "no C++ compiler")
26class TokenizerMatchesSdcpp(unittest.TestCase):
27    @classmethod
28    def setUpClass(cls):
29        cls.tmp = tempfile.TemporaryDirectory()
30        d = Path(cls.tmp.name)
31        cls.exe = d / "strata-te-tokens"
32        r = subprocess.run([CXX, "-std=c++17", "-O2", "-I", str(ROOT / "include"), "-I", str(ROOT / "src" / "image" / "te"),
33                            str(ROOT / "src" / "image" / "te" / "qwen2_tok.cpp"),
34                            str(ROOT / "src" / "image" / "te" / "qwen2_tok_main.cpp"), "-o", str(cls.exe)],
35                           capture_output=True, text=True, timeout=600)
36        if r.returncode != 0:
37            raise AssertionError("build failed:\n" + r.stderr[-4000:])
38        cls.cases = json.loads((DATA / "te_tok_expected.json").read_text())
39        lines = [f"{c['name']} {base64.b64decode(c['prompt_b64']).hex()}" for c in cls.cases]
40        (d / "cases.txt").write_text("\n".join(lines) + "\n", newline="\n")      # read byte for byte: no CR on Windows
41        r = subprocess.run([str(cls.exe), "run", str(DATA / "te_tok_merges.txt"), str(d / "cases.txt"), str(d / "out.txt")],
42                           capture_output=True, text=True, timeout=600)
43        if r.returncode != 0:
44            raise AssertionError("run failed:\n" + r.stderr[-4000:])
45        cls.got = {}
46        for line in (d / "out.txt").read_text().splitlines():
47            parts = line.split(" ", 2)
48            cls.got[parts[0]] = parts[1:]
49
50    @classmethod
51    def tearDownClass(cls):
52        cls.tmp.cleanup()
53
54    def test_case_set_is_wide(self):
55        names = [c["name"] for c in self.cases]
56        self.assertGreaterEqual(len(names), 380)
57        for prefix in ("gate_", "long_", "special_", "gguf_literal_", "w_", "u_", "e_", "l_", "x_", "r_"):
58            self.assertTrue(any(n.startswith(prefix) for n in names), prefix)
59
60    def test_every_case_matches(self):
61        bad = []
62        for c in self.cases:
63            g = self.got.get(c["name"])
64            if g is None:
65                bad.append((c["name"], "no output"))
66                continue
67            if "error" in c:
68                if g[0] != "error":
69                    bad.append((c["name"], "sd.cpp refused the prompt, we did not"))
70                continue
71            if g[0] != "ok":
72                bad.append((c["name"], f"we refused: {g[1]}"))
73                continue
74            n_sys, ids, w = g[1].split(" ")
75            ids = [int(x) for x in ids.split(",")] if ids else []
76            want_w = [struct.unpack("<I", struct.pack("<f", x))[0] for x in c["weights"]]
77            got_w = [int(x, 16) for x in w.split(",")] if w else []
78            if int(n_sys) != c["n_system"]:
79                bad.append((c["name"], f"n_system {n_sys} vs {c['n_system']}"))
80            elif ids != c["ids"]:
81                k = next((i for i, (a, b) in enumerate(zip(ids, c["ids"])) if a != b), min(len(ids), len(c["ids"])))
82                bad.append((c["name"], f"ids differ at {k}: ours {ids[k:k + 5]} sd.cpp {c['ids'][k:k + 5]} "
83                                       f"({len(ids)} vs {len(c['ids'])} ids)"))
84            elif got_w != want_w:
85                bad.append((c["name"], "weights differ"))
86        self.assertEqual(bad, [], f"{len(bad)} of {len(self.cases)} cases differ")
87
88
89if __name__ == "__main__":
90    unittest.main()