okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
1"""tools/image/qimage.py - Qwen-Image-2.1-Turbo for Strata's image endpoint: stable-diffusion.cpp (sd-cli) at a pinned 2commit, built for this PC's GPU, and the model's three files at pinned Hugging Face revisions. 3 4setup.py (--images qwen-image) and tools/image/install.py use these pieces; serve/images.py runs the result. 5 6backend CUDA on an NVIDIA card, HIP on an AMD card with its own memory (Linux), Vulkan on an APU/iGPU (AMD's shared 7memory: the HIP path's queue evictions reset a 780M on current firmware, NEW-MODELS-PLAN.md section 4), 8on Intel and on AMD under Windows; CPU without a GPU. --image-backend picks another. 9files the denoiser (DiT) quant by the GPU's memory: Q4_K_M up to 8 GB, Q6_K up to 12 GB, Q8_0 above (Unsloth's 10LPIPS vs bf16: 0.153 / 0.055 / 0.036); the VAE (bf16); the Qwen3-VL-8B text encoder UD-Q4_K_XL (the 11model card's choice). Each file is checked against the SHA-256 the Hugging Face API lists for it at the 12pinned revision. 13defaults 8 steps, CFG 1, euler, Turbo's own sigmas (serve/images.py), --diffusion-fa; on Vulkan also --vae-tiling 14(an untiled 1024x1024 VAE decode is one dispatch long enough to trip the amdgpu job timeout on a 780M) 15with --vae-tile-overlap 0.25. 16""" 17from __future__import annotations 18 19import os 20import shutil 21import zipfile 22from pathlib import Path 23 24SD_CPP_COMMIT = "2988060a4338a5dcd94721c964a8e87003c1ac8b" # "add TAEQI2.1 support for Qwen Image 2.1" (#2123) 25SD_GGML_COMMIT = "d25b121ce1d6ae0c7e62ad080460d9fc1e46dd93" # its ggml submodule (leejet/ggml) 26SD_CPP_ZIP = f"https://github.com/leejet/stable-diffusion.cpp/archive/ { SD_CPP_COMMIT } .zip" 27SD_GGML_ZIP = f"https://github.com/leejet/ggml/archive/ { SD_GGML_COMMIT } .zip" 28 29# the LunarG Vulkan SDK for a Linux PC without Vulkan development files (headers, glslc): unpacked into third_party, 30# no sudo; the version the 780M builds were made with 31VULKAN_SDK_VERSION = "1.4.363.0" 32VULKAN_SDK_URL = (f"https://sdk.lunarg.com/sdk/download/ { VULKAN_SDK_VERSION } /linux/" 33f"vulkansdk-linux-x86_64- { VULKAN_SDK_VERSION } .tar.xz" ) 34VULKAN_SDK_SIZE = 366_564_872 35VULKAN_SDK_SHA256 = "197962f5cbf80baf2775a03336a01cee7c8745686c65aaa70d3f751ade4d7e43" 36 37REVISIONS = {# the `sha` of https://huggingface.co/api/models/<repo>, 2026-10-12 38"unsloth/Qwen-Image-2.1-Turbo-GGUF" :"5d1f9f759ea877ae556cda88dbec958b62ad3809" , 39"unsloth/Qwen-Image-2.1-FP8" :"bb21a8ba7f0371c19ad1f72c82a5e8fc10f39939" , 40"unsloth/Qwen3-VL-8B-Instruct-GGUF" :"b93a7ee713758252c555be4210c00540df954dc2" , 41} 42_DIT = "unsloth/Qwen-Image-2.1-Turbo-GGUF" 43# name -> (repo, path in the repo, bytes, sha256): the Hub's LFS pointers at the pinned revisions 44FILES = { 45"Q4_K_M" : (_DIT ,"qwen-image-2.1-turbo-Q4_K_M.gguf" ,4_199_565_120 , 46"8940e8b522af886e0c0f5afddf720e82dd223cb9a43580b5f61c4d740452ac20" ), 47"Q6_K" : (_DIT ,"qwen-image-2.1-turbo-Q6_K.gguf" ,6_271_551_296 , 48"f4560fb47ad863ffed7e32737d3c42988c44bd0c459606777d7ffe2e895d0a70" ), 49"Q8_0" : (_DIT ,"qwen-image-2.1-turbo-Q8_0.gguf" ,7_640_860_480 , 50"399d2ddc3636f36456e2f5bfa57187da4e38721bc046430317f42a9eab5b1712" ), 51"vae" : ("unsloth/Qwen-Image-2.1-FP8" ,"vae/qwen_image_2.1_vae_bf16.safetensors" ,675_508_656 , 52"71879ffd5321e6d10c3c87513e2b474b1252efa7f3dec2969214a9bf06a6dd5c" ), 53"llm" : ("unsloth/Qwen3-VL-8B-Instruct-GGUF" ,"Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf" ,5_148_699_488 , 54"e3d1a6e87c5cb31e054f2c3bc0dd82ffde052f613de5eef3665b7bd33c9b703e" ), 55} 56QUANTS = ("Q4_K_M" ,"Q6_K" ,"Q8_0" ) 57BACKENDS = ("cuda" ,"hip" ,"vulkan" ,"cpu" ) 58LICENSE_NOTE = ("Qwen-Image-2.1-Turbo is under the Qwen Research License (not Apache 2.0): " 59"https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo/blob/main/LICENSE - read it before you use the images " 60"commercially" ) 61MODEL_DIR = "qwen-image-2.1-turbo" 62SD_EXE = "sd-cli.exe" if os .name == "nt" else "sd-cli" 63 64 65def pick_quant (gpu_gb :float )-> str : 66"""The denoiser for a GPU with `gpu_gb` of memory: Q4_K_M up to 8 GB, Q6_K up to 12 GB, Q8_0 above.""" 67if gpu_gb <= 8 : 68return "Q4_K_M" 69if gpu_gb <= 12 : 70return "Q6_K" 71return "Q8_0" 72 73 74# AMD APUs (integrated GPUs on shared memory) by gfx target: Rembrandt 680M/660M, Mendocino 610M, Phoenix 780M/760M/ 75# 740M, Strix Point 890M/880M, Strix Halo 8060S, Krackan, Raven/Renoir/Cezanne 76APU_ARCHS = ("gfx1035" ,"gfx1036" ,"gfx1037" ,"gfx1103" ,"gfx1150" ,"gfx1151" ,"gfx1152" ,"gfx1153" , 77"gfx902" ,"gfx909" ,"gfx90c" ) 78 79 80def is_apu (gpu :dict | None )-> bool : 81"""An integrated GPU on shared memory: setup's "uma" mark, or an APU's gfx target (setup marks only the APUs the 82text engine supports).""" 83if not gpu : 84return False 85return bool (gpu .get ("uma" ))or str (gpu .get ("arch" )or "" ).split (":" )[0 ]in APU_ARCHS 86 87 88def pick_backend (gpu :dict | None ,win :bool )-> str : 89"""sd.cpp's backend for setup's GPU dict (vendor, uma, arch): see the module's docstring.""" 90if not gpu : 91return "cpu" 92vendor = (gpu .get ("vendor" )or "nvidia" ).lower () 93if vendor == "nvidia" : 94return "cuda" 95if vendor == "amd" : 96return "vulkan" if is_apu (gpu )or win else "hip" 97return "vulkan" # Intel (Arc) and others 98 99 100def default_args (backend :str )-> list [str ]: 101"""sd-cli's fixed arguments besides the ones serve/images.py writes per request.""" 102# Vulkan: 256-pixel tiles at a quarter's overlap, not sd.cpp's half: the 780M's 1024x1024 decode takes 23 s instead 103# of 45 s, at an LPIPS of 0.012 against the half-overlap image (Q8_0's own distance to bf16 is ~0.03) 104return ["--diffusion-fa" ]+ (["--vae-tiling" ,"--vae-tile-overlap" ,"0.25" ]if backend == "vulkan" else []) 105 106 107def file_url (name :str ,endpoint :str = "https://huggingface.co" )-> str : 108repo ,path ,_ ,_ = FILES [name ] 109return f" { endpoint . rstrip ( '/' ) } / { repo } /resolve/ { REVISIONS [ repo ] } / { path } " 110 111 112def local_path (models_dir :Path ,name :str )-> Path : 113return Path (models_dir )/ MODEL_DIR / Path (FILES [name ][1 ]).name 114 115 116def cmake_defs (backend :str ,arch = None ,rocm :Path | None = None ,cuda_root :Path | None = None )-> list [str ]: 117"""CMake definitions for sd-cli on `backend`: arch = the CUDA compute capability ("86") or the gfx target.""" 118defs = ["-DSD_BUILD_EXAMPLES=ON" ,"-DSD_WEBP=OFF" ,"-DSD_WEBM=OFF" ,"-DSD_BUILD_SHARED_LIBS=OFF" , 119"-DGGML_NATIVE=ON" ] 120if backend == "cuda" : 121defs += ["-DSD_CUDA=ON" ]+ ([f"-DCMAKE_CUDA_ARCHITECTURES= { arch } " ]if arch else []) 122if cuda_root : 123defs += [f"-DCUDAToolkit_ROOT= { cuda_root } " ] 124elif backend == "hip" : 125if not rocm : 126raise ValueError ("the HIP build needs the ROCm folder" ) 127gfx = str (arch ).split (":" )[0 ] 128llvm = rocm / "lib" / "llvm" if (rocm / "lib" / "llvm" / "bin" ).is_dir ()else rocm / "llvm" 129bitcode = next ((p for p in (llvm / "amdgcn" / "bitcode" ,rocm / "amdgcn" / "bitcode" )if p .is_dir ()), 130llvm / "amdgcn" / "bitcode" ) 131defs += ["-DSD_HIPBLAS=ON" ,f"-DGPU_TARGETS= { gfx } " ,f"-DAMDGPU_TARGETS= { gfx } " , 132f"-DCMAKE_C_COMPILER= { llvm / 'bin' / 'clang' } " ,f"-DCMAKE_CXX_COMPILER= { llvm / 'bin' / 'clang++' } " , 133f"-DCMAKE_HIP_COMPILER= { llvm / 'bin' / 'clang++' } " , 134f"-DCMAKE_PREFIX_PATH= { rocm } ; { rocm / 'lib' / 'rocm_sysdeps' } ; { llvm } " , 135f"-DCMAKE_HIP_FLAGS=--rocm-path= { rocm } --rocm-device-lib-path= { bitcode } " ] 136elif backend == "vulkan" : 137defs += ["-DSD_VULKAN=ON" ] 138elif backend != "cpu" : 139raise ValueError (f"unknown backend { backend !r } " ) 140return defs 141 142 143def unpack_source (third_party :Path ,sd_zip :Path ,ggml_zip :Path )-> Path : 144"""stable-diffusion.cpp's zip with its ggml submodule's zip inside (GitHub's archives leave submodules out) -> 145third_party/stable-diffusion.cpp, stamped with the two commits.""" 146dst = Path (third_party )/ "stable-diffusion.cpp" 147tmp = Path (third_party )/ "_unpack-sd" 148shutil .rmtree (tmp ,ignore_errors = True ) 149for z ,sub in ((sd_zip ,"sd" ), (ggml_zip ,"ggml" )): 150with zipfile .ZipFile (z )as f : 151f .extractall (tmp / sub ) 152top = next ((tmp / "sd" ).iterdir ()) 153gtop = next ((tmp / "ggml" ).iterdir ()) 154shutil .rmtree (top / "ggml" ,ignore_errors = True ) 155shutil .move (str (gtop ),str (top / "ggml" )) 156shutil .rmtree (dst ,ignore_errors = True ) 157shutil .move (str (top ),str (dst )) 158shutil .rmtree (tmp ,ignore_errors = True ) 159 (dst / ".strata-pin" ).write_text (f" { SD_CPP_COMMIT } \n { SD_GGML_COMMIT } \n" ,encoding = "utf-8" ) 160return dst 161 162 163def source_ok (src :Path )-> bool : 164pin = Path (src )/ ".strata-pin" 165return pin .is_file ()and pin .read_text (encoding = "utf-8" ).split ()== [SD_CPP_COMMIT ,SD_GGML_COMMIT ] \ 166and (Path (src )/ "ggml" / "CMakeLists.txt" ).is_file () 167 168 169NATIVE_DIR = Path (__file__ ).resolve ().parent / "sdcpp_native" 170NATIVE_BACKENDS = ("cuda" ,"hip" )# where the native DiT runner (I2) is built in 171 172 173def native_hash ()-> str : 174"""A fingerprint of the native runner's sources (a change compiles sd-cli again).""" 175import hashlib 176h = hashlib .sha256 () 177for f in sorted (NATIVE_DIR .glob ("*" )): 178if f .is_file ()and f .suffix in (".cu" ,".hpp" ,".py" ): 179h .update (f .name .encode ()+ b"\0" + f .read_bytes ().replace (b"\r\n" ,b"\n" )) 180return h .hexdigest ()[:16 ] 181 182 183NOISE_DIR = Path (__file__ ).resolve ().parent / "sdcpp_noise" # Strata's noise generator for sd-cli (every backend) 184NOISE_FILES = ("apply.py" ,"strata_noise.hpp" ,"strata_noise_tables.inc" ,"strata_philox_rng.hpp" ,"strata_sin_exc.bin" ) 185 186 187def noise_hash ()-> str : 188"""A fingerprint of the noise generator's sources (a change compiles sd-cli again, for a build that has it).""" 189import hashlib 190h = hashlib .sha256 () 191for name in NOISE_FILES : 192data = (NOISE_DIR / name ).read_bytes () 193if not name .endswith (".bin" ): 194data = data .replace (b"\r\n" ,b"\n" ) 195h .update (name .encode ()+ b"\0" + data ) 196return h .hexdigest ()[:16 ] 197 198 199VAE_DIR = Path (__file__ ).resolve ().parent / "sdcpp_vae" # Strata's VAE decoder for sd-cli (CUDA / HIP builds) 200VAE_BACKENDS = NATIVE_BACKENDS 201 202 203def vae_hash (repo :Path | None = None )-> str : 204"""A fingerprint of the VAE decoder's sources: apply.py and every file it copies into sd-cli's tree (src/image/vae, 205the headers, include/strata/hip_compat); a change compiles sd-cli again, for a build that has the decoder.""" 206import hashlib 207import importlib .util 208spec = importlib .util .spec_from_file_location ("strata_sdcpp_vae_apply_hash" ,VAE_DIR / "apply.py" ) 209mod = importlib .util .module_from_spec (spec ) 210spec .loader .exec_module (mod ) 211repo = Path (repo )if repo is not None else mod .REPO 212files = [VAE_DIR / "apply.py" ]+ [repo / src for src ,_ in mod .FILES ]+ \ 213sorted (f for f in (repo / mod .HIP_COMPAT ).iterdir ()if f .is_file ()) 214h = hashlib .sha256 () 215for f in files : 216h .update (f .name .encode ()+ b"\0" + f .read_bytes ().replace (b"\r\n" ,b"\n" )) 217return h .hexdigest ()[:16 ] 218 219 220def build_stamp (backend :str ,arch ,noise :bool = False ,vae :bool = False )-> dict : 221"""What a built sd-cli is stamped with (BUILD.json): the pins, the backend and, where it applies, a fingerprint of 222the native runner's sources and, only when the noise generator is asked for (images "noise": "strata"), of the 223noise generator's, and only when Strata's VAE decoder is asked for (images "vae_decoder": "strata", CUDA / HIP), of 224the decoder's: nobody compiles again unasked when they are off.""" 225stamp = {"sd_cpp" :SD_CPP_COMMIT ,"ggml" :SD_GGML_COMMIT ,"backend" :backend ,"arch" :str (arch or "" )} 226if backend in NATIVE_BACKENDS : 227stamp ["native" ]= native_hash () 228if noise : 229stamp ["noise" ]= noise_hash () 230if vae and backend in VAE_BACKENDS : 231stamp ["vae_decoder" ]= vae_hash () 232return stamp 233 234 235def image_config (backend :str ,quant :str ,exe :Path ,models_dir :Path ,* ,uma :bool = False ,gpu = None , 236lib_dirs = (),policy :str = "auto" ,native :bool = False ,noise :bool = False , 237vae :bool = False )-> dict : 238"""The run config's "images" section (serve/images.py reads it).""" 239cfg = {"model_name" :"qwen-image-2.1-turbo" ,"exe" :str (exe ),"backend" :backend ,"quant" :quant , 240"diffusion_model" :str (local_path (models_dir ,quant )),"vae" :str (local_path (models_dir ,"vae" )), 241"llm" :str (local_path (models_dir ,"llm" )),"args" :default_args (backend ),"gpu_policy" :policy , 242"uma" :bool (uma ),"sd_cpp" :SD_CPP_COMMIT [:7 ]} 243if backend in NATIVE_BACKENDS : 244cfg ["native" ]= bool (native )# Strata's DiT runner (--model-args qwen_image_2_1_native=1) 245if noise : 246cfg ["noise" ]= "strata" # Strata's noise generator (--model-args strata_noise=1); absent = "sdcpp" 247if vae and backend in VAE_BACKENDS : 248cfg ["vae_decoder" ]= "strata" # Strata's VAE decoder (--model-args strata_vae=1); absent = "sdcpp" 249if gpu is not None : 250cfg ["gpu" ]= gpu 251if lib_dirs : 252cfg ["lib_dirs" ]= [str (d )for d in lib_dirs ] 253return cfg