mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 07:48:45 +00:00
Image generation: images "vae_decoder" switches sd-cli to Strata's own VAE decoder (CUDA / HIP builds; default stays stable-diffusion.cpp's)
The images section takes "vae_decoder": "sdcpp" (default, also when absent) or "strata". "strata" adds strata_vae=1
to the one --model-args string sd-cli gets (serve/images.py sd_cli_args), next to qwen_image_2_1_native=1 and
strata_noise=1. Hidden flags build it in: setup.py --image-vae on|off and tools/image/install.py --vae on|off, honoured
for cuda and hip only; the sd-cli build stamp gets "vae_decoder" = qimage.vae_hash() (apply.py and every file it
copies, CRLF-neutral), so a build without the switch keeps its stamp and nobody compiles again unasked.
A config that asks for the decoder where it cannot run is refused before sd-cli starts (ImageGen.vae_problem(), also
printed once by the server at start), in the owner's wording of 11-11:
- the sd-cli here was built without it: "Image generation is set to use Strata's own picture decoder ("vae_decoder":
"strata" in the images settings), but the image program here was built without it. Run setup again with: --images
qwen-image --image-vae on"
- another backend: "Image generation is set to use Strata's own picture decoder ("vae_decoder": "strata" in the images
settings), which needs the CUDA (NVIDIA) or ROCm (AMD) build of the image program; this one was built for {backend}.
Set "vae_decoder" to "sdcpp" in the images settings."
- setup --image-vae on for another backend warns and carries on without it: "Strata's own picture decoder runs with
CUDA or ROCm only; image generation on {backend} keeps stable-diffusion.cpp's decoder"
Tests: serve/test_images.py VaeDecoderSwitch, tools/test_qimage.py VaeDecoder (the exact sentences included).
p1004-20261111-0012-8a8a: tools/image/gate, tools/test_sdcpp_vae.py, tools/test_qimage.py, serve/test_images.py
102 passed, 51 subtests passed.
This commit is contained in:
1 parent
97b14b6b06
commit
56630caca0
7 files changed
+263
-11
No files matched your search
+32
-2
@@ -25,7 +25,9 @@ The config's "images" section (written by setup --images, tools/image/install.py
|
||||
"native": false, "noise": "sdcpp"}
|
||||
(native: Strata's own DiT runner, tools/image/sdcpp_native; CUDA / HIP builds. noise: "sdcpp" (default) is
|
||||
stable-diffusion.cpp's own noise; "strata" is Strata's generator, tools/image/sdcpp_noise: the same stream on every
|
||||
operating system and CPU, built into sd-cli by setup --image-noise on)
|
||||
operating system and CPU, built into sd-cli by setup --image-noise on. "vae_decoder": "sdcpp" (default) is
|
||||
stable-diffusion.cpp's VAE decoder; "strata" is Strata's own, src/image/vae via tools/image/sdcpp_vae, CUDA / HIP
|
||||
builds only, built into sd-cli by setup --image-vae on)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -53,6 +55,15 @@ NOISES = ("sdcpp", "strata")
|
||||
# built sd-cli does not have it: ONE next step, in plain words
|
||||
NOISE_MISSING = ("Image generation is set to use Strata's own noise (\"noise\": \"strata\" in the images settings), but "
|
||||
"the image program here was built without it. Run setup again with: --images qwen-image --image-noise on")
|
||||
VAE_DECODERS = ("sdcpp", "strata")
|
||||
VAE_DECODER_BACKENDS = ("cuda", "hip")
|
||||
# the same two cases for Strata's own VAE decoder (the owner's wording, 11-11)
|
||||
VAE_MISSING = ("Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the images "
|
||||
"settings), but the image program here was built without it. Run setup again with: --images qwen-image "
|
||||
"--image-vae on")
|
||||
VAE_BACKEND = ("Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the images "
|
||||
"settings), which needs the CUDA (NVIDIA) or ROCm (AMD) build of the image program; this one was built "
|
||||
"for {backend}. Set \"vae_decoder\" to \"sdcpp\" in the images settings.") # {backend}: as setup prints it
|
||||
SIZE_STEP = 32 # sd.cpp's Qwen-Image-2.1 docs: dimensions divisible by 32
|
||||
MIN_SIDE = 256
|
||||
FILE_NAME = re.compile(r"^[0-9a-f]{32}\.png$")
|
||||
@@ -154,6 +165,8 @@ def sd_cli_args(cfg: dict, job: dict, out_pattern: str, prompt_file: str) -> lis
|
||||
model_args.append("qwen_image_2_1_native=1")
|
||||
if cfg.get("noise") == "strata": # Strata's noise generator inside sd-cli (tools/image/sdcpp_noise)
|
||||
model_args.append("strata_noise=1")
|
||||
if cfg.get("vae_decoder") == "strata": # Strata's VAE decoder inside sd-cli (tools/image/sdcpp_vae)
|
||||
model_args.append("strata_vae=1")
|
||||
if model_args:
|
||||
cmd += ["--model-args", ",".join(model_args)]
|
||||
return cmd
|
||||
@@ -356,6 +369,9 @@ class ImageGen:
|
||||
raise ValueError(f'the config\'s "images" section needs "{k}" (run setup with --images again)')
|
||||
if self.cfg.get("noise", "sdcpp") not in NOISES:
|
||||
raise ValueError(f'images "noise" must be one of {", ".join(NOISES)}, not {self.cfg["noise"]!r}')
|
||||
if self.cfg.get("vae_decoder", "sdcpp") not in VAE_DECODERS:
|
||||
raise ValueError(f'images "vae_decoder" must be one of {", ".join(VAE_DECODERS)}, '
|
||||
f'not {self.cfg["vae_decoder"]!r}')
|
||||
self.policy, self.reload = policy, reload
|
||||
self.model = self.cfg.get("model_name") or MODEL_NAME
|
||||
self.log = log
|
||||
@@ -383,6 +399,20 @@ class ImageGen:
|
||||
return NOISE_MISSING
|
||||
return None if isinstance(meta, dict) and meta.get("noise") else NOISE_MISSING
|
||||
|
||||
def vae_problem(self) -> str | None:
|
||||
"""VAE_BACKEND when the config says "vae_decoder": "strata" for a backend that has no such decoder (Vulkan,
|
||||
CPU), VAE_MISSING when the sd-cli it runs was not built with it (no "vae_decoder" stamp in its BUILD.json);
|
||||
else None. Without this sd-cli would ignore the arg and decode with stable-diffusion.cpp's decoder."""
|
||||
if self.cfg.get("vae_decoder") != "strata":
|
||||
return None
|
||||
if self.cfg.get("backend") not in VAE_DECODER_BACKENDS:
|
||||
return VAE_BACKEND.format(backend=self.cfg.get("backend") or "another backend")
|
||||
try:
|
||||
meta = json.loads(Path(self.cfg["exe"]).with_name("BUILD.json").read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return VAE_MISSING
|
||||
return None if isinstance(meta, dict) and meta.get("vae_decoder") else VAE_MISSING
|
||||
|
||||
def _say(self, text: str) -> None:
|
||||
print(f"[strata] {text}", flush=True)
|
||||
if self.log is not None:
|
||||
@@ -409,7 +439,7 @@ class ImageGen:
|
||||
def run(self, job: dict, cancel: threading.Event | None = None) -> tuple[list[bytes], dict]:
|
||||
"""Run sd-cli for `job` (parse_request's dict) -> (the PNG files' bytes in order, figures). The caller holds
|
||||
the GPU turn. ImageJobFailed when sd-cli fails, times out or is cancelled."""
|
||||
problem = self.noise_problem()
|
||||
problem = self.noise_problem() or self.vae_problem()
|
||||
if problem:
|
||||
self.totals["failed"] += 1
|
||||
raise ImageJobFailed(problem)
|
||||
|
||||
@@ -10242,6 +10242,9 @@ def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> i
|
||||
noise_problem = svc.images.noise_problem()
|
||||
if noise_problem:
|
||||
print(f"[strata] image generation: {noise_problem}", flush=True)
|
||||
vae_problem = svc.images.vae_problem()
|
||||
if vae_problem:
|
||||
print(f"[strata] image generation: {vae_problem}", flush=True)
|
||||
print(f"[strata] image generation: {svc.images.model} {icfg.get('quant') or ''} on "
|
||||
f"{icfg.get('backend') or '?'} (POST /v1/images/generations; GPU policy {svc.images.policy})", flush=True)
|
||||
if cfg.get("prevent_sleep") is not None and not isinstance(cfg["prevent_sleep"], bool):
|
||||
|
||||
@@ -586,5 +586,91 @@ class OverHttp(unittest.TestCase):
|
||||
self.assertGreaterEqual(chat_at, img_at - 0.05)
|
||||
|
||||
|
||||
class VaeDecoderSwitch(unittest.TestCase):
|
||||
"""images "vae_decoder" (OWN-5 step 2): "sdcpp" or absent changes nothing; "strata" adds strata_vae=1 to the one
|
||||
--model-args string; a config that asks for it with an sd-cli built without it, or on a backend without it, is
|
||||
refused before sd-cli starts (the owner's wording of 11-11, see serve/images.py)."""
|
||||
|
||||
def test_the_owners_words(self):
|
||||
self.assertEqual(images_api.VAE_MISSING,
|
||||
"Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the "
|
||||
"images settings), but the image program here was built without it. Run setup again with: "
|
||||
"--images qwen-image --image-vae on")
|
||||
self.assertEqual(images_api.VAE_BACKEND.format(backend="vulkan"),
|
||||
"Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the "
|
||||
"images settings), which needs the CUDA (NVIDIA) or ROCm (AMD) build of the image program; this "
|
||||
"one was built for vulkan. Set \"vae_decoder\" to \"sdcpp\" in the images settings.")
|
||||
|
||||
JOB = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42}
|
||||
BASE = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf",
|
||||
"args": ["--diffusion-fa", "--vae-tiling"]}
|
||||
|
||||
def test_off_leaves_the_command_line_alone(self):
|
||||
for extra in ({}, {"vae_decoder": "sdcpp"}, {"vae_decoder": None}):
|
||||
with self.subTest(extra=extra):
|
||||
self.assertEqual(images_api.sd_cli_args({**self.BASE, **extra}, self.JOB, "o/img_%d.png", "o/prompt.txt"),
|
||||
Command.CARD)
|
||||
|
||||
def test_on_is_one_model_args_string(self):
|
||||
on = {**self.BASE, "vae_decoder": "strata"}
|
||||
self.assertEqual(images_api.sd_cli_args(on, self.JOB, "o/img_%d.png", "o/prompt.txt"),
|
||||
Command.CARD + ["--model-args", "strata_vae=1"])
|
||||
all3 = images_api.sd_cli_args({**on, "native": True, "noise": "strata"}, self.JOB, "o/img_%d.png", "o/prompt.txt")
|
||||
self.assertEqual(all3, Command.CARD + ["--model-args", "qwen_image_2_1_native=1,strata_noise=1,strata_vae=1"])
|
||||
self.assertEqual(all3.count("--model-args"), 1)
|
||||
|
||||
def test_value_is_checked(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "out_dir": d}
|
||||
for ok in ("sdcpp", "strata"):
|
||||
images_api.ImageGen({**cfg, "vae_decoder": ok})
|
||||
for bad in ("on", "", "Strata", True, 1):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
||||
images_api.ImageGen({**cfg, "vae_decoder": bad})
|
||||
|
||||
def gen(self, d, build=None, backend="cuda"):
|
||||
cfg = image_cfg(d, vae_decoder="strata", backend=backend)
|
||||
exe = Path(d) / "engine-image" / "sd-cli"
|
||||
exe.parent.mkdir(exist_ok=True)
|
||||
exe.write_bytes(b"x")
|
||||
cfg["exe"] = str(exe)
|
||||
if build is not None:
|
||||
(exe.parent / "BUILD.json").write_text(build if isinstance(build, str) else json.dumps(build))
|
||||
return images_api.ImageGen(cfg)
|
||||
|
||||
def test_problem_by_build_json_and_backend(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.assertEqual(self.gen(d).vae_problem(), images_api.VAE_MISSING) # no BUILD.json
|
||||
for build in ({"sd_cpp": "x", "backend": "cuda"}, {"vae_decoder": ""}, "not json", "[1]", "{",
|
||||
{"noise": "0123456789abcdef"}):
|
||||
with self.subTest(build=build), tempfile.TemporaryDirectory() as d:
|
||||
self.assertEqual(self.gen(d, build).vae_problem(), images_api.VAE_MISSING)
|
||||
for backend in ("cuda", "hip"):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.assertIsNone(self.gen(d, {"vae_decoder": "0123456789abcdef"}, backend).vae_problem())
|
||||
for backend in ("vulkan", "cpu", "metal", None):
|
||||
with self.subTest(backend=backend), tempfile.TemporaryDirectory() as d:
|
||||
said = self.gen(d, {"vae_decoder": "0123456789abcdef"}, backend).vae_problem()
|
||||
self.assertEqual(said, images_api.VAE_BACKEND.format(backend=backend or "another backend"))
|
||||
self.assertIn(f"this one was built for {backend or 'another backend'}.", said)
|
||||
|
||||
def test_switch_off_asks_nothing(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for extra in ({}, {"vae_decoder": "sdcpp"}):
|
||||
self.assertIsNone(images_api.ImageGen({**image_cfg(d), **extra}).vae_problem())
|
||||
|
||||
def test_a_job_is_refused_before_sd_cli_starts(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
g = self.gen(d)
|
||||
job = images_api.parse_request({"prompt": "a cat"}, {})
|
||||
before = sorted(p.name for p in g.dir.iterdir())
|
||||
with mock.patch("serve.lifeline.popen") as popen, self.assertRaises(images_api.ImageJobFailed) as cm:
|
||||
g.run(job)
|
||||
popen.assert_not_called()
|
||||
self.assertEqual(str(cm.exception), images_api.VAE_MISSING)
|
||||
self.assertEqual(sorted(p.name for p in g.dir.iterdir()), before)
|
||||
self.assertEqual(g.totals["failed"], 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5466,7 +5466,18 @@ def apply_noise_generator(src: Path) -> None:
|
||||
mod.apply(src)
|
||||
|
||||
|
||||
def build_image_engine(backend: str, gpu: dict, noise: bool = False) -> tuple[Path, list[str]]:
|
||||
def apply_vae_decoder(src: Path) -> None:
|
||||
"""OWN-5 step 2: Strata's VAE decoder (src/image/vae via tools/image/sdcpp_vae) into the stable-diffusion.cpp
|
||||
source (idempotent; CUDA / HIP builds; sd-cli uses it only with --model-args strata_vae=1)."""
|
||||
import importlib.util
|
||||
QI = _qimage()
|
||||
spec = importlib.util.spec_from_file_location("strata_sdcpp_vae_apply", QI.VAE_DIR / "apply.py")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
mod.apply(src)
|
||||
|
||||
|
||||
def build_image_engine(backend: str, gpu: dict, noise: bool = False, vae: bool = False) -> tuple[Path, list[str]]:
|
||||
"""Compile sd-cli for `backend` into engine-image/ (again only when the pins or the backend changed, or, with
|
||||
`noise`, the noise generator's sources) -> (its path, the library folders it runs with). `noise`: Strata's noise
|
||||
generator is patched in (images "noise": "strata"); off, the build and its stamp are what they always were."""
|
||||
@@ -5474,7 +5485,8 @@ def build_image_engine(backend: str, gpu: dict, noise: bool = False) -> tuple[Pa
|
||||
IMAGE_ENGINE.mkdir(exist_ok=True)
|
||||
exe, stamp = IMAGE_ENGINE / QI.SD_EXE, IMAGE_ENGINE / "BUILD.json"
|
||||
arch = gpu.get("arch") if backend in ("cuda", "hip") else None
|
||||
want = QI.build_stamp(backend, arch, noise)
|
||||
vae = vae and backend in QI.VAE_BACKENDS
|
||||
want = QI.build_stamp(backend, arch, noise, vae)
|
||||
meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {}
|
||||
lib_dirs = [d for d in meta.get("lib_dirs") or [] if Path(d).is_dir()]
|
||||
if exe.exists() and {k: meta.get(k) for k in want} == want:
|
||||
@@ -5485,6 +5497,8 @@ def build_image_engine(backend: str, gpu: dict, noise: bool = False) -> tuple[Pa
|
||||
apply_native_runner(src)
|
||||
if noise: # Strata's noise generator (inert unless the config asks for it)
|
||||
apply_noise_generator(src)
|
||||
if vae: # Strata's VAE decoder (inert unless the config asks for it)
|
||||
apply_vae_decoder(src)
|
||||
vcvars, lib_dirs = None, []
|
||||
if backend == "cuda":
|
||||
nvcc, cuda_v = find_nvcc()
|
||||
@@ -5561,7 +5575,12 @@ def setup_images(a, gpu: dict, hip: bool, models_dir: Path) -> dict | None:
|
||||
if free_gb(models_dir) < need + 5:
|
||||
warn(f"less than {need + 5:.0f} GB free for the image model: the download may run out of disk space")
|
||||
noise = getattr(a, "image_noise", None) == "on"
|
||||
exe, lib_dirs = build_image_engine(backend, gpu or {}, noise)
|
||||
vae = getattr(a, "image_vae", None) == "on"
|
||||
if vae and backend not in QI.VAE_BACKENDS: # the owner's wording, 11-11
|
||||
warn(f"Strata's own picture decoder runs with CUDA or ROCm only; image generation on {backend} keeps "
|
||||
"stable-diffusion.cpp's decoder")
|
||||
vae = False
|
||||
exe, lib_dirs = build_image_engine(backend, gpu or {}, noise, vae)
|
||||
for name in (quant, "vae", "llm"):
|
||||
repo, path, size, sha = QI.FILES[name]
|
||||
dst = QI.local_path(models_dir, name)
|
||||
@@ -5569,7 +5588,7 @@ def setup_images(a, gpu: dict, hip: bool, models_dir: Path) -> dict | None:
|
||||
verify_sha256(dst, size, sha)
|
||||
cfg = QI.image_config(backend, quant, exe, models_dir, uma=QI.is_apu(gpu), lib_dirs=lib_dirs,
|
||||
policy=a.image_gpu_policy or "auto", native=getattr(a, "image_native", None) == "on",
|
||||
noise=noise)
|
||||
noise=noise, vae=vae)
|
||||
ok(f"image generation: {quant} on {backend}, GPU policy {cfg['gpu_policy']}")
|
||||
return cfg
|
||||
|
||||
@@ -10210,6 +10229,8 @@ def main() -> int:
|
||||
help=argparse.SUPPRESS)
|
||||
ap.add_argument("--image-noise", choices=["on", "off"],
|
||||
help=argparse.SUPPRESS)
|
||||
ap.add_argument("--image-vae", choices=["on", "off"],
|
||||
help=argparse.SUPPRESS)
|
||||
ap.add_argument("--image-gpu-policy", choices=["auto", "keep", "shrink", "unload"],
|
||||
help=argparse.SUPPRESS)
|
||||
ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF",
|
||||
|
||||
@@ -54,6 +54,7 @@ def main(argv=None) -> int:
|
||||
ap.add_argument("--native", choices=["on", "off"], default="off",
|
||||
help="EXPERIMENTAL: Strata's own DiT runner on CUDA / HIP (the config's \"native\")")
|
||||
ap.add_argument("--noise", choices=["on", "off"], default="off", help=argparse.SUPPRESS)
|
||||
ap.add_argument("--vae", choices=["on", "off"], default="off", help=argparse.SUPPRESS)
|
||||
ap.add_argument("--build-only", action="store_true", help="compile sd-cli only")
|
||||
ap.add_argument("--print", action="store_true", help="print the images section instead of writing it")
|
||||
ap.add_argument("--yes", action="store_true")
|
||||
@@ -71,7 +72,7 @@ def main(argv=None) -> int:
|
||||
if backend in ("cuda", "hip") and not gpu.get("arch"):
|
||||
S.fail(f"the {backend} build needs the GPU's architecture", "pass --arch (e.g. 86 or gfx1103)")
|
||||
S.ok(f"image generation: {quant} on {backend}" + (f" ({gb:.0f} GB GPU memory)" if gb else ""))
|
||||
exe, lib_dirs = S.build_image_engine(backend, gpu, a.noise == "on")
|
||||
exe, lib_dirs = S.build_image_engine(backend, gpu, a.noise == "on", a.vae == "on")
|
||||
if a.build_only:
|
||||
return 0
|
||||
if a.models_dir:
|
||||
@@ -86,7 +87,8 @@ def main(argv=None) -> int:
|
||||
S.download(QI.file_url(name, S.hf_endpoint()), dst, f"image model: {Path(path).name}")
|
||||
S.verify_sha256(dst, size, sha)
|
||||
section = QI.image_config(backend, quant, exe, models, uma=QI.is_apu(gpu), gpu=a.gpu, lib_dirs=lib_dirs,
|
||||
policy=a.gpu_policy, native=a.native == "on", noise=a.noise == "on")
|
||||
policy=a.gpu_policy, native=a.native == "on", noise=a.noise == "on",
|
||||
vae=a.vae == "on")
|
||||
if a.print or not a.config:
|
||||
print(json.dumps({"images": section}, indent=1))
|
||||
return 0
|
||||
|
||||
+30
-3
@@ -196,20 +196,45 @@ def noise_hash() -> str:
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def build_stamp(backend: str, arch, noise: bool = False) -> dict:
|
||||
VAE_DIR = Path(__file__).resolve().parent / "sdcpp_vae" # Strata's VAE decoder for sd-cli (CUDA / HIP builds)
|
||||
VAE_BACKENDS = NATIVE_BACKENDS
|
||||
|
||||
|
||||
def vae_hash(repo: Path | None = None) -> str:
|
||||
"""A fingerprint of the VAE decoder's sources: apply.py and every file it copies into sd-cli's tree (src/image/vae,
|
||||
the headers, include/strata/hip_compat); a change compiles sd-cli again, for a build that has the decoder."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location("strata_sdcpp_vae_apply_hash", VAE_DIR / "apply.py")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
repo = Path(repo) if repo is not None else mod.REPO
|
||||
files = [VAE_DIR / "apply.py"] + [repo / src for src, _ in mod.FILES] + \
|
||||
sorted(f for f in (repo / mod.HIP_COMPAT).iterdir() if f.is_file())
|
||||
h = hashlib.sha256()
|
||||
for f in files:
|
||||
h.update(f.name.encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n"))
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def build_stamp(backend: str, arch, noise: bool = False, vae: bool = False) -> dict:
|
||||
"""What a built sd-cli is stamped with (BUILD.json): the pins, the backend and, where it applies, a fingerprint of
|
||||
the native runner's sources and, only when the noise generator is asked for (images "noise": "strata"), of the
|
||||
noise generator's: nobody compiles again unasked when the noise generator is off."""
|
||||
noise generator's, and only when Strata's VAE decoder is asked for (images "vae_decoder": "strata", CUDA / HIP), of
|
||||
the decoder's: nobody compiles again unasked when they are off."""
|
||||
stamp = {"sd_cpp": SD_CPP_COMMIT, "ggml": SD_GGML_COMMIT, "backend": backend, "arch": str(arch or "")}
|
||||
if backend in NATIVE_BACKENDS:
|
||||
stamp["native"] = native_hash()
|
||||
if noise:
|
||||
stamp["noise"] = noise_hash()
|
||||
if vae and backend in VAE_BACKENDS:
|
||||
stamp["vae_decoder"] = vae_hash()
|
||||
return stamp
|
||||
|
||||
|
||||
def image_config(backend: str, quant: str, exe: Path, models_dir: Path, *, uma: bool = False, gpu=None,
|
||||
lib_dirs=(), policy: str = "auto", native: bool = False, noise: bool = False) -> dict:
|
||||
lib_dirs=(), policy: str = "auto", native: bool = False, noise: bool = False,
|
||||
vae: bool = False) -> dict:
|
||||
"""The run config's "images" section (serve/images.py reads it)."""
|
||||
cfg = {"model_name": "qwen-image-2.1-turbo", "exe": str(exe), "backend": backend, "quant": quant,
|
||||
"diffusion_model": str(local_path(models_dir, quant)), "vae": str(local_path(models_dir, "vae")),
|
||||
@@ -219,6 +244,8 @@ def image_config(backend: str, quant: str, exe: Path, models_dir: Path, *, uma:
|
||||
cfg["native"] = bool(native) # Strata's DiT runner (--model-args qwen_image_2_1_native=1)
|
||||
if noise:
|
||||
cfg["noise"] = "strata" # Strata's noise generator (--model-args strata_noise=1); absent = "sdcpp"
|
||||
if vae and backend in VAE_BACKENDS:
|
||||
cfg["vae_decoder"] = "strata" # Strata's VAE decoder (--model-args strata_vae=1); absent = "sdcpp"
|
||||
if gpu is not None:
|
||||
cfg["gpu"] = gpu
|
||||
if lib_dirs:
|
||||
|
||||
@@ -287,5 +287,88 @@ class Noise(unittest.TestCase):
|
||||
an.assert_not_called()
|
||||
|
||||
|
||||
class VaeDecoder(unittest.TestCase):
|
||||
"""OWN-5 step 2: Strata's VAE decoder for sd-cli (tools/image/sdcpp_vae, CUDA / HIP builds): off by default; nobody
|
||||
compiles again unasked; another backend never gets it."""
|
||||
|
||||
def test_stamp_without_the_switch_is_what_it_was(self):
|
||||
for backend, arch in (("cuda", 86), ("hip", "gfx1201"), ("vulkan", None), ("cpu", None)):
|
||||
self.assertEqual(QI.build_stamp(backend, arch, False, False), QI.build_stamp(backend, arch))
|
||||
self.assertNotIn("vae_decoder", QI.build_stamp(backend, arch, True))
|
||||
|
||||
def test_stamp_with_the_switch(self):
|
||||
for backend, arch in (("cuda", 86), ("hip", "gfx1201")):
|
||||
s = QI.build_stamp(backend, arch, False, True)
|
||||
self.assertEqual(s["vae_decoder"], QI.vae_hash())
|
||||
self.assertEqual({k: v for k, v in s.items() if k != "vae_decoder"}, QI.build_stamp(backend, arch))
|
||||
self.assertEqual(QI.build_stamp(backend, arch, True, True)["noise"], QI.noise_hash())
|
||||
for backend in ("vulkan", "cpu"):
|
||||
self.assertEqual(QI.build_stamp(backend, None, False, True), QI.build_stamp(backend, None))
|
||||
|
||||
def test_vae_hash_follows_the_decoder_sources(self):
|
||||
h = QI.vae_hash()
|
||||
self.assertRegex(h, r"^[0-9a-f]{16}$")
|
||||
self.assertEqual(QI.vae_hash(), h)
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location("strata_sdcpp_vae_apply_qtest", QI.VAE_DIR / "apply.py")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for src, _ in mod.FILES:
|
||||
(Path(d) / src).parent.mkdir(parents=True, exist_ok=True)
|
||||
(Path(d) / src).write_bytes((ROOT / src).read_bytes())
|
||||
(Path(d) / mod.HIP_COMPAT).mkdir(parents=True, exist_ok=True)
|
||||
for f in (ROOT / mod.HIP_COMPAT).iterdir():
|
||||
(Path(d) / mod.HIP_COMPAT / f.name).write_bytes(f.read_bytes().replace(b"\n", b"\r\n"))
|
||||
self.assertEqual(QI.vae_hash(Path(d)), h) # a CRLF checkout: the same hash
|
||||
p = Path(d) / "src" / "image" / "vae" / "wan_vae.cu"
|
||||
p.write_bytes(p.read_bytes() + b"// edit\n")
|
||||
self.assertNotEqual(QI.vae_hash(Path(d)), h)
|
||||
|
||||
def test_config(self):
|
||||
c = QI.image_config("cuda", "Q8_0", Path("/e/sd-cli"), Path("/m"), vae=True)
|
||||
self.assertEqual(c["vae_decoder"], "strata")
|
||||
self.assertTrue(c["vae"].endswith("qwen_image_2.1_vae_bf16.safetensors")) # the file path is untouched
|
||||
self.assertNotIn("vae_decoder", QI.image_config("cuda", "Q8_0", Path("/e/sd-cli"), Path("/m")))
|
||||
self.assertNotIn("vae_decoder", QI.image_config("vulkan", "Q4_K_M", Path("/e/sd-cli"), Path("/m"), vae=True))
|
||||
from serve.images import ImageGen
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
ImageGen({**c, "out_dir": d}) # serve accepts what setup writes
|
||||
|
||||
def test_flags(self):
|
||||
self.assertRegex((ROOT / "setup.py").read_text(encoding="utf-8"), re.escape('ap.add_argument("--image-vae"'))
|
||||
self.assertIn('warn(f"Strata\'s own picture decoder runs with CUDA or ROCm only; image generation on {backend} keeps "\n'
|
||||
' "stable-diffusion.cpp\'s decoder")',
|
||||
(ROOT / "setup.py").read_text(encoding="utf-8")) # the owner's wording of 11-11
|
||||
self.assertRegex((ROOT / "tools" / "image" / "install.py").read_text(encoding="utf-8"),
|
||||
re.escape('ap.add_argument("--vae"'))
|
||||
|
||||
def test_build_decisions(self):
|
||||
def stamp_file(d, stamp):
|
||||
(Path(d) / QI.SD_EXE).write_bytes(b"x")
|
||||
(Path(d) / "BUILD.json").write_text(json.dumps({**stamp, "lib_dirs": [d]}))
|
||||
|
||||
def build_until_nvcc(*args):
|
||||
with mock.patch.object(setup, "get_sd_cpp"), mock.patch.object(setup, "apply_native_runner"), \
|
||||
mock.patch.object(setup, "apply_noise_generator"), \
|
||||
mock.patch.object(setup, "apply_vae_decoder") as av, \
|
||||
mock.patch.object(setup, "find_nvcc", return_value=(None, None)):
|
||||
with self.assertRaises(SystemExit): # stops at "no nvcc", after the patches
|
||||
quiet(setup.build_image_engine, *args)
|
||||
return av
|
||||
with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "IMAGE_ENGINE", Path(d)):
|
||||
stamp_file(d, QI.build_stamp("cuda", 86)) # a build made before the switch existed
|
||||
with mock.patch.object(setup, "cmake_build") as cb:
|
||||
quiet(setup.build_image_engine, "cuda", {"arch": 86}, False, False)
|
||||
cb.assert_not_called()
|
||||
build_until_nvcc("cuda", {"arch": 86}, False, True).assert_called_once() # switched on: rebuilt
|
||||
stamp_file(d, QI.build_stamp("cuda", 86, False, True))
|
||||
with mock.patch.object(setup, "cmake_build") as cb:
|
||||
quiet(setup.build_image_engine, "cuda", {"arch": 86}, False, True)
|
||||
quiet(setup.build_image_engine, "cuda", {"arch": 86}, False, False) # off again: kept (inert)
|
||||
cb.assert_not_called()
|
||||
build_until_nvcc("cuda", {"arch": 89}, False, False).assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user