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
13.0 KiB253 linesraw
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
6  backend   CUDA on an NVIDIA card, HIP on an AMD card with its own memory (Linux), Vulkan on an APU/iGPU (AMD's shared
7            memory: the HIP path's queue evictions reset a 780M on current firmware, NEW-MODELS-PLAN.md section 4),
8            on Intel and on AMD under Windows; CPU without a GPU.  --image-backend picks another.
9  files     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
10            LPIPS vs bf16: 0.153 / 0.055 / 0.036); the VAE (bf16); the Qwen3-VL-8B text encoder UD-Q4_K_XL (the
11            model card's choice).  Each file is checked against the SHA-256 the Hugging Face API lists for it at the
12            pinned revision.
13  defaults  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)
15            with --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/"
33                  f"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."""
67    if gpu_gb <= 8:
68        return "Q4_K_M"
69    if gpu_gb <= 12:
70        return "Q6_K"
71    return "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
82    text engine supports)."""
83    if not gpu:
84        return False
85    return 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."""
90    if not gpu:
91        return "cpu"
92    vendor = (gpu.get("vendor") or "nvidia").lower()
93    if vendor == "nvidia":
94        return "cuda"
95    if vendor == "amd":
96        return "vulkan" if is_apu(gpu) or win else "hip"
97    return "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)
104    return ["--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:
108    repo, path, _, _ = FILES[name]
109    return f"{endpoint.rstrip('/')}/{repo}/resolve/{REVISIONS[repo]}/{path}"
110
111
112def local_path(models_dir: Path, name: str) -> Path:
113    return 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."""
118    defs = ["-DSD_BUILD_EXAMPLES=ON", "-DSD_WEBP=OFF", "-DSD_WEBM=OFF", "-DSD_BUILD_SHARED_LIBS=OFF",
119            "-DGGML_NATIVE=ON"]
120    if backend == "cuda":
121        defs += ["-DSD_CUDA=ON"] + ([f"-DCMAKE_CUDA_ARCHITECTURES={arch}"] if arch else [])
122        if cuda_root:
123            defs += [f"-DCUDAToolkit_ROOT={cuda_root}"]
124    elif backend == "hip":
125        if not rocm:
126            raise ValueError("the HIP build needs the ROCm folder")
127        gfx = str(arch).split(":")[0]
128        llvm = rocm / "lib" / "llvm" if (rocm / "lib" / "llvm" / "bin").is_dir() else rocm / "llvm"
129        bitcode = next((p for p in (llvm / "amdgcn" / "bitcode", rocm / "amdgcn" / "bitcode") if p.is_dir()),
130                       llvm / "amdgcn" / "bitcode")
131        defs += ["-DSD_HIPBLAS=ON", f"-DGPU_TARGETS={gfx}", f"-DAMDGPU_TARGETS={gfx}",
132                 f"-DCMAKE_C_COMPILER={llvm / 'bin' / 'clang'}", f"-DCMAKE_CXX_COMPILER={llvm / 'bin' / 'clang++'}",
133                 f"-DCMAKE_HIP_COMPILER={llvm / 'bin' / 'clang++'}",
134                 f"-DCMAKE_PREFIX_PATH={rocm};{rocm / 'lib' / 'rocm_sysdeps'};{llvm}",
135                 f"-DCMAKE_HIP_FLAGS=--rocm-path={rocm} --rocm-device-lib-path={bitcode}"]
136    elif backend == "vulkan":
137        defs += ["-DSD_VULKAN=ON"]
138    elif backend != "cpu":
139        raise ValueError(f"unknown backend {backend!r}")
140    return 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) ->
145    third_party/stable-diffusion.cpp, stamped with the two commits."""
146    dst = Path(third_party) / "stable-diffusion.cpp"
147    tmp = Path(third_party) / "_unpack-sd"
148    shutil.rmtree(tmp, ignore_errors=True)
149    for z, sub in ((sd_zip, "sd"), (ggml_zip, "ggml")):
150        with zipfile.ZipFile(z) as f:
151            f.extractall(tmp / sub)
152    top = next((tmp / "sd").iterdir())
153    gtop = next((tmp / "ggml").iterdir())
154    shutil.rmtree(top / "ggml", ignore_errors=True)
155    shutil.move(str(gtop), str(top / "ggml"))
156    shutil.rmtree(dst, ignore_errors=True)
157    shutil.move(str(top), str(dst))
158    shutil.rmtree(tmp, ignore_errors=True)
159    (dst / ".strata-pin").write_text(f"{SD_CPP_COMMIT}\n{SD_GGML_COMMIT}\n", encoding="utf-8")
160    return dst
161
162
163def source_ok(src: Path) -> bool:
164    pin = Path(src) / ".strata-pin"
165    return pin.is_file() and pin.read_text(encoding="utf-8").split() == [SD_CPP_COMMIT, SD_GGML_COMMIT] \
166        and (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)."""
175    import hashlib
176    h = hashlib.sha256()
177    for f in sorted(NATIVE_DIR.glob("*")):
178        if f.is_file() and f.suffix in (".cu", ".hpp", ".py"):
179            h.update(f.name.encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n"))
180    return 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)."""
189    import hashlib
190    h = hashlib.sha256()
191    for name in NOISE_FILES:
192        data = (NOISE_DIR / name).read_bytes()
193        if not name.endswith(".bin"):
194            data = data.replace(b"\r\n", b"\n")
195        h.update(name.encode() + b"\0" + data)
196    return 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,
205    the headers, include/strata/hip_compat); a change compiles sd-cli again, for a build that has the decoder."""
206    import hashlib
207    import importlib.util
208    spec = importlib.util.spec_from_file_location("strata_sdcpp_vae_apply_hash", VAE_DIR / "apply.py")
209    mod = importlib.util.module_from_spec(spec)
210    spec.loader.exec_module(mod)
211    repo = Path(repo) if repo is not None else mod.REPO
212    files = [VAE_DIR / "apply.py"] + [repo / src for src, _ in mod.FILES] + \
213        sorted(f for f in (repo / mod.HIP_COMPAT).iterdir() if f.is_file())
214    h = hashlib.sha256()
215    for f in files:
216        h.update(f.name.encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n"))
217    return 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
222    the native runner's sources and, only when the noise generator is asked for (images "noise": "strata"), of the
223    noise generator's, and only when Strata's VAE decoder is asked for (images "vae_decoder": "strata", CUDA / HIP), of
224    the decoder's: nobody compiles again unasked when they are off."""
225    stamp = {"sd_cpp": SD_CPP_COMMIT, "ggml": SD_GGML_COMMIT, "backend": backend, "arch": str(arch or "")}
226    if backend in NATIVE_BACKENDS:
227        stamp["native"] = native_hash()
228    if noise:
229        stamp["noise"] = noise_hash()
230    if vae and backend in VAE_BACKENDS:
231        stamp["vae_decoder"] = vae_hash()
232    return stamp
233
234
235def image_config(backend: str, quant: str, exe: Path, models_dir: Path, *, uma: bool = False, gpu=None,
236                 lib_dirs=(), policy: str = "auto", native: bool = False, noise: bool = False,
237                 vae: bool = False) -> dict:
238    """The run config's "images" section (serve/images.py reads it)."""
239    cfg = {"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]}
243    if backend in NATIVE_BACKENDS:
244        cfg["native"] = bool(native)       # Strata's DiT runner (--model-args qwen_image_2_1_native=1)
245    if noise:
246        cfg["noise"] = "strata"            # Strata's noise generator (--model-args strata_noise=1); absent = "sdcpp"
247    if vae and backend in VAE_BACKENDS:
248        cfg["vae_decoder"] = "strata"      # Strata's VAE decoder (--model-args strata_vae=1); absent = "sdcpp"
249    if gpu is not None:
250        cfg["gpu"] = gpu
251    if lib_dirs:
252        cfg["lib_dirs"] = [str(d) for d in lib_dirs]
253    return cfg