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
8.7 KiB169 linesraw
1"""tools/image/sdcpp_vae/apply.py - put Strata's own VAE decoder (src/image/vae, CUDA and HIP) into a
2stable-diffusion.cpp checkout at the pinned commit (tools/image/qimage.py SD_CPP_COMMIT).  Idempotent; sd-cli keeps
3stable-diffusion.cpp's decoder unless it is started with --model-args strata_vae=1, and only CUDA / HIP builds have it.
4
5    python tools/image/sdcpp_vae/apply.py third_party/stable-diffusion.cpp
6
7What it does:
8  * copies the decoder (src/image/vae/wan_vae.cu, safetensors_lite.hpp, convert.hpp) and the headers it uses
9    (include/strata/image/wan_vae.hpp, include/strata/kernels/{f16,bf16}_bits.hpp, include/strata/hip_compat/*) into
10    src/strata_vae/ of the checkout, unchanged;
11  * CMakeLists.txt: a static library strata_vae of our own (CUDA or HIP language, its own flags: none of ggml's
12    -use_fast_math) linked into the stable-diffusion library, with the cuBLAS / hipBLAS that ggml links already;
13  * src/pipeline/diffusion_engine.cpp: in decode_first_stage, for Qwen-Image-2.1 pictures with strata_vae=1, our
14    decoder takes the VAE-space latent and returns the picture in sd.cpp's 0-1 range; sd.cpp's latent statistics, its
15    8-bit conversion and its PNG writer stay as they are.  If our decoder cannot open the VAE file or fails, sd-cli logs
16    one warning and decodes with stable-diffusion.cpp's decoder."""
17from __future__ import annotations
18
19import shutil
20import sys
21from pathlib import Path
22
23HERE = Path(__file__).resolve().parent
24REPO = HERE.parents[2]
25MARK = "// strata: own VAE decoder"
26
27# (repo path, path under src/strata_vae/)
28FILES = [
29    ("src/image/vae/wan_vae.cu", "wan_vae.cu"),
30    ("src/image/vae/safetensors_lite.hpp", "safetensors_lite.hpp"),
31    ("src/image/vae/convert.hpp", "convert.hpp"),
32    ("include/strata/image/wan_vae.hpp", "include/strata/image/wan_vae.hpp"),
33    ("include/strata/kernels/f16_bits.hpp", "include/strata/kernels/f16_bits.hpp"),
34    ("include/strata/kernels/bf16_bits.hpp", "include/strata/kernels/bf16_bits.hpp"),
35]
36HIP_COMPAT = "include/strata/hip_compat"
37
38INCLUDE_OLD = '#include "core/rng_mt19937.hpp"\n'
39INCLUDE_NEW = INCLUDE_OLD + ("#ifdef SD_STRATA_VAE\n#include <cstring>\n#include \"strata/image/wan_vae.hpp\"  " + MARK +
40                             "\n#endif\n")
41DECODE_OLD = """    auto latents                      = first_stage_model->diffusion_to_vae_latents(x);
42    auto tiling_params                = first_stage_model->resolve_tiling_params(vae_tiling_params);
43"""
44DECODE_NEW = """    auto latents                      = first_stage_model->diffusion_to_vae_latents(x);
45#ifdef SD_STRATA_VAE
46    """ + MARK + """ (--model-args strata_vae=1): the one-pass picture, f32 accumulation
47    if (version == VERSION_QWEN_IMAGE_2_1 && !decode_video && config_->params.model_args != nullptr &&
48        std::strstr(config_->params.model_args, "strata_vae=1") != nullptr && latents.dim() == 4 &&
49        latents.shape()[2] == 64 && latents.shape()[3] == 1) {
50        static strata::image::WanVae* strata_vae = nullptr;
51        static bool strata_vae_failed            = false;
52        std::string strata_err;
53        if (strata_vae == nullptr && !strata_vae_failed) {
54            strata_vae        = strata::image::wan_vae_open(SAFE_STR(config_->params.vae_path), -1, &strata_err,
55                                                            n_threads);   // sd-cli's own thread setting
56            strata_vae_failed = strata_vae == nullptr;
57            if (strata_vae_failed) {
58                LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder", strata_err.c_str());
59            }
60        }
61        if (strata_vae != nullptr) {
62            const int lw              = static_cast<int>(latents.shape()[0]);
63            const int lh              = static_cast<int>(latents.shape()[1]);
64            sd::Tensor<float> decoded = sd::zeros<float>({static_cast<int64_t>(lw) * 16, static_cast<int64_t>(lh) * 16, 4, 1});
65            strata::image::WanVaeStats strata_stats;
66            strata_err = strata::image::wan_vae_decode(strata_vae, latents.data(), lh, lw, decoded.data(), &strata_stats);
67            if (strata_err.empty()) {
68                for (int64_t i = 0; i < decoded.numel(); ++i) {   // VAE::scale_tensor_to_0_1
69                    float value = (decoded[i] + 1.0f) * 0.5f;
70                    decoded[i]  = std::max(0.0f, std::min(1.0f, value));
71                }
72                LOG_INFO("strata VAE decoder: %.2fs, peak %.0f MiB", strata_stats.decode_ms / 1000.0,
73                         strata_stats.peak_bytes / 1048576.0);
74                return decoded;
75            }
76            if (strata_err.find("not finite") != std::string::npos) {   // sd.cpp's decoder has the same f16 operands
77                LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder, which may fail the same way",
78                         strata_err.c_str());
79            } else {
80                LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder", strata_err.c_str());
81            }
82        }
83    }
84#endif
85    auto tiling_params                = first_stage_model->resolve_tiling_params(vae_tiling_params);
86"""
87CMAKE_OLD = "target_include_directories(${SD_LIB} PUBLIC . src include)\n"
88CMAKE_NEW = """if (SD_CUDA OR SD_HIPBLAS)  # """ + MARK.lstrip("/ ") + """: src/strata_vae (tools/image/sdcpp_vae/apply.py)
89    set(STRATA_VAE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/strata_vae)
90    if (SD_CUDA)
91        if (NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
92            set(STRATA_VAE_ARCH native)
93        endif()
94        enable_language(CUDA)
95        find_package(CUDAToolkit REQUIRED)
96        add_library(strata_vae STATIC ${STRATA_VAE_DIR}/wan_vae.cu)
97        if (STRATA_VAE_ARCH)
98            set_target_properties(strata_vae PROPERTIES CUDA_ARCHITECTURES ${STRATA_VAE_ARCH})
99        endif()
100        if (GGML_STATIC AND NOT WIN32)   # the same cuBLAS / runtime as ggml-cuda
101            target_link_libraries(strata_vae PRIVATE CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static)
102        elseif (GGML_STATIC)
103            target_link_libraries(strata_vae PRIVATE CUDA::cudart_static CUDA::cublas)
104        else()
105            target_link_libraries(strata_vae PRIVATE CUDA::cudart CUDA::cublas)
106        endif()
107    else()
108        if (AMDGPU_TARGETS AND NOT GPU_TARGETS)
109            set(GPU_TARGETS ${AMDGPU_TARGETS})
110        endif()
111        if (GPU_TARGETS AND NOT CMAKE_HIP_ARCHITECTURES)
112            set(CMAKE_HIP_ARCHITECTURES ${GPU_TARGETS})
113        endif()
114        enable_language(HIP)
115        find_package(hip REQUIRED)
116        find_package(hipblas REQUIRED)
117        set_source_files_properties(${STRATA_VAE_DIR}/wan_vae.cu PROPERTIES LANGUAGE HIP)
118        add_library(strata_vae STATIC ${STRATA_VAE_DIR}/wan_vae.cu)
119        target_link_libraries(strata_vae PRIVATE hip::host roc::hipblas)
120        # HIP is enabled here, after the stable-diffusion library was defined: give both targets the architectures
121        # (else CMake stops with "HIP_ARCHITECTURES is empty for target stable-diffusion")
122        set_target_properties(strata_vae ${SD_LIB} PROPERTIES HIP_ARCHITECTURES "${CMAKE_HIP_ARCHITECTURES}")
123    endif()
124    target_include_directories(strata_vae PRIVATE ${STRATA_VAE_DIR} ${STRATA_VAE_DIR}/include)
125    target_compile_features(strata_vae PRIVATE cxx_std_17)
126    set_target_properties(strata_vae PROPERTIES POSITION_INDEPENDENT_CODE ON)
127    target_link_libraries(${SD_LIB} PRIVATE strata_vae)
128    target_include_directories(${SD_LIB} PRIVATE ${STRATA_VAE_DIR}/include)
129    target_compile_definitions(${SD_LIB} PRIVATE SD_STRATA_VAE)
130endif()
131""" + CMAKE_OLD
132
133
134def edit(path: Path, old: str, new: str) -> None:
135    text = path.read_text(encoding="utf-8")
136    if new in text:
137        return
138    if text.count(old) != 1:
139        raise SystemExit(f"{path}: the expected code is not there (another stable-diffusion.cpp commit?)")
140    path.write_bytes(text.replace(old, new).encode("utf-8"))
141
142
143def copy_sources(dst: Path) -> None:
144    """The decoder's files into dst (src/strata_vae of a checkout), byte for byte."""
145    for src, rel in FILES:
146        (dst / rel).parent.mkdir(parents=True, exist_ok=True)
147        shutil.copyfile(REPO / src, dst / rel)
148    hc = dst / HIP_COMPAT
149    hc.mkdir(parents=True, exist_ok=True)
150    for f in sorted((REPO / HIP_COMPAT).iterdir()):
151        if f.is_file():
152            shutil.copyfile(f, hc / f.name)
153
154
155def apply(sd: Path) -> None:
156    sd = Path(sd)
157    copy_sources(sd / "src" / "strata_vae")
158    engine = sd / "src" / "pipeline" / "diffusion_engine.cpp"
159    edit(engine, INCLUDE_OLD, INCLUDE_NEW)
160    edit(engine, DECODE_OLD, DECODE_NEW)
161    edit(sd / "CMakeLists.txt", CMAKE_OLD, CMAKE_NEW)
162
163
164if __name__ == "__main__":
165    if len(sys.argv) == 2 and not sys.argv[1].startswith("-"):
166        apply(Path(sys.argv[1]))
167        print("Strata VAE decoder applied")
168    else:
169        raise SystemExit(__doc__)