okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
150c2394f
main
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 6python -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) { 33std::string rpc_servers_spec = SAFE_STR(sd_ctx_params->rpc_servers); 34add_rpc_devices(rpc_servers_spec); 35 36rng = get_rng(sd_ctx_params->rng_type); 37if (sd_ctx_params->sampler_rng_type != RNG_TYPE_COUNT && sd_ctx_params->sampler_rng_type != sd_ctx_params->rng_type) { 38sampler_rng = get_rng(sd_ctx_params->sampler_rng_type); 39} else { 40sampler_rng = rng; 41} 42 43ggml_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) { 55const uint64_t seed = std::strtoull(argv[1], nullptr, 10); 56const std::vector<float> o = strata_noise::randn(seed, 262144); 57uint64_t h = 1469598103934665603ull; 58const unsigned char* p = (const unsigned char*) o.data(); 59for (size_t i = 0; i < o.size() * 4; ++i) h = (h ^ p[i]) * 1099511628211ull; 60std::printf("%016llx\\n", (unsigned long long) h); 61return 0; 62} 63""" 64 65 66class Apply (unittest .TestCase ): 67def tree (self ,d ): 68sd = 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" ) 72return sd 73 74def test_patch_and_idempotent (self ): 75with tempfile .TemporaryDirectory ()as d : 76sd = self .tree (d ) 77A .apply (sd ) 78engine = (sd / "src" / "pipeline" / "diffusion_engine.cpp" ).read_text (encoding = "utf-8" ) 79self .assertIn ('#include "core/strata_philox_rng.hpp"' ,engine ) 80self .assertEqual (engine .count ("strata_noise::requested(sd_ctx_params->model_args)" ),1 ) 81self .assertIn ("rng = std::make_shared<StrataPhiloxRNG>();" ,engine ) 82# the stock code is all still there, in the same order: the block only follows it 83self .assertTrue (engine .index ("sampler_rng = rng;" )< engine .index ("strata_noise::requested" )) 84self .assertTrue (engine .index ("strata_noise::requested" )< engine .index ("ggml_log_set" )) 85for name in A .FILES + ("strata_sin_exc_data.inc" ,): 86self .assertTrue ((sd / "src" / "core" / name ).is_file (),name ) 87before = {p :p .read_bytes ()for p in sd .rglob ("*" )if p .is_file ()} 88A .apply (sd )# again: nothing changes 89self .assertEqual ({p :p .read_bytes ()for p in sd .rglob ("*" )if p .is_file ()},before ) 90 91def test_another_commit_is_refused (self ): 92with tempfile .TemporaryDirectory ()as d : 93sd = self .tree (d ) 94p = sd / "src" / "pipeline" / "diffusion_engine.cpp" 95p .write_text (ENGINE .replace ("sampler_rng = rng;" ,"sampler_rng = other;" ),encoding = "utf-8" ) 96with self .assertRaises (SystemExit ): 97A .apply (sd ) 98 99def test_the_table_as_a_c_array (self ): 100data = (NOISE / A .BIN ).read_bytes () 101src = A .data_inc (data ) 102body = src .split ("= {" ,1 )[1 ].rsplit ("};" ,1 )[0 ] 103got = bytes (int (x ,16 )for x in re .findall (r"0x([0-9a-f]{2})" ,body )) 104self .assertEqual (got ,data ) 105self .assertIn (f"STRATA_SIN_EXC_DATA[]" ,src ) 106self .assertLess (len (src ),1_200_000 )# about 1.1 MB of source for the 184 KB table 107 108def test_prepare_writes_the_generator_files (self ): 109with tempfile .TemporaryDirectory ()as d : 110A .prepare (Path (d )/ "inc" ) 111names = sorted (p .name for p in (Path (d )/ "inc" ).iterdir ()) 112self .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 ): 117def test_three_seeds_match_the_x86_stream (self ): 118cxx = shutil .which ("g++" )or shutil .which ("c++" )or shutil .which ("clang++" ) 119with tempfile .TemporaryDirectory ()as d : 120inc = Path (d )/ "inc" 121A .prepare (inc ) 122 (Path (d )/ "t.cpp" ).write_text (PROGRAM ,encoding = "utf-8" ) 123exe = Path (d )/ ("t.exe" if sys .platform == "win32" else "t" ) 124r = subprocess .run ([cxx ,"-std=c++17" ,"-O2" ,"-I" ,str (inc ),str (Path (d )/ "t.cpp" ),"-o" ,str (exe )], 125capture_output = True ,text = True ) 126self .assertEqual (r .returncode ,0 ,r .stderr [- 2000 :]) 127for seed ,want in GOLDEN .items (): 128out = subprocess .run ([str (exe ),str (seed )],capture_output = True ,text = True ,timeout = 300 ) 129self .assertEqual (out .stdout .strip (),want ,seed ) 130 131 132if __name__ == "__main__" : 133unittest .main ()