okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
5.0 KiB105 linesraw
1"""tools/test_qi21_glue.py - the steps between Strata's image parts (src/image/pipeline/qi21_glue.cpp) give the bytes
2stable-diffusion.cpp 2988060's code gives: the starting latent (DiscreteFlowDenoiser::noise_scaling on a zero latent),
3the condition (apply_token_weights + the system rows dropped) and the decoder output to 0..1 (scale_tensor_to_0_1).
4The expectations are those operations written out with numpy float32 (and a sequential float64 sum for sd.cpp's
5Tensor<float>::mean).  Compiled twice (-O2; -O3 -ffp-contract=fast: the file must not fuse).  No GPU, no model file.
6
7    python -m pytest tools/test_qi21_glue.py"""
8import shutil
9import subprocess
10import tempfile
11import unittest
12from pathlib import Path
13
14import numpy as np
15
16ROOT = Path(__file__).resolve().parents[1]
17CXX = shutil.which("g++") or shutil.which("c++") or shutil.which("clang++")
18F = np.float32
19
20
21def sd_mean(v: np.ndarray) -> np.float32:
22    """sd::Tensor<float>::mean: a double sum in element order, divided in double, then float."""
23    s = np.cumsum(v.reshape(-1).astype(np.float64))[-1]
24    return F(s / np.float64(v.size))
25
26
27def want_condition(h: np.ndarray, w: np.ndarray, n_system: int) -> np.ndarray:
28    h = h.astype(np.float32).copy()
29    if not np.all(w == F(1)):
30        m0 = sd_mean(h)
31        h = (h * w[:, None]).astype(np.float32)
32        m1 = sd_mean(h)
33        if np.isfinite(m0) and np.isfinite(m1) and m1 != 0:
34            h = (h * F(m0 / m1)).astype(np.float32)
35    return h[n_system:]
36
37
38def want_unit(x: np.ndarray) -> np.ndarray:
39    v = ((x + F(1)).astype(np.float32) * F(0.5)).astype(np.float32)
40    return np.where(v < 0, F(0), np.where(v > 1, F(1), v)).astype(np.float32)
41
42
43@unittest.skipUnless(CXX, "no C++ compiler")
44class GlueMatchesSdcpp(unittest.TestCase):
45    def run_all(self, flags):
46        rng = np.random.default_rng(7)
47        with tempfile.TemporaryDirectory() as td:
48            t = Path(td)
49            exe = t / "strata-glue-check"
50            r = subprocess.run([CXX, "-std=c++17", *flags, "-I", str(ROOT / "include"),
51                                str(ROOT / "src" / "image" / "pipeline" / "qi21_glue.cpp"),
52                                str(ROOT / "src" / "image" / "pipeline" / "qi21_glue_check_main.cpp"), "-o", str(exe)],
53                               capture_output=True, text=True, timeout=300)
54            self.assertEqual(r.returncode, 0, r.stderr[-3000:])
55
56            def run(*args):
57                p = subprocess.run([str(exe), *map(str, args)], capture_output=True, text=True, timeout=60)
58                self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
59
60            # starting latent: sigma0 1.0 (Turbo) and another sigma; -0.0 noise becomes +0.0 as in sd.cpp
61            noise = np.concatenate([rng.standard_normal(4096), [-0.0, 0.0, 1e-45, -1e-45]]).astype(np.float32)
62            noise.tofile(t / "noise.bin")
63            for sigma in ("1.0", "0.978453"):
64                run("latent", t / "noise.bin", sigma, t / "x0.bin")
65                s = F(float(sigma))
66                want = ((np.zeros_like(noise) * (F(1) - s)).astype(np.float32) + (noise * s).astype(np.float32))
67                got = np.fromfile(t / "x0.bin", dtype=np.float32)
68                self.assertEqual(got.tobytes(), want.astype(np.float32).tobytes(), sigma)
69
70            # condition: plain weights (rows dropped only), weighted rows, a BREAK-like -1, a zero new mean
71            n, hd = 23, 96
72            h = (rng.standard_normal((n, hd)) * 40).astype(np.float32)
73            h.tofile(t / "h.bin")
74            cases = [np.ones(n, np.float32),
75                     np.array([1.0] * 10 + [1.21] * 5 + [0.9] * 8, np.float32),
76                     np.array([1.0] * 20 + [-1.0, 1.1, 1.0], np.float32)]
77            for i, w in enumerate(cases):
78                w.tofile(t / "w.bin")
79                run("cond", t / "h.bin", n, hd, t / "w.bin", 14, t / "c.bin")
80                got = np.fromfile(t / "c.bin", dtype=np.float32)
81                self.assertEqual(got.tobytes(), want_condition(h, w, 14).tobytes(), f"weights case {i}")
82            z = np.zeros((n, hd), np.float32)
83            z.tofile(t / "z.bin")
84            cases[1].tofile(t / "w.bin")
85            run("cond", t / "z.bin", n, hd, t / "w.bin", 14, t / "c.bin")
86            self.assertEqual(np.fromfile(t / "c.bin", dtype=np.float32).tobytes(), z[14:].tobytes())
87
88            # decoder output to 0..1, including the ends and values next to them
89            x = np.concatenate([rng.uniform(-1.3, 1.3, 20000),
90                                [-1.0, 1.0, -3.0, 3.0, 0.0, -0.0]]).astype(np.float32)
91            x = np.concatenate([x, np.nextafter(np.float32([-1, 1]), np.float32(0)),
92                                np.nextafter(np.float32([-1, 1]), np.float32([-2, 2]))]).astype(np.float32)
93            x.tofile(t / "u.bin")
94            run("unit", t / "u.bin", t / "u_out.bin")
95            self.assertEqual(np.fromfile(t / "u_out.bin", dtype=np.float32).tobytes(), want_unit(x).tobytes())
96
97    def test_o2(self):
98        self.run_all(["-O2"])
99
100    def test_o3_contract_fast(self):
101        self.run_all(["-O3", "-ffp-contract=fast"])
102
103
104if __name__ == "__main__":
105    unittest.main()