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
5.1 KiB108 linesraw
1"""tools/test_dit_rope.py - our Qwen-Image-2.1 RoPE table (src/image/dit/qi21_rope.cpp) against the tables
2stable-diffusion.cpp 2988060 built for the same pictures: their sha256, recorded from sd.cpp's stock and native runners
3through the stage hook (tools/image/gate/stage_hooks.py pe_stock_<k>) in tools/image/gate/data/qi21_rope_sha.json
4(512x512 with four prompts, 1024x1024, 1536x1024, a 1,025-token prompt).  Compiles with the system C++ compiler; no GPU,
5no sd.cpp, no model file.
6
7The table is std::cos / std::sin of float angles, so its last bit is the C library's: the recorded sha256 are sd.cpp's on
8glibc (Linux), and the byte check runs where the C library is glibc.  Elsewhere sd.cpp gets that C library's bits too, not
9glibc's (macOS 27 on an M4: every float correctly rounded, 3,360 of the 269,568 floats of the first case 1 ulp from glibc's,
10so no recorded hash matches).  The second test runs everywhere: every float of the table against a float64 reference of the
11same float steps, within 2 ulp plus the error of a 2-ulp powf in the angle.
12
13    python -m pytest tools/test_dit_rope.py"""
14import hashlib
15import json
16import math
17import platform
18import shutil
19import struct
20import subprocess
21import tempfile
22import unittest
23from pathlib import Path
24
25ROOT = Path(__file__).resolve().parents[1]
26CXX = shutil.which("g++") or shutil.which("c++") or shutil.which("clang++")
27CASES = ROOT / "tools" / "image" / "gate" / "data" / "qi21_rope_sha.json"
28GLIBC = platform.system() == "Linux" and platform.libc_ver()[0] == "glibc"
29
30
31def build(td: Path) -> Path:
32    exe = td / "strata-dit-rope"
33    r = subprocess.run([CXX, "-std=c++17", "-O2", "-I", str(ROOT / "include"),
34                        str(ROOT / "src" / "image" / "dit" / "qi21_rope.cpp"),
35                        str(ROOT / "src" / "image" / "dit" / "qi21_rope_main.cpp"), "-o", str(exe)],
36                       capture_output=True, text=True, timeout=300)
37    if r.returncode != 0:
38        raise AssertionError("build failed:\n" + r.stderr[-3000:])
39    return exe
40
41
42def table(exe: Path, td: Path, c: dict) -> bytes:
43    out = td / "t.bin"
44    subprocess.run([str(exe), str(c["text_tokens"]), str(c["H"]), str(c["W"]), str(out)], check=True)
45    return out.read_bytes()
46
47
48def f32(x: float) -> float:
49    return struct.unpack("<f", struct.pack("<f", x))[0]
50
51
52def reference(text: int, H: int, W: int):
53    """(value, angle) for every float of the table: sd.cpp's float steps in float64, each rounded to float32, and cos / sin of
54    the float32 angle rounded once to float32."""
55    pos = [(float(p),) * 3 for p in range(text)]
56    pos += [(float(text), float(h - (H - H // 2)), float(w - (W - W // 2))) for h in range(H) for w in range(W)]   # every picture token at text_len
57    val, ang = [0.0] * (len(pos) * 256), [0.0] * (len(pos) * 256)
58    off = 0
59    for a, dim in enumerate((16, 56, 56)):
60        half = dim // 2
61        step = f32(f32(f32(dim * 1.0 - 2) / dim) / (half - 1))
62        omega = [f32(1.0 / f32(10000.0 ** f32(i * step))) for i in range(half)]
63        for i, p in enumerate(pos):
64            for j, om in enumerate(omega):
65                t = f32(p[a] * om)
66                c, s = f32(math.cos(t)), f32(math.sin(t))
67                k = i * 256 + off + 4 * j
68                val[k:k + 4] = (c, -s, s, c)
69                ang[k:k + 4] = (t,) * 4
70        off += half * 4
71    return val, ang
72
73
74def ulp32(x: float) -> float:
75    return 2.0 ** (math.floor(math.log2(max(abs(x), 2.0 ** -126))) - 23)
76
77
78@unittest.skipUnless(CXX, "no C++ compiler")
79class RopeTableMatchesSdcpp(unittest.TestCase):
80    @unittest.skipUnless(GLIBC, "the recorded sha256 are sd.cpp's tables on glibc, and this C library rounds cosf / sinf "
81                                "differently in the last bit (test_tables_close_to_float64 checks every float here)")
82    def test_tables(self):
83        cases = json.loads(CASES.read_text())
84        self.assertGreaterEqual(len(cases), 7)
85        with tempfile.TemporaryDirectory() as td:
86            exe = build(Path(td))
87            bad = [c["from"] for c in cases if hashlib.sha256(table(exe, Path(td), c)).hexdigest() != c["sha256"]]
88            self.assertEqual(bad, [])
89
90    def test_tables_close_to_float64(self):
91        cases = json.loads(CASES.read_text())
92        self.assertGreaterEqual(len(cases), 7)
93        with tempfile.TemporaryDirectory() as td:
94            exe = build(Path(td))
95            for c in cases:
96                raw = table(exe, Path(td), c)
97                got = struct.unpack("<%df" % (len(raw) // 4), raw)
98                val, ang = reference(c["text_tokens"], c["H"], c["W"])
99                self.assertEqual(len(got), len(val), c["from"])
100                far = [k for k, (g, v, t) in enumerate(zip(got, val, ang))
101                       if abs(g - v) > 2 * ulp32(v) + abs(t) * 2.0 ** -22]
102                self.assertEqual(far[:5], [], f"{c['from']}: {len(far)} of {len(got)} floats off "
103                                              f"(first at {far[0] if far else '-'}: ours {got[far[0]] if far else '-'}, "
104                                              f"float64 {val[far[0]] if far else '-'})")
105
106
107if __name__ == "__main__":
108    unittest.main()