okami.mom/strata

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

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
6.7 KiB134 linesraw
1"""Tests for the patch that puts Strata's VAE decoder into sd-cli (tools/image/sdcpp_vae/apply.py), on stand-in files
2with the code it edits at the pinned stable-diffusion.cpp commit: the sources it copies (byte for byte), the CMake
3target, the decode hook with its switch and its fallback (one warning that names the reason, then sd.cpp's own
4decoder), that a second run changes nothing, that it works before or after the native runner's and the noise
5generator's patches, and that a checkout at another commit is refused.
6
7    python -m unittest tools.test_sdcpp_vae
8"""
9from __future__ import annotations
10
11import importlib.util
12import tempfile
13import unittest
14from pathlib import Path
15
16ROOT = Path(__file__).resolve().parents[1]
17
18
19def load(name, path):
20    spec = importlib.util.spec_from_file_location(name, path)
21    m = importlib.util.module_from_spec(spec)
22    spec.loader.exec_module(m)
23    return m
24
25
26V = load("strata_sdcpp_vae_apply_test", ROOT / "tools" / "image" / "sdcpp_vae" / "apply.py")
27N = load("strata_sdcpp_native_apply_for_vae_test", ROOT / "tools" / "image" / "sdcpp_native" / "apply.py")
28Z = load("strata_sdcpp_noise_apply_for_vae_test", ROOT / "tools" / "image" / "sdcpp_noise" / "apply.py")
29
30ENGINE = """#include "core/rng.hpp"
31#include "core/rng_mt19937.hpp"
32#include "core/rng_philox.hpp"
33#include "core/util.h"
34
35bool StableDiffusionGGML::init(const sd_ctx_params_t* sd_ctx_params) {
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
44sd::Tensor<float> StableDiffusionGGML::decode_first_stage(const sd::Tensor<float>& x, bool decode_video) {
45    auto latents                      = first_stage_model->diffusion_to_vae_latents(x);
46    auto tiling_params                = first_stage_model->resolve_tiling_params(vae_tiling_params);
47    return {};
48}
49"""
50CMAKE = "add_library(${SD_LIB} STATIC ${SD_LIB_SOURCES})\ntarget_include_directories(${SD_LIB} PUBLIC . src include)\n"
51BUILDERS = '#include "model/diffusion/minit2i.hpp"\n' + N.BUILDER_OLD
52
53
54def fake_tree(d: Path) -> Path:
55    sd = d / "stable-diffusion.cpp"
56    (sd / "src" / "pipeline").mkdir(parents=True)
57    (sd / "src" / "core").mkdir(parents=True)
58    (sd / "src" / "model" / "diffusion").mkdir(parents=True)
59    (sd / "ggml" / "src" / "ggml-cuda").mkdir(parents=True)
60    (sd / "src" / "pipeline" / "diffusion_engine.cpp").write_text(ENGINE)
61    (sd / "src" / "pipeline" / "model_builders.cpp").write_text(BUILDERS)
62    (sd / "CMakeLists.txt").write_text(CMAKE)
63    return sd
64
65
66class Apply(unittest.TestCase):
67    def test_copies_edits_and_is_idempotent(self):
68        with tempfile.TemporaryDirectory() as t:
69            sd = fake_tree(Path(t))
70            V.apply(sd)
71            for src, rel in V.FILES:
72                self.assertEqual((sd / "src" / "strata_vae" / rel).read_bytes(), (ROOT / src).read_bytes(), rel)
73            self.assertTrue((sd / "src" / "strata_vae" / "include" / "strata" / "hip_compat" / "cublas_v2.h").is_file())
74            eng = (sd / "src" / "pipeline" / "diffusion_engine.cpp").read_text()
75            cm = (sd / "CMakeLists.txt").read_text()
76            self.assertIn('std::strstr(config_->params.model_args, "strata_vae=1")', eng)
77            self.assertIn("version == VERSION_QWEN_IMAGE_2_1", eng)
78            self.assertIn("#ifdef SD_STRATA_VAE", eng)
79            # the fallback: the reason goes into the warning, then stable-diffusion.cpp's decoder runs (no return)
80            self.assertEqual(eng.count('LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp\'s decoder", '
81                                       'strata_err.c_str());'), 2)
82            # a non-finite picture: the warning says that sd.cpp's decoder (the same f16 operands) may fail the same way
83            self.assertIn('if (strata_err.find("not finite") != std::string::npos)', eng)
84            self.assertIn("using stable-diffusion.cpp's decoder, which may fail the same way", eng)
85            cu = (ROOT / "src" / "image" / "vae" / "wan_vae.cu").read_text(encoding="utf-8")
86            self.assertIn('"wan_vae: the picture has values that are not finite', cu)      # the reason the hook looks for
87            self.assertLess(eng.index("return decoded;"), eng.rindex("LOG_WARN"))
88            self.assertLess(eng.rindex("LOG_WARN"), eng.index("auto tiling_params"))
89            self.assertIn("add_library(strata_vae STATIC", cm)
90            self.assertIn("target_compile_definitions(${SD_LIB} PRIVATE SD_STRATA_VAE)", cm)
91            self.assertNotIn("use_fast_math", cm)
92            # HIP: the library defined before enable_language(HIP) needs the architectures too (p620, 11-10)
93            self.assertIn('set_target_properties(strata_vae ${SD_LIB} PROPERTIES HIP_ARCHITECTURES '
94                          '"${CMAKE_HIP_ARCHITECTURES}")', cm)
95            self.assertLess(cm.index("if (SD_CUDA OR SD_HIPBLAS)"), cm.index(V.CMAKE_OLD))
96            before = (eng, cm)
97            V.apply(sd)
98            self.assertEqual(((sd / "src" / "pipeline" / "diffusion_engine.cpp").read_text(),
99                              (sd / "CMakeLists.txt").read_text()), before)
100
101    def test_with_native_and_noise_in_either_order(self):
102        results = []
103        for order in ((V, N, Z), (N, Z, V)):
104            with tempfile.TemporaryDirectory() as t:
105                sd = fake_tree(Path(t))
106                for m in order:
107                    if m is N:
108                        N.edit(sd / "src" / "pipeline" / "model_builders.cpp", N.INCLUDE_OLD, N.INCLUDE_NEW)
109                        N.edit(sd / "src" / "pipeline" / "model_builders.cpp", N.BUILDER_OLD, N.BUILDER_NEW)
110                        N.edit(sd / "CMakeLists.txt", N.CMAKE_OLD, N.CMAKE_NEW)
111                    elif m is Z:
112                        Z.apply(sd)
113                    else:
114                        V.apply(sd)
115                eng = (sd / "src" / "pipeline" / "diffusion_engine.cpp").read_text()
116                cm = (sd / "CMakeLists.txt").read_text()
117                self.assertIn(V.MARK, eng)
118                self.assertIn(Z.MARK, eng)
119                self.assertIn("SD_QI_NATIVE", cm)
120                self.assertIn("SD_STRATA_VAE", cm)
121                results.append(eng.count(V.MARK))
122        self.assertEqual(results[0], results[1])
123
124    def test_other_commit_is_refused(self):
125        with tempfile.TemporaryDirectory() as t:
126            sd = fake_tree(Path(t))
127            (sd / "src" / "pipeline" / "diffusion_engine.cpp").write_text(ENGINE.replace("diffusion_to_vae_latents(x)",
128                                                                                          "to_vae(x)"))
129            with self.assertRaises(SystemExit):
130                V.apply(sd)
131
132
133if __name__ == "__main__":
134    unittest.main()