okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
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 5python 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 10src/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 14decoder takes the VAE-space latent and returns the picture in sd.cpp's 0-1 range; sd.cpp's latent statistics, its 158-bit conversion and its PNG writer stay as they are. If our decoder cannot open the VAE file or fails, sd-cli logs 16one 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); 42auto 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 47if (version == VERSION_QWEN_IMAGE_2_1 && !decode_video && config_->params.model_args != nullptr && 48std::strstr(config_->params.model_args, "strata_vae=1") != nullptr && latents.dim() == 4 && 49latents.shape()[2] == 64 && latents.shape()[3] == 1) { 50static strata::image::WanVae* strata_vae = nullptr; 51static bool strata_vae_failed = false; 52std::string strata_err; 53if (strata_vae == nullptr && !strata_vae_failed) { 54strata_vae = strata::image::wan_vae_open(SAFE_STR(config_->params.vae_path), -1, &strata_err, 55n_threads); // sd-cli's own thread setting 56strata_vae_failed = strata_vae == nullptr; 57if (strata_vae_failed) { 58LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder", strata_err.c_str()); 59} 60} 61if (strata_vae != nullptr) { 62const int lw = static_cast<int>(latents.shape()[0]); 63const int lh = static_cast<int>(latents.shape()[1]); 64sd::Tensor<float> decoded = sd::zeros<float>({static_cast<int64_t>(lw) * 16, static_cast<int64_t>(lh) * 16, 4, 1}); 65strata::image::WanVaeStats strata_stats; 66strata_err = strata::image::wan_vae_decode(strata_vae, latents.data(), lh, lw, decoded.data(), &strata_stats); 67if (strata_err.empty()) { 68for (int64_t i = 0; i < decoded.numel(); ++i) { // VAE::scale_tensor_to_0_1 69float value = (decoded[i] + 1.0f) * 0.5f; 70decoded[i] = std::max(0.0f, std::min(1.0f, value)); 71} 72LOG_INFO("strata VAE decoder: %.2fs, peak %.0f MiB", strata_stats.decode_ms / 1000.0, 73strata_stats.peak_bytes / 1048576.0); 74return decoded; 75} 76if (strata_err.find("not finite") != std::string::npos) { // sd.cpp's decoder has the same f16 operands 77LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder, which may fail the same way", 78strata_err.c_str()); 79} else { 80LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder", strata_err.c_str()); 81} 82} 83} 84#endif 85auto 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) 89set(STRATA_VAE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/strata_vae) 90if (SD_CUDA) 91if (NOT DEFINED CMAKE_CUDA_ARCHITECTURES) 92set(STRATA_VAE_ARCH native) 93endif() 94enable_language(CUDA) 95find_package(CUDAToolkit REQUIRED) 96add_library(strata_vae STATIC ${STRATA_VAE_DIR}/wan_vae.cu) 97if (STRATA_VAE_ARCH) 98set_target_properties(strata_vae PROPERTIES CUDA_ARCHITECTURES ${STRATA_VAE_ARCH}) 99endif() 100if (GGML_STATIC AND NOT WIN32) # the same cuBLAS / runtime as ggml-cuda 101target_link_libraries(strata_vae PRIVATE CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static) 102elseif (GGML_STATIC) 103target_link_libraries(strata_vae PRIVATE CUDA::cudart_static CUDA::cublas) 104else() 105target_link_libraries(strata_vae PRIVATE CUDA::cudart CUDA::cublas) 106endif() 107else() 108if (AMDGPU_TARGETS AND NOT GPU_TARGETS) 109set(GPU_TARGETS ${AMDGPU_TARGETS}) 110endif() 111if (GPU_TARGETS AND NOT CMAKE_HIP_ARCHITECTURES) 112set(CMAKE_HIP_ARCHITECTURES ${GPU_TARGETS}) 113endif() 114enable_language(HIP) 115find_package(hip REQUIRED) 116find_package(hipblas REQUIRED) 117set_source_files_properties(${STRATA_VAE_DIR}/wan_vae.cu PROPERTIES LANGUAGE HIP) 118add_library(strata_vae STATIC ${STRATA_VAE_DIR}/wan_vae.cu) 119target_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") 122set_target_properties(strata_vae ${SD_LIB} PROPERTIES HIP_ARCHITECTURES "${CMAKE_HIP_ARCHITECTURES}") 123endif() 124target_include_directories(strata_vae PRIVATE ${STRATA_VAE_DIR} ${STRATA_VAE_DIR}/include) 125target_compile_features(strata_vae PRIVATE cxx_std_17) 126set_target_properties(strata_vae PROPERTIES POSITION_INDEPENDENT_CODE ON) 127target_link_libraries(${SD_LIB} PRIVATE strata_vae) 128target_include_directories(${SD_LIB} PRIVATE ${STRATA_VAE_DIR}/include) 129target_compile_definitions(${SD_LIB} PRIVATE SD_STRATA_VAE) 130endif() 131""" + CMAKE_OLD 132 133 134def edit (path :Path ,old :str ,new :str )-> None : 135text = path .read_text (encoding = "utf-8" ) 136if new in text : 137return 138if text .count (old )!= 1 : 139raise SystemExit (f" { path } : the expected code is not there (another stable-diffusion.cpp commit?)" ) 140path .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.""" 145for src ,rel in FILES : 146 (dst / rel ).parent .mkdir (parents = True ,exist_ok = True ) 147shutil .copyfile (REPO / src ,dst / rel ) 148hc = dst / HIP_COMPAT 149hc .mkdir (parents = True ,exist_ok = True ) 150for f in sorted ((REPO / HIP_COMPAT ).iterdir ()): 151if f .is_file (): 152shutil .copyfile (f ,hc / f .name ) 153 154 155def apply (sd :Path )-> None : 156sd = Path (sd ) 157copy_sources (sd / "src" / "strata_vae" ) 158engine = sd / "src" / "pipeline" / "diffusion_engine.cpp" 159edit (engine ,INCLUDE_OLD ,INCLUDE_NEW ) 160edit (engine ,DECODE_OLD ,DECODE_NEW ) 161edit (sd / "CMakeLists.txt" ,CMAKE_OLD ,CMAKE_NEW ) 162 163 164if __name__ == "__main__" : 165if len (sys .argv )== 2 and not sys .argv [1 ].startswith ("-" ): 166apply (Path (sys .argv [1 ])) 167"Strata VAE decoder applied" ) 168else : 169raise SystemExit (__doc__ )