okami.mom/strata

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

Niko1221Merge f-own-5 fccdb48a3 (image noise switch, step 1 only) into f-own-int150c2394f

main
6.1 KiB133 linesraw
1"""Tests for Strata's noise generator for sd-cli (tools/image/sdcpp_noise): the patch for the pinned
2stable-diffusion.cpp (a stand-in file with the code it edits), the table as a C array, and, where a C++ compiler is
3there, the generator's stream for three seeds against the hashes of stable-diffusion.cpp's Linux x86 build.  The
4exhaustive proofs (every input of the generator, 1005 seeds, three CPUs and compilers) are tools/image/gate/noise.
5
6    python -m unittest tools.test_sdcpp_noise
7"""
8from __future__ import annotations
9
10import re
11import shutil
12import subprocess
13import sys
14import tempfile
15import unittest
16from pathlib import Path
17
18import importlib.util  # noqa: E402
19
20ROOT = Path(__file__).resolve().parents[1]
21NOISE = ROOT / "tools" / "image" / "sdcpp_noise"
22_spec = importlib.util.spec_from_file_location("strata_sdcpp_noise_apply_test", NOISE / "apply.py")
23A = importlib.util.module_from_spec(_spec)             # not "import apply": sdcpp_native has an apply.py too
24_spec.loader.exec_module(A)
25
26# the lines of src/pipeline/diffusion_engine.cpp at the pinned commit that apply.py edits, with their neighbours
27ENGINE = """#include "core/rng.hpp"
28#include "core/rng_mt19937.hpp"
29#include "core/rng_philox.hpp"
30#include "core/util.h"
31
32bool StableDiffusionGGML::init(const sd_ctx_params_t* sd_ctx_params) {
33    std::string rpc_servers_spec = SAFE_STR(sd_ctx_params->rpc_servers);
34    add_rpc_devices(rpc_servers_spec);
35
36    rng = get_rng(sd_ctx_params->rng_type);
37    if (sd_ctx_params->sampler_rng_type != RNG_TYPE_COUNT && sd_ctx_params->sampler_rng_type != sd_ctx_params->rng_type) {
38        sampler_rng = get_rng(sd_ctx_params->sampler_rng_type);
39    } else {
40        sampler_rng = rng;
41    }
42
43    ggml_log_set(sd_ggml_log_callback, nullptr);
44}
45"""
46
47# fnv64 of the 262144 floats randn(seed, 262144) gives, as stable-diffusion.cpp 2988060's Linux x86 build (GCC -O3, no
48# -march) makes them (tools/image/gate/noise/seeds.cpp, 1005 seeds, p2006 x86 11-10; the same on aarch64 and MSVC)
49GOLDEN = {0: "ed8d8d740dbd5fe6", 42: "ab9095ca6f8db096", 4611686018427387904: "ecc168e692cf1189"}
50
51PROGRAM = """#include <cstdio>
52#include <cstdlib>
53#include "strata_noise.hpp"
54int main(int argc, char** argv) {
55    const uint64_t seed = std::strtoull(argv[1], nullptr, 10);
56    const std::vector<float> o = strata_noise::randn(seed, 262144);
57    uint64_t h = 1469598103934665603ull;
58    const unsigned char* p = (const unsigned char*) o.data();
59    for (size_t i = 0; i < o.size() * 4; ++i) h = (h ^ p[i]) * 1099511628211ull;
60    std::printf("%016llx\\n", (unsigned long long) h);
61    return 0;
62}
63"""
64
65
66class Apply(unittest.TestCase):
67    def tree(self, d):
68        sd = Path(d) / "sd"
69        (sd / "src" / "pipeline").mkdir(parents=True)
70        (sd / "src" / "core").mkdir(parents=True)
71        (sd / "src" / "pipeline" / "diffusion_engine.cpp").write_text(ENGINE, encoding="utf-8")
72        return sd
73
74    def test_patch_and_idempotent(self):
75        with tempfile.TemporaryDirectory() as d:
76            sd = self.tree(d)
77            A.apply(sd)
78            engine = (sd / "src" / "pipeline" / "diffusion_engine.cpp").read_text(encoding="utf-8")
79            self.assertIn('#include "core/strata_philox_rng.hpp"', engine)
80            self.assertEqual(engine.count("strata_noise::requested(sd_ctx_params->model_args)"), 1)
81            self.assertIn("rng = std::make_shared<StrataPhiloxRNG>();", engine)
82            # the stock code is all still there, in the same order: the block only follows it
83            self.assertTrue(engine.index("sampler_rng = rng;") < engine.index("strata_noise::requested"))
84            self.assertTrue(engine.index("strata_noise::requested") < engine.index("ggml_log_set"))
85            for name in A.FILES + ("strata_sin_exc_data.inc",):
86                self.assertTrue((sd / "src" / "core" / name).is_file(), name)
87            before = {p: p.read_bytes() for p in sd.rglob("*") if p.is_file()}
88            A.apply(sd)                                   # again: nothing changes
89            self.assertEqual({p: p.read_bytes() for p in sd.rglob("*") if p.is_file()}, before)
90
91    def test_another_commit_is_refused(self):
92        with tempfile.TemporaryDirectory() as d:
93            sd = self.tree(d)
94            p = sd / "src" / "pipeline" / "diffusion_engine.cpp"
95            p.write_text(ENGINE.replace("sampler_rng = rng;", "sampler_rng = other;"), encoding="utf-8")
96            with self.assertRaises(SystemExit):
97                A.apply(sd)
98
99    def test_the_table_as_a_c_array(self):
100        data = (NOISE / A.BIN).read_bytes()
101        src = A.data_inc(data)
102        body = src.split("= {", 1)[1].rsplit("};", 1)[0]
103        got = bytes(int(x, 16) for x in re.findall(r"0x([0-9a-f]{2})", body))
104        self.assertEqual(got, data)
105        self.assertIn(f"STRATA_SIN_EXC_DATA[]", src)
106        self.assertLess(len(src), 1_200_000)             # about 1.1 MB of source for the 184 KB table
107
108    def test_prepare_writes_the_generator_files(self):
109        with tempfile.TemporaryDirectory() as d:
110            A.prepare(Path(d) / "inc")
111            names = sorted(p.name for p in (Path(d) / "inc").iterdir())
112            self.assertEqual(names, sorted(A.FILES + ("strata_sin_exc_data.inc",)))
113
114
115@unittest.skipUnless(shutil.which("g++") or shutil.which("c++") or shutil.which("clang++"), "no C++ compiler")
116class Stream(unittest.TestCase):
117    def test_three_seeds_match_the_x86_stream(self):
118        cxx = shutil.which("g++") or shutil.which("c++") or shutil.which("clang++")
119        with tempfile.TemporaryDirectory() as d:
120            inc = Path(d) / "inc"
121            A.prepare(inc)
122            (Path(d) / "t.cpp").write_text(PROGRAM, encoding="utf-8")
123            exe = Path(d) / ("t.exe" if sys.platform == "win32" else "t")
124            r = subprocess.run([cxx, "-std=c++17", "-O2", "-I", str(inc), str(Path(d) / "t.cpp"), "-o", str(exe)],
125                               capture_output=True, text=True)
126            self.assertEqual(r.returncode, 0, r.stderr[-2000:])
127            for seed, want in GOLDEN.items():
128                out = subprocess.run([str(exe), str(seed)], capture_output=True, text=True, timeout=300)
129                self.assertEqual(out.stdout.strip(), want, seed)
130
131
132if __name__ == "__main__":
133    unittest.main()