Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Image generation: Qwen-Image-2.1-Turbo through stable-diffusion.cpp (POST /v1/images/generations)
Niko1221a5b3b6c27b56
diff --git a/docs/IMAGES.md b/docs/IMAGES.mdnew file mode 100644index 000000000..7f6273554--- /dev/null+++ b/docs/IMAGES.md@@ -0,0 +1,79 @@+# Image generation (Qwen-Image-2.1-Turbo)++Strata's server can also make images: `POST /v1/images/generations`, OpenAI's images API. The model is+[Qwen-Image-2.1-Turbo](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo) (8 steps, CFG 1) in+[Unsloth's GGUF quants](https://huggingface.co/unsloth/Qwen-Image-2.1-Turbo-GGUF), run by+[stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) (`sd-cli`), which setup compiles for your GPU.+It is optional and off unless you ask for it.++The model is under the **Qwen Research License**, not Apache 2.0: read+[its license](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo/blob/main/LICENSE) before you use the images+commercially.++## Set it up++ ./setup.sh --setup --images qwen-image (Linux)+ START-HERE.bat --setup --images qwen-image (Windows)++or, for an install that is already set up, without running the whole setup again:++ .venv/bin/python tools/image/install.py --config strata-<model>.json++Setup compiles `sd-cli` (stable-diffusion.cpp at a pinned commit) into `engine-image/`, downloads three files into+the data folder's `models/qwen-image-2.1-turbo/` and checks each against its SHA-256, and writes an `"images"` section+into the model's run config.++| piece | file | size |+|---|---|---|+| denoiser (by GPU memory) | `qwen-image-2.1-turbo-Q4_K_M.gguf` up to 8 GB, `Q6_K` up to 12 GB, `Q8_0` above | 4.2 / 6.3 / 7.6 GB |+| text encoder | `Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf` | 5.1 GB |+| VAE | `qwen_image_2.1_vae_bf16.safetensors` | 0.7 GB |++Options: `--image-quant Q4_K_M|Q6_K|Q8_0` (a bigger one than recommended is kept, with a warning),+`--image-backend cuda|hip|vulkan|cpu`, `--image-gpu-policy auto|keep|shrink|unload`, `--images no` (takes the section+out of the config).++Backends: CUDA on NVIDIA (needs the CUDA Toolkit), HIP on AMD cards with their own memory (Linux, the same ROCm as the+engine), Vulkan on AMD APUs/iGPUs (Radeon 780M, Strix Point/Halo), Intel Arc and AMD under Windows. A Linux PC without+the Vulkan development files gets the LunarG Vulkan SDK unpacked into `third_party/` (no sudo); on Windows install the+Vulkan SDK first. On Vulkan setup adds `--vae-tiling`: an untiled 1024x1024 VAE decode on a Radeon 780M is one GPU+job long enough to trip the kernel driver's job timeout (no image).++## Use it++ curl http://127.0.0.1:8080/v1/images/generations -H "Content-Type: application/json" \+ -d '{"prompt": "a cartoon sloth mascot waving, flat vector illustration", "size": "1024x1024", "seed": 42}'++| field | |+|---|---|+| `prompt` | the description (required) |+| `size` | `WIDTHxHEIGHT`, each side a multiple of 32 from 256 to 2048 (`max_side`); default and `auto`: `1024x1024` |+| `n` | images, 1 to 4 (`max_n`); image *i* uses seed + *i* |+| `response_format` | `b64_json` (default) or `url` (`/v1/images/files/<random name>.png`; the server keeps the newest 64) |+| `seed` | Strata's: a whole number for a repeatable image (default: random; the answer says which) |+| `steps` | Strata's: 8 (Turbo's schedule). Another count uses stable-diffusion.cpp's own schedule, which Turbo was not made for |++The answer is OpenAI's shape (`created`, `data[].b64_json` or `data[].url`, `revised_prompt` = the prompt) plus+`data[].seed` and a `strata` object with the seconds, steps and backend. The settings are the model card's for+stable-diffusion.cpp: 8 steps, CFG 1, euler, Turbo's own sigmas, `--diffusion-fa`. An image from the API is the PNG+plain `sd-cli` writes with the same arguments, byte for byte.++## Sharing the GPU with the text model++One job at a time: an image job takes the same turn a chat request takes, so a chat request waits for the image and+the other way round. What the text model does meanwhile is the config's `images.gpu_policy`:++| policy | the text model during an image job |+|---|---|+| `auto` (default) | `keep` when the image job fits next to it (an APU always), else `shrink` when the engine was started with `--vram-elastic`, else `unload` |+| `keep` | stays loaded and idle |+| `shrink` | gives VRAM from its expert cache (as `POST /v1/vram`) and takes it back afterwards; the conversation stays |+| `unload` | its conversation is saved to a file, the engine is stopped, and the next start restores the conversation (`"reload": "eager"` starts it again right after the image; default `lazy`: with the next chat request) |++Each image runs its own `sd-cli` process, so no image memory stays on the GPU between images. Loading the three+files takes a few seconds per image from the page cache.++## Speed++Seconds per 1024x1024 image (8 steps) measured in the I1 tests are in `phaseA-tests/notes-qimage.md`+(Radeon 780M: HIP Q8_0 ~131 s, Vulkan Q8_0 ~200 s with `--vae-tiling`).diff --git a/serve/fixtures/fake_sd_cli.py b/serve/fixtures/fake_sd_cli.pynew file mode 100644index 000000000..3dd80a6b0--- /dev/null+++ b/serve/fixtures/fake_sd_cli.py@@ -0,0 +1,57 @@+"""A stand-in for stable-diffusion.cpp's sd-cli (serve/test_images.py): reads the arguments serve/images.py passes and+writes one small PNG per image whose pixels encode the seed, size and prompt, so a test can tell the images apart.+FAKE_SD_FAIL=1: exits 1 after a log line. FAKE_SD_SLEEP=<s>: waits that long first (cancel tests).+FAKE_SD_ARGS=<file>: writes its argument list there (JSON)."""+import hashlib+import json+import os+import struct+import sys+import time+import zlib+++def png(w: int, h: int, seed: int, text: str) -> bytes:+ digest = hashlib.sha256(f"{seed}|{w}x{h}|{text}".encode()).digest()+ row = b"\x00" + digest[:3] * 4+ raw = row * 4+ def chunk(t, d):+ return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 2, 0, 0, 0))+ + chunk(b"tEXt", f"parameters\x00{text}, Seed: {seed}, Size: {w}x{h}".encode("latin-1", "replace"))+ + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))+++def main(argv):+ a = {}+ i = 0+ while i < len(argv):+ if argv[i].startswith("-") and i + 1 < len(argv) and not argv[i + 1].startswith("--"):+ a[argv[i]] = argv[i + 1]+ i += 2+ else:+ a[argv[i]] = True+ i += 1+ if os.environ.get("FAKE_SD_ARGS"):+ with open(os.environ["FAKE_SD_ARGS"], "w", encoding="utf-8") as f:+ json.dump(argv, f)+ time.sleep(float(os.environ.get("FAKE_SD_SLEEP") or 0))+ print("[INFO ] loading tensors completed, taking 0.10s", flush=True)+ if os.environ.get("FAKE_SD_FAIL"):+ print("[ERROR] ggml_vulkan: ErrorDeviceLost", flush=True)+ return 1+ steps = int(a.get("--steps", 20))+ for s in range(1, steps + 1):+ print(f" |{'=' * s}| {s}/{steps} - 0.01s/it", flush=True)+ print("[INFO ] get_learned_condition completed, taking 12 ms", flush=True)+ print("[INFO ] sampling completed, taking 0.08s", flush=True)+ print("[INFO ] decode_first_stage completed, taking 0.02s", flush=True)+ w, h, seed, n = int(a["-W"]), int(a["-H"]), int(a["-s"]), int(a.get("-b", 1))+ for k in range(n):+ with open(a["-o"] % k, "wb") as f:+ f.write(png(w, h, seed + k, a["-p"]))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/serve/images.py b/serve/images.pynew file mode 100644index 000000000..de155286c--- /dev/null+++ b/serve/images.py@@ -0,0 +1,468 @@+"""serve/images.py - image generation (Qwen-Image-2.1-Turbo) through stable-diffusion.cpp's sd-cli.++POST /v1/images/generations takes OpenAI's request shape (prompt, size, n, response_format b64_json|url) plus Strata's+own fields seed and steps. Each request runs one `sd-cli` process with the arguments the model's card gives for+stable-diffusion.cpp (8 steps, CFG 1, euler, Turbo's sigmas, --diffusion-fa) and returns the PNG files that process+wrote, unchanged: an image from the API is byte for byte the image plain sd-cli writes with the same arguments.++The GPU is shared with the text engine one job at a time: an image job takes the service's turn (the FIFO every chat+request takes), so no chat turn runs on the GPU meanwhile, and the config's "gpu_policy" says what happens to the+text engine during the job (gpu_turn):+ keep - it stays loaded and idle (an APU's shared memory, a card with room for both)+ shrink - an engine started with --vram-elastic gives the image job VRAM from its expert cache and takes it back+ afterwards (POST /v1/vram's mechanism; the conversation stays in the engine)+ unload - its conversation is saved to a session file, the engine is stopped, and the next start restores it+ auto - (default) keep when there is room for the image job next to it, else shrink when the engine can,+ else unload+The process per request keeps nothing on the GPU between images: when the job ends, all of its memory is free again.++The config's "images" section (written by setup --images, tools/image/install.py):+ {"exe": "engine-image/sd-cli", "backend": "vulkan", "diffusion_model": "...Q8_0.gguf", "vae": "...",+ "llm": "...Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf", "quant": "Q8_0", "args": ["--diffusion-fa"],+ "gpu_policy": "auto", "reload": "lazy"|"eager", "max_n": 4, "max_side": 2048, "timeout_s": 3600,+ "lib_dirs": [...], "uma": false, "need_mib": null, "out_dir": null, "keep_files": 64}+"""+from __future__ import annotations++import base64+import contextlib+import os+import random+import re+import secrets+import subprocess+import tempfile+import threading+import time+from pathlib import Path++# Qwen-Image-2.1-Turbo's own schedule (model_index.json "sample_sigmas") plus the terminal 0, as Unsloth's card passes+# it to sd-cli; it is an 8-step schedule, so another step count leaves the schedule to sd.cpp+TURBO_SIGMAS = "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0"+TURBO_STEPS = 8+MODEL_NAME = "qwen-image-2.1-turbo"+POLICIES = ("auto", "keep", "shrink", "unload")+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$")+STEP_LINE = re.compile(r"\|\s*(\d+)/(\d+)\s*-") # sd.cpp's progress bar: "|==== | 3/8 - 14.1s/it"+++class ImageRequestError(ValueError):+ """A request the image endpoint refuses (400)."""+++class ImageJobFailed(RuntimeError):+ """sd-cli ended without the images (500); the message carries the end of its log."""+++def parse_size(value, max_side: int) -> tuple[int, int]:+ """OpenAI's size, "1024x1024" (or "auto": 1024x1024) -> (width, height); each side a multiple of 32 from 256 to+ max_side."""+ if value is None or value == "auto":+ return 1024, 1024+ if not isinstance(value, str):+ raise ImageRequestError("size: a string WIDTHxHEIGHT, e.g. \"1024x1024\"")+ m = re.fullmatch(r"\s*(\d{2,5})\s*[xX×]\s*(\d{2,5})\s*", value)+ if not m:+ raise ImageRequestError(f"size: WIDTHxHEIGHT, e.g. \"1024x1024\", not {value!r}")+ w, h = int(m.group(1)), int(m.group(2))+ for side in (w, h):+ if side < MIN_SIDE or side > max_side or side % SIZE_STEP:+ raise ImageRequestError(f"size {w}x{h}: each side a multiple of {SIZE_STEP} from {MIN_SIDE} to {max_side}")+ return w, h+++def _int_field(req: dict, key: str, lo: int, hi: int, default):+ v = req.get(key)+ if v is None:+ return default+ if isinstance(v, bool) or not isinstance(v, int) or not lo <= v <= hi:+ raise ImageRequestError(f"{key}: a whole number from {lo} to {hi}")+ return v+++def parse_request(req: dict, cfg: dict) -> dict:+ """The fields of one /v1/images/generations request, checked. Unknown OpenAI fields (quality, style, user,+ background, moderation) are accepted and ignored; an output format other than PNG is refused."""+ prompt = req.get("prompt")+ if not isinstance(prompt, str) or not prompt.strip():+ raise ImageRequestError("prompt: a non-empty string")+ if len(prompt) > 16000:+ raise ImageRequestError("prompt: at most 16000 characters")+ if "\0" in prompt:+ raise ImageRequestError("prompt: no NUL characters")+ fmt = req.get("response_format") or "b64_json"+ if fmt not in ("b64_json", "url"):+ raise ImageRequestError("response_format: b64_json or url")+ out_fmt = req.get("output_format")+ if out_fmt not in (None, "png"):+ raise ImageRequestError("output_format: only png")+ w, h = parse_size(req.get("size"), int(cfg.get("max_side") or 2048))+ n = _int_field(req, "n", 1, int(cfg.get("max_n") or 4), 1)+ steps = _int_field(req, "steps", 1, 100, int(cfg.get("steps") or TURBO_STEPS))+ seed = _int_field(req, "seed", 0, 2**62, None)+ if seed is None:+ seed = random.SystemRandom().randrange(0, 2**31)+ return {"prompt": prompt, "width": w, "height": h, "n": n, "steps": steps, "seed": seed, "response_format": fmt}+++def sd_cli_args(cfg: dict, job: dict, out_pattern: str) -> list[str]:+ """The sd-cli command for one job: the model card's stable-diffusion.cpp command (8 steps, CFG 1, euler, Turbo's+ sigmas, --diffusion-fa from the config's args), the size, seed and batch count, and the config's other args."""+ cmd = [str(cfg["exe"]),+ "--diffusion-model", str(cfg["diffusion_model"]), "--vae", str(cfg["vae"]), "--llm", str(cfg["llm"]),+ "-p", job["prompt"],+ "--steps", str(job["steps"]), "--cfg-scale", "1.0", "--sampling-method", "euler",+ "-W", str(job["width"]), "-H", str(job["height"])]+ if job["steps"] == TURBO_STEPS:+ cmd += ["--sigmas", str(cfg.get("sigmas") or TURBO_SIGMAS)]+ cmd += ["-s", str(job["seed"])]+ if job["n"] > 1:+ cmd += ["-b", str(job["n"])]+ cmd += ["-o", out_pattern]+ cmd += [str(a) for a in (cfg.get("args") or [])]+ return cmd+++def image_env(cfg: dict, base: dict | None = None) -> dict:+ """sd-cli's environment: the libraries its backend needs (ROCm's, setup's lib_dirs) first on the search path, the+ GPU to use when the config names one, and the config's own "env"."""+ env = dict(os.environ if base is None else base)+ dirs = [str(d) for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()]+ if dirs:+ var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"+ env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else []))+ gpu = cfg.get("gpu")+ if gpu is not None:+ var = {"cuda": "CUDA_VISIBLE_DEVICES", "hip": "HIP_VISIBLE_DEVICES",+ "vulkan": "GGML_VK_VISIBLE_DEVICES"}.get(cfg.get("backend"))+ if var:+ env[var] = str(gpu)+ if var == "CUDA_VISIBLE_DEVICES":+ env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"+ for k, v in (cfg.get("env") or {}).items():+ env[str(k)] = str(v)+ return env+++def need_mib(cfg: dict, width: int, height: int) -> int:+ """The GPU memory an image job is planned with: the three model files plus the working buffers (about 2 GiB plus+ 4 GiB per megapixel at Turbo's settings; the 780M baseline peaked 7.4 GB over the weights at 1024x1024 on HIP);+ the config's "need_mib" overrides it."""+ if cfg.get("need_mib"):+ return int(cfg["need_mib"])+ files = 0+ for k in ("diffusion_model", "vae", "llm"):+ try:+ files += Path(cfg[k]).stat().st_size+ except (OSError, KeyError, TypeError):+ pass+ work = (2 << 30) + int(4 * (1 << 30) * width * height / (1024 * 1024))+ return (files + work) >> 20+++class ImageGen:+ """One sd-cli process per request, one request at a time (the service's turn, gpu_turn)."""++ def __init__(self, cfg: dict, log=None):+ self.cfg = dict(cfg)+ policy = self.cfg.get("gpu_policy") or "auto"+ if policy not in POLICIES:+ raise ValueError(f'images "gpu_policy" must be one of {", ".join(POLICIES)}, not {policy!r}')+ reload = self.cfg.get("reload") or "lazy"+ if reload not in ("lazy", "eager"):+ raise ValueError(f'images "reload" must be lazy or eager, not {reload!r}')+ for k in ("exe", "diffusion_model", "vae", "llm"):+ if not isinstance(self.cfg.get(k), str) or not self.cfg[k]:+ raise ValueError(f'the config\'s "images" section needs "{k}" (run setup with --images again)')+ self.policy, self.reload = policy, reload+ self.model = self.cfg.get("model_name") or MODEL_NAME+ self.log = log+ out = self.cfg.get("out_dir")+ self.dir = Path(out) if out else Path(tempfile.mkdtemp(prefix="strata-images-"))+ self.dir.mkdir(parents=True, exist_ok=True)+ self.keep_files = int(self.cfg.get("keep_files") or 64)+ self.lock = threading.Lock() # one sd-cli at a time even when the service's turn is not taken+ self.totals = {"images": 0, "jobs": 0, "seconds": 0.0, "failed": 0}+ self.last = None # the last job's figures (/v1/status)+ self.progress = None # (step, steps) of the running job++ def missing(self) -> list[str]:+ return [self.cfg[k] for k in ("exe", "diffusion_model", "vae", "llm") if not Path(self.cfg[k]).exists()]++ def _say(self, text: str) -> None:+ print(f"[strata] {text}", flush=True)+ if self.log is not None:+ try:+ self.log.write(f"[images] {text}\n")+ self.log.flush()+ except (OSError, ValueError):+ pass++ def _prune(self) -> None:+ """Keep the newest keep_files PNGs of response_format url (the oldest go)."""+ files = sorted((p for p in self.dir.glob("*.png") if FILE_NAME.match(p.name)), key=lambda p: p.stat().st_mtime)+ for p in files[:max(0, len(files) - self.keep_files)]:+ with contextlib.suppress(OSError):+ p.unlink()++ def file(self, name: str) -> Path | None:+ """A stored image (response_format url) by its name, or None."""+ if not FILE_NAME.match(name or ""):+ return None+ p = self.dir / name+ return p if p.is_file() else None++ 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."""+ work = Path(tempfile.mkdtemp(prefix="job-", dir=self.dir))+ pattern = str(work / "img_%d.png")+ cmd = sd_cli_args(self.cfg, job, pattern)+ timeout = float(self.cfg.get("timeout_s") or 3600)+ logf = work / "sd-cli.log"+ t0 = time.monotonic()+ self.progress = (0, job["steps"])+ with self.lock:+ with open(logf, "w", encoding="utf-8", errors="replace") as lf:+ try:+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL, env=image_env(self.cfg),+ cwd=str(work), text=True, errors="replace", bufsize=1)+ except OSError as e:+ raise ImageJobFailed(f"sd-cli did not start ({cmd[0]}): {e}") from e+ try:+ from serve.winjob import contain+ contain(proc) # ends with the server (Windows)+ except Exception:+ pass+ why = None++ def pump():+ for line in proc.stdout:+ lf.write(line)+ m = STEP_LINE.search(line)+ if m:+ self.progress = (int(m.group(1)), int(m.group(2)))+ reader = threading.Thread(target=pump, daemon=True)+ reader.start()+ while proc.poll() is None:+ if cancel is not None and cancel.is_set():+ why = "cancelled (the client left)"+ elif time.monotonic() - t0 > timeout:+ why = f"it ran past timeout_s ({timeout:g} s)"+ if why:+ proc.kill()+ break+ time.sleep(0.2)+ with contextlib.suppress(subprocess.TimeoutExpired):+ proc.wait(timeout=30)+ reader.join(timeout=10)+ secs = time.monotonic() - t0+ self.progress = None+ log = logf.read_text(encoding="utf-8", errors="replace")+ outs = [work / f"img_{i}.png" for i in range(job["n"])]+ try:+ if why or proc.returncode != 0 or not all(p.is_file() for p in outs):+ self.totals["failed"] += 1+ tail = "\n".join(log.strip().splitlines()[-12:])+ what = why or (f"sd-cli exited with code {proc.returncode}" if proc.returncode+ else "sd-cli wrote no image")+ self._say(f"image job failed: {what}\n{tail}")+ raise ImageJobFailed(f"{what}; the end of its log:\n{tail}")+ images = [p.read_bytes() for p in outs]+ finally:+ for p in work.iterdir():+ with contextlib.suppress(OSError):+ p.unlink()+ with contextlib.suppress(OSError):+ work.rmdir()+ figures = {"seconds": round(secs, 2), "steps": job["steps"], "n": job["n"],+ "size": f"{job['width']}x{job['height']}", "seed": job["seed"],+ "backend": self.cfg.get("backend"), "quant": self.cfg.get("quant")}+ for key, pat in (("text_encode_ms", r"get_learned_condition completed, taking ([0-9.]+) ?ms"),+ ("sampling_s", r"sampling completed, taking ([0-9.]+) ?s"),+ ("vae_decode_s", r"decode_first_stage completed, taking ([0-9.]+) ?s")):+ m = re.findall(pat, log)+ if m:+ figures[key] = float(m[-1])+ self.totals["jobs"] += 1+ self.totals["images"] += job["n"]+ self.totals["seconds"] += secs+ self.last = figures+ return images, figures++ def store(self, data: bytes) -> str:+ """Keep one PNG for response_format url -> its file name (32 random hex digits: the name is the access)."""+ name = secrets.token_hex(16) + ".png"+ (self.dir / name).write_bytes(data)+ self._prune()+ return name++ def response(self, images: list[bytes], job: dict, figures: dict, base_url: str) -> dict:+ data = []+ for i, png in enumerate(images):+ item = {"revised_prompt": job["prompt"], "seed": job["seed"] + i}+ if job["response_format"] == "url":+ item["url"] = f"{base_url}/v1/images/files/{self.store(png)}"+ else:+ item["b64_json"] = base64.b64encode(png).decode("ascii")+ data.append(item)+ return {"created": int(time.time()), "data": data, "model": self.model,+ "output_format": "png", "size": f"{job['width']}x{job['height']}", "strata": figures}++ def status(self) -> dict:+ out = {"enabled": True, "model": self.model, "backend": self.cfg.get("backend"),+ "quant": self.cfg.get("quant"), "gpu_policy": self.policy, **self.totals}+ if self.progress:+ out["step"], out["steps"] = self.progress+ if self.last:+ out["last"] = self.last+ return out+++# ------------------------------------------------------------------------------------------- the GPU turn+def resolve_policy(svc, gen: ImageGen, need: int) -> str:+ """auto -> keep / shrink / unload for this job (see the module's docstring); a fixed policy is kept, except that+ an engine that is not running has nothing to give back (keep)."""+ eng = svc.engine+ running = not hasattr(eng, "alive") or eng.alive()+ if not running or not hasattr(eng, "unload"):+ return "keep"+ if gen.policy != "auto":+ return gen.policy+ if gen.cfg.get("uma"):+ return "keep" # an APU: the image job and the engine share the RAM either way+ free = svc.free_vram_mib()+ if free is None or free >= need:+ return "keep"+ if engine_elastic(eng):+ return "shrink"+ return "unload"+++def engine_elastic(eng) -> bool:+ """An engine that resizes its expert cache on request (--vram-elastic, #533)."""+ if not hasattr(eng, "vram"):+ return False+ if (getattr(eng, "info", None) or {}).get("vram_elastic"):+ return True+ spawn = getattr(eng, "spawn", None)+ args = spawn[1] if isinstance(spawn, (list, tuple)) and len(spawn) > 1 else []+ return "--vram-elastic" in (args or [])+++def _client_gone(svc) -> Exception:+ """The server module's ClientGone (it may run as __main__, so not imported by name)."""+ import sys+ return getattr(sys.modules.get(type(svc).__module__), "ClientGone", RuntimeError)()+++def gpu_turn(svc, gen: ImageGen, job: dict, cancel: threading.Event | None = None):+ """The image job's turn on the GPU: the service's FIFO (and, with parallel requests, the engine's control lines+ once no slot is generating), and the text engine made room for it per the policy. Yields the policy used."""+ with svc.status_lock:+ svc.status["queued"] += 1+ queued = True+ try:+ with svc._turn(cancel):+ with svc.status_lock:+ svc.status["queued"] -= 1+ queued = False+ ctl = getattr(svc.engine, "ctl", None) if getattr(svc.engine, "batch", 0) else None+ if ctl is not None:+ while not ctl.acquire(timeout=0.25):+ if cancel is not None and cancel.is_set():+ raise _client_gone(svc)+ try:+ if ctl is not None: # running parallel requests finish first+ while getattr(svc, "live_reqs", None):+ if cancel is not None and cancel.is_set():+ raise _client_gone(svc)+ time.sleep(0.25)+ need = need_mib(gen.cfg, job["width"], job["height"])+ policy = resolve_policy(svc, gen, need)+ with svc.status_lock:+ svc.status.update(busy=True, phase="generating an image", started=time.time(),+ first_token=None, prompt_tokens=None, generated=None, max_tokens=None)+ restore = _make_room(svc, gen, policy, need)+ try:+ yield policy+ finally:+ _give_back(svc, gen, policy, restore)+ with svc.status_lock:+ svc.status["busy"] = False+ svc.last_request_at = time.time()+ finally:+ if ctl is not None:+ ctl.release()+ finally:+ if queued:+ with svc.status_lock:+ svc.status["queued"] -= 1+++def _make_room(svc, gen: ImageGen, policy: str, need: int):+ """Do what `policy` says before the job; -> what _give_back needs."""+ eng = svc.engine+ if policy == "shrink":+ try:+ out = eng.vram(need)+ gen._say(f"image job: the engine's expert cache gave VRAM back ({out.get('vram_free_mib')} MiB free)")+ return "shrunk"+ except Exception as e: # noqa: BLE001 - the job still runs, with what is free+ gen._say(f"image job: the engine could not give VRAM back ({e}); the job runs with what is free")+ return None+ if policy == "unload":+ saved = None+ if hasattr(eng, "session_file") and not getattr(eng, "batch", 0):+ path = str(gen.dir / f"llm-session-{secrets.token_hex(6)}.bin")+ try:+ r = eng.session_file("save", path)+ saved = path+ gen._say(f"image job: the conversation ({r.get('tokens')} tokens) saved; unloading the model")+ except Exception as e: # noqa: BLE001 - unloading still frees the GPU+ gen._say(f"image job: the conversation could not be saved ({e}); unloading the model")+ with contextlib.suppress(OSError):+ os.unlink(path)+ eng.unload()+ if svc.vision is not None and hasattr(svc.vision, "unload"):+ svc.vision.unload()+ return saved or "unloaded"+ return None+++def _give_back(svc, gen: ImageGen, policy: str, restore) -> None:+ eng = svc.engine+ if restore == "shrunk":+ try:+ eng.vram(svc.vram_reserve) # the reserve asked for last (None: the start's)+ except Exception as e: # noqa: BLE001+ gen._say(f"image job: the expert cache did not grow back ({e}); POST /v1/vram can retry")+ elif policy == "unload" and restore:+ if restore != "unloaded":+ svc.restore_after_load = restore # Service.ensure_loaded restores it after the next start+ if gen.reload == "eager":+ try:+ svc.ensure_loaded() # the caller still holds the FIFO+ except Exception as e: # noqa: BLE001 - the next request tries again+ gen._say(f"image job: the model did not load again yet ({e}); the next request loads it")+++def restore_session(svc) -> None:+ """After an engine start: restore the conversation an image job saved before it unloaded the engine."""+ path = getattr(svc, "restore_after_load", None)+ if not path:+ return+ svc.restore_after_load = None+ try:+ r = svc.engine.session_file("restore", path)+ print(f"[strata] the conversation from before the image job is back ({r.get('tokens')} tokens)", flush=True)+ except Exception as e: # noqa: BLE001 - the engine runs, without the old cache+ print(f"[strata] the conversation from before the image job was not restored ({e}); the next request "+ "reads its prompt again", flush=True)+ finally:+ with contextlib.suppress(OSError):+ os.unlink(path)diff --git a/serve/server.py b/serve/server.pyindex ff1b935c3..a0f883509 100644--- a/serve/server.py+++ b/serve/server.py@@ -5,6 +5,9 @@Endpoints: POST /v1/chat/completions (OpenAI, stream and non-stream), POST /v1/messages (Anthropic, stream andnon-stream), GET /v1/models, GET /models, GET /props, GET /slots, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence).+Image generation (optional, when the config has an "images" section): POST /v1/images/generations (OpenAI's shape,+plus seed and steps) runs stable-diffusion.cpp's sd-cli for Qwen-Image-2.1-Turbo, one job at a time on the GPU the+text engine uses (serve/images.py).Tools from MCP servers (serve/mcp.py, `"mcp_servers"` in the config or --mcp-config) are offered only to requests thatask for them with `"strata_mcp": true` - the web app does; other clients see exactly the API they always saw.Images (optional, when the config has a "vision" entry): OpenAI image_url parts and Anthropic image blocks (base64@@ -64,6 +67,7 @@ from serve.winjob import contain # noqa: E402from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402from serve import responses as responses_api # noqa: E402from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402+from serve import images as images_api # noqa: E402IM_END = "<|im_end|>"IMAGE_PAD = "<|image_pad|>"@@ -2931,6 +2935,8 @@ class Service:self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off)self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> Falseself.tool_call_recovery = False # opt-in: tool calls in forms next to the template's+ self.images = None # serve/images.py's ImageGen when the config has "images"+ self.restore_after_load = None # a session file an image job saved before it unloadedself.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +tokenizer.encode("<|endoftext|>", parse_special=True))@@ -3146,6 +3152,8 @@ class Service:self.vision.unload()raiseprint("[strata] the engine is running again", flush=True)+ if self.restore_after_load: # an image job unloaded it: its conversation comes back+ images_api.restore_session(self)if self.vram_reserve is not None and hasattr(self.engine, "vram"): # #533: the reserve asked for lasttry:self.engine.vram(self.vram_reserve)@@ -3502,6 +3510,7 @@ class Service:"requested": max(1, int(getattr(self.engine, "batch", 0) or 0))},"dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"],"vision": {"enabled": images, "available": images, "error": None},+ "image_generation": self.images.status() if self.images is not None else {"enabled": False},"activity": {"requests": totals["requests"] + int(busy), "in_flight": int(busy) + int(s.get("queued") or 0),"last_request_at": int(last_at) if last_at else None},"last_timings": last_t,@@ -5071,7 +5080,21 @@ def make_handler(svc: Service):elif path in ("/health", "/api/health"):self._json(200, {"status": "ok", "max_context": svc.reported_ctx(), "model": svc.model,"images": svc.vision is not None, "api_key": bool(svc.api_key),+ "image_generation": svc.images is not None,"loaded": svc.loaded(), "service": "strata"})+ elif path.startswith("/v1/images/files/"):+ # response_format url: the name (32 random hex digits) is the access, as an OpenAI image URL is+ f = svc.images.file(path[len("/v1/images/files/"):]) if svc.images is not None else None+ if f is None:+ self._json(404, {"error": {"message": "not found (the server keeps the newest images only)"}})+ return+ body = f.read_bytes()+ self.send_response(200)+ self.send_header("Content-Type", "image/png")+ self.send_header("Cache-Control", "private, max-age=86400")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)elif path == "/status":if not self._authorized(): # #212: it shows the end of the last answerreturn@@ -5099,7 +5122,11 @@ def make_handler(svc: Service):if svc.aliases: # #297: the aliases, and each one listed under its own idmodel["aliases"] = list(svc.aliases)data = [model, *({**model, "id": x, "alias_of": svc.model} for x in svc.aliases)]- self._json(200, {"object": "list", "data": data if loaded else []})+ data = data if loaded else []+ if svc.images is not None: # the image model: POST /v1/images/generations+ data.append({"id": svc.images.model, "object": "model", "status": {"value": "loaded"},+ "architecture": {"input_modalities": ["text"], "output_modalities": ["image"]}})+ self._json(200, {"object": "list", "data": data})elif path == "/props":if self._authorized():self._props()@@ -5237,6 +5264,8 @@ def make_handler(svc: Service):self._anthropic(req)elif path == "/v1/messages/count_tokens":self._count_tokens(req)+ elif path == "/v1/images/generations":+ self._images(req)else:self._json(404, {"error": {"message": "not found"}})except EngineNonFinite as e: # #879, twice: not the request's fault@@ -5291,6 +5320,33 @@ def make_handler(svc: Service):record["state"] = "error" if record.get("error") else record.get("outcome", "completed")svc.request_trace.record = None+ def _images(self, req):+ """POST /v1/images/generations (serve/images.py): one sd-cli job in the GPU's turn."""+ gen = svc.images+ if gen is None:+ self._json(404, {"error": {"type": "invalid_request_error", "code": "images_not_set_up",+ "message": "image generation is not set up on this server (run setup "+ "with --images qwen-image)"}})+ return+ job = images_api.parse_request(req, gen.cfg) # ImageRequestError (a ValueError): 400+ svc.last_request_at = time.time()+ cancel = threading.Event()+ self._watch_client(cancel)+ print(f"[strata] image: {job['width']}x{job['height']}, n={job['n']}, {job['steps']} steps, "+ f"seed {job['seed']}", flush=True)+ try:+ with images_api.gpu_turn(svc, gen, job, cancel) as policy:+ images, figures = gen.run(job, cancel)+ except images_api.ImageJobFailed as e:+ self._json(500, {"error": {"type": "server_error", "code": "image_generation_failed",+ "message": str(e)}})+ return+ figures["gpu_policy"] = policy+ print(f"[strata] image done in {figures['seconds']:.1f} s ({policy})", flush=True)+ host = self.headers.get("Host") or f"{self.server.server_address[0]}:{self.server.server_address[1]}"+ scheme = "https" if (self.headers.get("X-Forwarded-Proto") or "").lower() == "https" else "http"+ self._json(200, gen.response(images, job, figures, f"{scheme}://{host}"))+def _props(self):model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0]if model not in svc.model_names():@@ -6441,6 +6497,21 @@ def main() -> int:sampling_defaults=sampling_defaults,fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)svc.reasoning_close_retry = cfg.get("reasoning_close_retry") is True # #1053: opt-in, off by default+ if cfg.get("images"): # image generation (serve/images.py), set up by setup --images+ icfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))+ if k in ("exe", "diffusion_model", "vae", "llm", "out_dir") and isinstance(v, str)+ and not os.path.isabs(v) else v)+ for k, v in cfg["images"].items()}+ try:+ svc.images = images_api.ImageGen(icfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None)+ except ValueError as e:+ raise SystemExit(f"[strata] config: {e}")+ gone = svc.images.missing()+ if gone:+ print(f"[strata] image generation: missing {', '.join(gone)} - requests fail until setup --images has run "+ "again", 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):raise SystemExit(f"[strata] config \"prevent_sleep\" must be true or false, not {cfg['prevent_sleep']!r}")from serve.keepawake import KeepAwakediff --git a/serve/test_images.py b/serve/test_images.pynew file mode 100644index 000000000..5d9a78703--- /dev/null+++ b/serve/test_images.py@@ -0,0 +1,334 @@+"""POST /v1/images/generations (serve/images.py): the request shape, the sd-cli command, the GPU turn and its policies,+over HTTP with a stand-in sd-cli (serve/fixtures/fake_sd_cli.py) and the mock engine.++ python -m serve.test_images+"""+import base64+import json+import os+import sys+import tempfile+import threading+import time+import unittest+import urllib.error+import urllib.request+from pathlib import Path+from unittest import mock++from serve import images as images_api+from serve.frontend import ChatTemplate+from serve.server import ByteTokenizer, MockEngine, Service, serve++ROOT = Path(__file__).resolve().parents[1]+FAKE = ROOT / "serve" / "fixtures" / "fake_sd_cli.py"+REAL_ARGS = images_api.sd_cli_args+++def fake_args(cfg, job, out):+ """sd-cli's command, run through Python (the stand-in is a script)."""+ return [sys.executable, str(FAKE), *REAL_ARGS(cfg, job, out)[1:]]+++def image_cfg(d, **kw):+ files = {}+ for k in ("diffusion_model", "vae", "llm"):+ p = Path(d) / f"{k}.bin"+ p.write_bytes(b"x" * 1024)+ files[k] = str(p)+ return {"exe": str(FAKE), "backend": "vulkan", "quant": "Q8_0", "args": ["--diffusion-fa"],+ "out_dir": str(Path(d) / "out"), **files, **kw}+++class Request(unittest.TestCase):+ CFG = {"max_n": 4, "max_side": 2048}++ def test_defaults(self):+ j = images_api.parse_request({"prompt": "a cat"}, self.CFG)+ self.assertEqual((j["width"], j["height"], j["n"], j["steps"], j["response_format"]),+ (1024, 1024, 1, 8, "b64_json"))+ self.assertTrue(0 <= j["seed"] < 2**31)++ def test_fields(self):+ j = images_api.parse_request({"prompt": "a cat", "size": "1536x1024", "n": 2, "steps": 4, "seed": 7,+ "response_format": "url", "quality": "hd", "model": "dall-e-3"}, self.CFG)+ self.assertEqual((j["width"], j["height"], j["n"], j["steps"], j["seed"], j["response_format"]),+ (1536, 1024, 2, 4, 7, "url"))+ self.assertEqual(images_api.parse_request({"prompt": "x", "size": "auto"}, self.CFG)["width"], 1024)++ def test_refused(self):+ bad = [{}, {"prompt": ""}, {"prompt": 5}, {"prompt": "x", "n": 0}, {"prompt": "x", "n": 5},+ {"prompt": "x", "n": True}, {"prompt": "x", "size": "1000x1000"}, {"prompt": "x", "size": "128x128"},+ {"prompt": "x", "size": "4096x1024"}, {"prompt": "x", "size": "big"}, {"prompt": "x", "steps": 0},+ {"prompt": "x", "seed": -1}, {"prompt": "x", "seed": "1"}, {"prompt": "x", "response_format": "png"},+ {"prompt": "x", "output_format": "jpeg"}, {"prompt": "a\0b"}]+ for req in bad:+ with self.subTest(req=req), self.assertRaises(images_api.ImageRequestError):+ images_api.parse_request(req, self.CFG)+++class Command(unittest.TestCase):+ def test_the_model_cards_command(self):+ """Unsloth's stable-diffusion.cpp command for Turbo: 8 steps, CFG 1, euler, the Turbo sigmas, --diffusion-fa."""+ cfg = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf",+ "args": ["--diffusion-fa", "--vae-tiling"]}+ job = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42}+ self.assertEqual(images_api.sd_cli_args(cfg, job, "o/img_%d.png"), [+ "sd-cli", "--diffusion-model", "dit.gguf", "--vae", "vae.st", "--llm", "te.gguf", "-p", "a sloth",+ "--steps", "8", "--cfg-scale", "1.0", "--sampling-method", "euler", "-W", "1024", "-H", "768",+ "--sigmas", "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0",+ "-s", "42", "-o", "o/img_%d.png", "--diffusion-fa", "--vae-tiling"])++ def test_other_steps_and_batch(self):+ cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l"}+ cmd = images_api.sd_cli_args(cfg, {"prompt": "p", "width": 512, "height": 512, "n": 3, "steps": 4,+ "seed": 1}, "x")+ self.assertNotIn("--sigmas", cmd) # Turbo's sigmas are an 8-step schedule+ self.assertEqual(cmd[cmd.index("-b") + 1], "3")++ def test_env(self):+ env = images_api.image_env({"backend": "cuda", "gpu": 1, "env": {"X": 2}}, {"PATH": "p"})+ self.assertEqual((env["CUDA_VISIBLE_DEVICES"], env["CUDA_DEVICE_ORDER"], env["X"]), ("1", "PCI_BUS_ID", "2"))+ with tempfile.TemporaryDirectory() as d:+ env = images_api.image_env({"backend": "hip", "gpu": 0, "lib_dirs": [d, d + "-missing"]}, {})+ self.assertEqual(env["HIP_VISIBLE_DEVICES"], "0")+ self.assertEqual(env["PATH" if os.name == "nt" else "LD_LIBRARY_PATH"], d)+ self.assertEqual(images_api.image_env({"backend": "vulkan", "gpu": 2}, {})["GGML_VK_VISIBLE_DEVICES"], "2")++ def test_config_checked(self):+ with self.assertRaises(ValueError):+ images_api.ImageGen({"exe": "x", "diffusion_model": "d", "vae": "v"})+ with tempfile.TemporaryDirectory() as d:+ with self.assertRaises(ValueError):+ images_api.ImageGen(image_cfg(d, gpu_policy="sometimes"))+++class FakeEngine:+ """An engine with the parts the GPU turn uses: alive/unload/restart, vram (elastic) and session files."""++ def __init__(self, elastic=False):+ self.up, self.calls, self.info = True, [], {"vram_elastic": elastic}+ self.spawn = (["strata"], ["--vram-elastic"] if elastic else [])+ self.unloaded = False++ def alive(self):+ return self.up++ def exit_code(self):+ return 0++ def unload(self):+ self.calls.append("unload")+ self.up, self.unloaded = False, True++ def restart(self):+ self.calls.append("restart")+ self.up, self.unloaded = True, False++ def vram(self, reserve):+ self.calls.append(("vram", reserve))+ return {"vram_free_mib": 9000}++ def session_file(self, action, path):+ self.calls.append((action, os.path.basename(path)))+ if action == "save":+ Path(path).write_bytes(b"kv")+ else:+ assert Path(path).read_bytes() == b"kv"+ return {"tokens": 123, "bytes": 2, "ms": 1.0}++ def generate(self, ids, max_new, sampling, cancel, embeddings=None):+ return iter(())+++class Policy(unittest.TestCase):+ def svc(self, engine):+ tok = ByteTokenizer()+ return Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))++ def test_resolve(self):+ with tempfile.TemporaryDirectory() as d:+ gen = images_api.ImageGen(image_cfg(d))+ eng = FakeEngine()+ svc = self.svc(eng)+ with mock.patch.object(svc, "free_vram_mib", return_value=20000):+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")+ with mock.patch.object(svc, "free_vram_mib", return_value=None):+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")+ with mock.patch.object(svc, "free_vram_mib", return_value=4000):+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "unload")+ svc.engine = FakeEngine(elastic=True)+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "shrink")+ gen.cfg["uma"] = True+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")+ gen.cfg["uma"] = False+ gen.policy = "unload"+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "unload")+ svc.engine.up = False # nothing loaded: nothing to give back+ self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")+ self.assertEqual(images_api.resolve_policy(self.svc(MockEngine(ByteTokenizer(), "x")), gen, 1), "keep")++ def test_unload_saves_and_the_next_start_restores(self):+ with tempfile.TemporaryDirectory() as d:+ gen = images_api.ImageGen(image_cfg(d, gpu_policy="unload"))+ eng = FakeEngine()+ svc = self.svc(eng)+ job = {"width": 1024, "height": 1024}+ with images_api.gpu_turn(svc, gen, job) as policy:+ self.assertEqual(policy, "unload")+ self.assertTrue(svc.fifo.locked()) # no chat turn meanwhile+ self.assertFalse(eng.up)+ self.assertTrue(svc.status["busy"])+ self.assertFalse(svc.fifo.locked())+ self.assertFalse(svc.status["busy"])+ self.assertEqual([c if isinstance(c, str) else c[0] for c in eng.calls], ["save", "unload"])+ self.assertTrue(svc.restore_after_load)+ with svc.fifo:+ svc.ensure_loaded() # the next request: start, then the conversation back+ self.assertEqual([c if isinstance(c, str) else c[0] for c in eng.calls],+ ["save", "unload", "restart", "restore"])+ self.assertIsNone(svc.restore_after_load)+ self.assertEqual(list(Path(gen.dir).glob("llm-session-*")), [])++ def test_eager_reload(self):+ with tempfile.TemporaryDirectory() as d:+ gen = images_api.ImageGen(image_cfg(d, gpu_policy="unload", reload="eager"))+ eng = FakeEngine()+ svc = self.svc(eng)+ with images_api.gpu_turn(svc, gen, {"width": 512, "height": 512}):+ pass+ self.assertEqual([c if isinstance(c, str) else c[0] for c in eng.calls],+ ["save", "unload", "restart", "restore"])+ self.assertTrue(eng.up)++ def test_shrink_gives_the_cache_back(self):+ with tempfile.TemporaryDirectory() as d:+ gen = images_api.ImageGen(image_cfg(d, gpu_policy="shrink"))+ eng = FakeEngine(elastic=True)+ svc = self.svc(eng)+ svc.vram_reserve = 512+ with images_api.gpu_turn(svc, gen, {"width": 1024, "height": 1024}):+ self.assertEqual(eng.calls[0][0], "vram")+ self.assertEqual(eng.calls[0][1], 6 * 1024) # 2 GiB + 4 GiB per megapixel (+ 3 KiB of files)+ self.assertEqual(eng.calls[-1], ("vram", 512))+ self.assertTrue(eng.up)++ def test_keep_touches_nothing(self):+ with tempfile.TemporaryDirectory() as d:+ gen = images_api.ImageGen(image_cfg(d, gpu_policy="keep"))+ eng = FakeEngine()+ svc = self.svc(eng)+ with images_api.gpu_turn(svc, gen, {"width": 1024, "height": 1024}):+ pass+ self.assertEqual(eng.calls, [])++[email protected](images_api, "sd_cli_args", fake_args)+class OverHttp(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ tok = ByteTokenizer()+ self.engine = MockEngine(tok, "</think>\n\nok")+ self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ self.svc.images = images_api.ImageGen(image_cfg(self.tmp.name, keep_files=3))+ self.httpd = serve(self.svc, port=0)+ self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"++ def tearDown(self):+ self.httpd.shutdown()+ self.httpd.server_close()+ self.tmp.cleanup()++ def post(self, body, path="/v1/images/generations"):+ req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=60) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as e:+ with e:+ return e.code, json.loads(e.read())++ def get(self, path):+ try:+ with urllib.request.urlopen(self.base + path, timeout=30) as r:+ return r.status, r.read(), r.headers.get("Content-Type")+ except urllib.error.HTTPError as e:+ with e:+ return e.code, e.read(), None++ def test_b64(self):+ code, body = self.post({"prompt": "a red fox", "seed": 11, "n": 2, "size": "512x768"})+ self.assertEqual(code, 200, body)+ self.assertEqual(len(body["data"]), 2)+ pngs = [base64.b64decode(x["b64_json"]) for x in body["data"]]+ sys.path.insert(0, str(FAKE.parent))+ import fake_sd_cli+ self.assertEqual(pngs, [fake_sd_cli.png(512, 768, 11, "a red fox"), fake_sd_cli.png(512, 768, 12, "a red fox")])+ self.assertEqual([x["seed"] for x in body["data"]], [11, 12])+ self.assertEqual(body["size"], "512x768")+ self.assertEqual(body["strata"]["steps"], 8)+ self.assertEqual(body["strata"]["sampling_s"], 0.08)+ self.assertEqual(body["strata"]["gpu_policy"], "keep")+ self.assertEqual(self.svc.images.totals["images"], 2)+ self.assertEqual([p.name for p in Path(self.svc.images.dir).iterdir()], []) # nothing left behind++ def test_url(self):+ names = []+ for i in range(4):+ code, body = self.post({"prompt": "a lighthouse", "seed": i, "response_format": "url"})+ self.assertEqual(code, 200, body)+ url = body["data"][0]["url"]+ self.assertTrue(url.startswith(self.base + "/v1/images/files/"), url)+ names.append(url.rsplit("/", 1)[1])+ code, data, ctype = self.get(url[len(self.base):])+ self.assertEqual((code, ctype), (200, "image/png"))+ self.assertTrue(data.startswith(b"\x89PNG"))+ self.assertEqual(self.get("/v1/images/files/" + names[0])[0], 404) # keep_files 3: the oldest went+ self.assertEqual(self.get("/v1/images/files/../../setup.py")[0], 404)+ self.assertEqual(self.get("/v1/images/files/" + "0" * 32 + ".png")[0], 404)++ def test_bad_request_and_failure(self):+ self.assertEqual(self.post({"prompt": "x", "size": "999x999"})[0], 400)+ with mock.patch.dict(os.environ, {"FAKE_SD_FAIL": "1"}):+ code, body = self.post({"prompt": "x"})+ self.assertEqual(code, 500)+ self.assertIn("ErrorDeviceLost", body["error"]["message"])+ self.assertEqual(self.svc.images.totals["failed"], 1)+ self.assertFalse(self.svc.status["busy"])+ self.assertFalse(self.svc.fifo.locked())++ def test_listed(self):+ code, data, _ = self.get("/v1/models")+ ids = [m["id"] for m in json.loads(data)["data"]]+ self.assertIn("qwen-image-2.1-turbo", ids)+ st = json.loads(self.get("/v1/status")[1])+ self.assertTrue(st["image_generation"]["enabled"])+ self.assertTrue(json.loads(self.get("/health")[1])["image_generation"])++ def test_not_set_up(self):+ self.svc.images = None+ code, body = self.post({"prompt": "x"})+ self.assertEqual((code, body["error"]["code"]), (404, "images_not_set_up"))++ def test_chat_waits_for_the_image(self):+ """One job at a time on the GPU: a chat request sent during an image job is answered after it."""+ done = {}+ with mock.patch.dict(os.environ, {"FAKE_SD_SLEEP": "1.5"}):+ t = threading.Thread(target=lambda: done.setdefault("img", (self.post({"prompt": "x"}), time.time())))+ t.start()+ time.sleep(0.5)+ req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(+ {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": "hi"}]}).encode(),+ headers={"Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=60) as r:+ self.assertEqual(r.status, 200)+ chat_at = time.time()+ t.join()+ (code, _), img_at = done["img"]+ self.assertEqual(code, 200)+ self.assertGreaterEqual(chat_at, img_at - 0.05)+++if __name__ == "__main__":+ unittest.main()diff --git a/serve/web/app.css b/serve/web/app.cssindex b0a57c6ab..0c75e60ee 100644--- a/serve/web/app.css+++ b/serve/web/app.css@@ -188,3 +188,11 @@ main { flex: 1; min-height: 0; display: flex; }.facts { grid-template-columns: 1fr; gap: 2px; }.facts dd { margin-bottom: var(--st-s-2); }}+/* Images tab (POST /v1/images/generations) */+.img-form{display:flex;flex-direction:column;gap:12px}+.img-prompt{height:auto;padding:10px 14px;resize:vertical}+.img-row{display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap}+.img-results{display:flex;flex-direction:column;gap:12px}+.img-results figure{margin:0}+.img-results img{max-width:100%;border-radius:var(--st-r-lg);display:block}+.img-results figcaption{font-size:var(--st-fs-sm, 13px);color:var(--st-ink-2, inherit);margin-top:4px}diff --git a/serve/web/app.js b/serve/web/app.jsindex 4460a95a7..d3ad404fc 100644--- a/serve/web/app.js+++ b/serve/web/app.js@@ -73,9 +73,10 @@ matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {let tab = "chat";function showTab(name) {- tab = ["chat", "monitor", "about"].includes(name) ? name : "chat";+ tab = ["chat", "images", "monitor", "about"].includes(name) ? name : "chat";for (const b of document.querySelectorAll(".st-tab")) b.setAttribute("aria-selected", String(b.dataset.tab === tab));- for (const v of ["chat", "monitor", "about"]) $(`view-${v}`).hidden = v !== tab;+ for (const v of ["chat", "images", "monitor", "about"]) $(`view-${v}`).hidden = v !== tab;+ if (tab === "images") $("img-prompt").focus();if (location.hash.slice(1) !== tab) history.replaceState(null, "", tab === "chat" ? location.pathname : `#${tab}`);if (tab === "chat") $("input").focus();if (tab === "monitor") loadMcp();@@ -103,6 +104,8 @@ async function loadHealth() {$("attach-btn").title = health.images ? "Attach a text file or a picture (or drop it here)": "Attach a text file (or drop it here)";$("chat-empty-sub").textContent = `${health.model} runs on this PC. Nothing leaves it.`;+ $("tab-btn-images").hidden = !health.image_generation;+ if (location.hash === "#images" && health.image_generation) showTab("images");} catch (e) {setTimeout(loadHealth, 2000);}@@ -1081,3 +1084,36 @@ if (startQuestion) history.replaceState(null, "", location.pathname + location.hloadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } });showTab(location.hash.slice(1) || "chat");poll();++// ------------------------------------------------------------------ images (POST /v1/images/generations)+$("img-form").onsubmit = async (ev) => {+ ev.preventDefault();+ const prompt = $("img-prompt").value.trim();+ if (!prompt) return;+ const body = {prompt, size: $("img-size").value, response_format: "b64_json"};+ if ($("img-seed").value !== "") body.seed = Number($("img-seed").value);+ $("img-go").disabled = true;+ const t0 = performance.now();+ $("img-hint").textContent = "Generating\u2026 (a minute or more on a small GPU)";+ try {+ const r = await fetch("v1/images/generations", {method: "POST", headers: headers(true), body: JSON.stringify(body)});+ const j = await r.json();+ if (!r.ok) throw new Error((j.error && j.error.message) || r.statusText);+ for (const d of j.data) {+ const fig = document.createElement("figure");+ const img = document.createElement("img");+ img.src = "data:image/png;base64," + d.b64_json;+ img.alt = prompt;+ const cap = document.createElement("figcaption");+ cap.textContent = `${j.size}, seed ${d.seed}, ${((performance.now() - t0) / 1000).toFixed(0)} s: ${prompt}`;+ fig.append(img, cap);+ $("img-results").prepend(fig);+ }+ $("img-hint").textContent = "Done. Right-click an image to save it.";+ } catch (e) {+ $("img-hint").textContent = "";+ toast("error", "No image", String(e.message || e), 8000);+ } finally {+ $("img-go").disabled = false;+ }+};diff --git a/serve/web/index.html b/serve/web/index.htmlindex 79cc6b7c5..0c7847f22 100644--- a/serve/web/index.html+++ b/serve/web/index.html@@ -23,6 +23,8 @@<nav class="st-tabs" role="tablist" aria-label="Views"><button class="st-tab" role="tab" id="tab-btn-chat" aria-controls="view-chat" aria-selected="true" data-tab="chat"><svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-chat"/></svg>Chat</button>+ <button class="st-tab" role="tab" id="tab-btn-images" aria-controls="view-images" aria-selected="false" data-tab="images" hidden>+ <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-image"/></svg>Images</button><button class="st-tab" role="tab" id="tab-btn-monitor" aria-controls="view-monitor" aria-selected="false" data-tab="monitor"><svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-activity"/></svg>Monitor</button><button class="st-tab" role="tab" id="tab-btn-about" aria-controls="view-about" aria-selected="false" data-tab="about">@@ -71,6 +73,27 @@</div></section>+ <!-- ============================ Images ============================ -->+ <section class="view view--images" id="view-images" role="tabpanel" aria-labelledby="tab-btn-images" hidden>+ <div class="about">+ <form class="st-card img-form" id="img-form">+ <span class="card-title" id="img-title">Make an image</span>+ <textarea class="st-input img-prompt" id="img-prompt" rows="3" placeholder="Describe the image…" aria-label="Prompt"></textarea>+ <div class="img-row">+ <label class="st-field">Size+ <select class="st-input" id="img-size">+ <option>1024x1024</option><option>1536x1024</option><option>1024x1536</option>+ <option>768x768</option><option>512x512</option></select></label>+ <label class="st-field">Seed+ <input class="st-input" id="img-seed" type="number" min="0" placeholder="random"></label>+ <button type="submit" class="st-btn st-btn--primary" id="img-go">Generate</button>+ </div>+ <span class="composer-hint" id="img-hint">One image at a time; a chat request waits for it (and the other way round).</span>+ </form>+ <div class="img-results" id="img-results"></div>+ </div>+ </section>+<!-- ============================ Monitor ============================ --><section class="view view--monitor" id="view-monitor" role="tabpanel" aria-labelledby="tab-btn-monitor" hidden><div class="monitor">diff --git a/setup.py b/setup.pyindex 7d291e1c6..b561c8782 100644--- a/setup.py+++ b/setup.py@@ -29,7 +29,9 @@ answers, no questions), --setup (install another model / change settings instead(EXPERIMENTAL, off by default),--models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-madeengine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM),---kv-streaming on|off|auto.+--kv-streaming on|off|auto, --images qwen-image|no (image generation: Qwen-Image-2.1-Turbo through+stable-diffusion.cpp, POST /v1/images/generations; --image-quant Q4_K_M|Q6_K|Q8_0, --image-backend+cuda|hip|vulkan|cpu, --image-gpu-policy auto|keep|shrink|unload; docs/IMAGES.md).Setup recommends, it never forces: the recommended answers are the defaults (--yes, or Enter), and a bigger choicethan it recommends - a longer context, more GPUs, a bigger RAM budget, a size it thinks will not fit - is kept, with@@ -2712,6 +2714,175 @@ def build_vision_cpu(eng: Path, stamp: Path, meta: dict, llama, vsrc) -> Path:return eng+# ------------------------------------------------------------------------------------------------ image generation+IMAGE_ENGINE = ROOT / "engine-image" # sd-cli for Qwen-Image-2.1-Turbo (tools/image/qimage.py), --images+++def _qimage():+ if str(ROOT / "tools" / "image") not in sys.path:+ sys.path.insert(0, str(ROOT / "tools" / "image"))+ import qimage+ return qimage+++def get_sd_cpp() -> Path:+ """stable-diffusion.cpp and its ggml at the pinned commits (tools/image/qimage.py), as zips: no git."""+ QI = _qimage()+ src = ROOT / "third_party" / "stable-diffusion.cpp"+ if QI.source_ok(src):+ return src+ z1 = ROOT / "third_party" / f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT[:7]}.zip"+ z2 = ROOT / "third_party" / f"sd-ggml-{QI.SD_GGML_COMMIT[:7]}.zip"+ download(QI.SD_CPP_ZIP, z1, "stable-diffusion.cpp source")+ download(QI.SD_GGML_ZIP, z2, "stable-diffusion.cpp's ggml source")+ try:+ src = QI.unpack_source(ROOT / "third_party", z1, z2)+ except zipfile.BadZipFile:+ for z in (z1, z2):+ drop_archive(z)+ raise+ for z in (z1, z2):+ z.unlink(missing_ok=True)+ z.with_name(z.name + ".done").unlink(missing_ok=True)+ return src+++def vulkan_sdk() -> Path | None:+ """What a Vulkan build of sd-cli needs (the Vulkan headers and glslc): $VULKAN_SDK, the distribution's packages,+ else (Linux) the LunarG SDK unpacked into third_party (no sudo, ~370 MB). Returns the SDK folder it put on PATH,+ None when the system's files are used."""+ QI = _qimage()+ have = os.environ.get("VULKAN_SDK")+ if have and Path(have).is_dir():+ return None+ if not WIN and shutil.which("glslc") and Path("/usr/include/vulkan/vulkan.h").exists():+ return None+ if WIN:+ fail("compiling the image generator for this GPU (Vulkan) needs the Vulkan SDK",+ "install it from https://vulkan.lunarg.com/sdk/home#windows, open a new window and run setup again "+ "(or --image-backend cpu)")+ base = ROOT / "third_party" / "vulkan-sdk"+ sdk = base / QI.VULKAN_SDK_VERSION / "x86_64"+ if not (sdk / "bin" / "glslc").exists():+ import tarfile+ tar = ROOT / "third_party" / f"vulkansdk-{QI.VULKAN_SDK_VERSION}.tar.xz"+ download(QI.VULKAN_SDK_URL, tar, f"the Vulkan SDK {QI.VULKAN_SDK_VERSION} (LunarG, for compiling only)")+ verify_sha256(tar, QI.VULKAN_SDK_SIZE, QI.VULKAN_SDK_SHA256)+ shutil.rmtree(base, ignore_errors=True)+ base.mkdir(parents=True)+ with tarfile.open(tar) as t:+ t.extractall(base, **({"filter": "data"} if hasattr(tarfile, "data_filter") else {}))+ tar.unlink(missing_ok=True)+ tar.with_name(tar.name + ".done").unlink(missing_ok=True)+ os.environ["VULKAN_SDK"] = str(sdk)+ os.environ["PATH"] = os.pathsep.join([str(sdk / "bin"), os.environ.get("PATH", "")])+ os.environ["LD_LIBRARY_PATH"] = os.pathsep.join([str(sdk / "lib" / "VulkanLoader" / "lib"),+ os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep)+ ok(f"Vulkan SDK: {sdk}")+ return sdk+++def build_image_engine(backend: str, gpu: dict) -> tuple[Path, list[str]]:+ """Compile sd-cli for `backend` into engine-image/ (again only when the pins or the backend changed) -> (its path,+ the library folders it runs with)."""+ QI = _qimage()+ 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)+ 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:+ ok(f"image generator already built ({backend})")+ return exe, lib_dirs+ src = get_sd_cpp()+ vcvars, lib_dirs = None, []+ if backend == "cuda":+ nvcc, cuda_v = find_nvcc()+ if nvcc is None:+ fail("compiling the image generator for NVIDIA needs the CUDA Toolkit (nvcc)",+ "install it from https://developer.nvidia.com/cuda-downloads and run setup again "+ "(or --image-backend vulkan / cpu)")+ root = Path(nvcc).resolve().parent.parent+ defs = QI.cmake_defs("cuda", arch=arch, cuda_root=root) + [f"-DCMAKE_CUDA_COMPILER={nvcc}"] + \+ host_compiler_defs(True)+ vcvars = find_vcvars(cuda_v) if WIN else None+ lib_dirs = [str(root / "bin")] if WIN else [str(d) for d in (root / "lib64", root / "lib") if d.is_dir()]+ elif backend == "hip":+ root, dirs = rocm_root([arch])+ os.environ.update({"HIP_PLATFORM": "amd", "ROCM_PATH": str(root), "HIP_PATH": str(root)})+ os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep)+ defs = QI.cmake_defs("hip", arch=arch, rocm=root)+ lib_dirs = list(dirs)+ elif backend == "vulkan":+ sdk = vulkan_sdk()+ defs = QI.cmake_defs("vulkan")+ vcvars = find_vcvars() if WIN else None+ if sdk is not None: # the SDK's loader (lib/VulkanLoader): CMake does not look there+ loader = sdk / "lib" / "VulkanLoader" / "lib"+ defs += [f"-DVulkan_LIBRARY={loader / 'libvulkan.so'}", f"-DVulkan_INCLUDE_DIR={sdk / 'include'}",+ f"-DVulkan_GLSLC_EXECUTABLE={sdk / 'bin' / 'glslc'}"]+ import ctypes.util+ if not ctypes.util.find_library("vulkan"):+ lib_dirs = [str(loader)] # no system Vulkan loader to run with: the SDK's+ else:+ defs = QI.cmake_defs("cpu")+ vcvars = find_vcvars() if WIN else None+ say(f" Compiling the image generator (stable-diffusion.cpp {QI.SD_CPP_COMMIT[:7]}, {backend}; 5-20 minutes, "+ "once) ...")+ bdir = ROOT / f"build-image-{backend}"+ cmake_build(src, bdir, "sd-cli", defs, vcvars, f"build-image-{backend}.bat" if WIN else "")+ built = bdir / "bin" / QI.SD_EXE+ if not built.exists():+ fail(f"the image generator's build finished without {built}", f"delete the folder {bdir.name} and run again")+ shutil.copy2(built, exe)+ stamp.write_text(json.dumps({**want, "lib_dirs": lib_dirs}, indent=1))+ ok(f"image generator compiled: {exe}")+ return exe, lib_dirs+++def image_backend_choice(a, gpu: dict | None, hip: bool) -> tuple[str, str, float]:+ """--images: (backend, quant, the GPU memory in GB the quant was picked for). An explicit --image-quant above the+ recommendation is kept, with a warning (recommend, never force)."""+ QI = _qimage()+ vendor = "amd" if hip else ((gpu or {}).get("vendor") or "nvidia")+ backend = a.image_backend or QI.pick_backend({**gpu, "vendor": vendor} if gpu else None, WIN)+ gb = float((gpu or {}).get("vram_gb") or 0.0) if backend != "cpu" else 0.0+ rec = QI.pick_quant(gb) if backend != "cpu" else "Q4_K_M"+ quant = a.image_quant or rec+ if QI.QUANTS.index(quant) > QI.QUANTS.index(rec):+ warn(f"image model {quant}: setup recommends {rec} for {gb:.0f} GB of GPU memory; kept as you chose "+ "(stable-diffusion.cpp then keeps part of it in RAM, which is slower)")+ return backend, quant, gb+++def setup_images(a, gpu: dict, hip: bool, models_dir: Path) -> dict | None:+ """--images qwen-image: sd-cli for this GPU and Qwen-Image-2.1-Turbo's three files -> the run config's "images"+ section (serve/images.py); None for --images no, or when not wanted after all."""+ if not a.images or a.images == "no":+ return None+ QI = _qimage()+ backend, quant, _ = image_backend_choice(a, gpu, hip)+ say(f" Image generation: Qwen-Image-2.1-Turbo {quant} on {backend} (8 steps, CFG 1; POST /v1/images/generations)")+ say(" " + QI.LICENSE_NOTE)+ need = sum(QI.FILES[k][2] for k in (quant, "vae", "llm")) / 1e9+ if ask(f"Download the image model ({need:.1f} GB) and set up image generation?", ["y", "n"], "y", a.yes) != "y":+ return None+ models_dir.mkdir(parents=True, exist_ok=True)+ 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")+ exe, lib_dirs = build_image_engine(backend, gpu or {})+ for name in (quant, "vae", "llm"):+ repo, path, size, sha = QI.FILES[name]+ dst = QI.local_path(models_dir, name)+ download(QI.file_url(name, hf_endpoint()), dst, f"image model: {Path(path).name}")+ 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")+ ok(f"image generation: {quant} on {backend}, GPU policy {cfg['gpu_policy']}")+ return cfg++# ------------------------------------------------------------------------------------------------ the enginedef driver_major(gpu):try:@@ -3963,6 +4134,8 @@ def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) ->if not isinstance(old, dict):old = Nonekept = carry_over(old, cfg) if old is not None else []+ if "images" in cfg and cfg["images"] is None: # --images no (or not downloaded): no image section+ cfg.pop("images")bak = Noneif cfg_path.is_file() and old != cfg:bak = cfg_path.with_name(cfg_path.name + ".bak")@@ -4845,6 +5018,17 @@ def main() -> int:help="the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on ""the CPU): more reads small text and charts better, and takes longer to encode; remembered ""for this model")+ ap.add_argument("--images", choices=["qwen-image", "no"],+ help="image generation (POST /v1/images/generations): Qwen-Image-2.1-Turbo through "+ "stable-diffusion.cpp, compiled here; no = take it out of the config (docs/IMAGES.md)")+ ap.add_argument("--image-quant", choices=["Q4_K_M", "Q6_K", "Q8_0"],+ help="the image model's size (default by GPU memory: Q4_K_M up to 8 GB, Q6_K up to 12, Q8_0 above)")+ ap.add_argument("--image-backend", choices=["cuda", "hip", "vulkan", "cpu"],+ help="where images are made (default: cuda on NVIDIA, hip on an AMD card, vulkan on an APU/iGPU "+ "and Intel)")+ ap.add_argument("--image-gpu-policy", choices=["auto", "keep", "shrink", "unload"],+ help="what the text model does during an image job (default auto: stays loaded when both fit, "+ "else gives VRAM back or is unloaded and its conversation restored afterwards)")ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF",help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection ""(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md")@@ -5798,6 +5982,8 @@ def main() -> int:cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2)elif a.vision_tokens is not None:warn("--vision-tokens: images are off for this model, so it is not used")+ if a.images: # only when given: else an earlier "images" is carried over+ cfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir))cfg_path = ROOT / f"strata-{tag.lower()}.json"cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA onlyif cal is not None:@@ -5832,6 +6018,8 @@ def main() -> int:say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")if vision != "none":say(" Images: send them in the chat page, in chat.py (/image <path>) or over the API")+ if cfg.get("images"):+ say(f" Image generation: POST http://127.0.0.1:{port}/v1/images/generations (OpenAI's images API)")if a.parallel is None: # #465: the opt-in, said once (nothing changes)for line in parallel_note(None, [g.get("vram_gb", 0.0) for g in chosen], MODELS[model]["arena_gb"], ctx, kv,"--kv-resident" in cfg["args"]):diff --git a/tools/image/install.py b/tools/image/install.pynew file mode 100644index 000000000..3bb64bb3f--- /dev/null+++ b/tools/image/install.py@@ -0,0 +1,99 @@+"""tools/image/install.py - image generation (Qwen-Image-2.1-Turbo) for an existing Strata install, or on its own:+compiles sd-cli for the backend (setup.py's build_image_engine), downloads and checks the three model files, and+writes the "images" section into a run config (or prints it). setup.py --images qwen-image does the same inside+the normal setup; this is the way to add it without running the whole setup again.++ python tools/image/install.py --config strata-q2_0.json (backend and size picked for this PC)+ python tools/image/install.py --backend vulkan --quant Q8_0 --models-dir ~/models --print+ python tools/image/install.py --backend hip --arch gfx1103 --build-only++--gpu-policy auto|keep|shrink|unload: what the text model does during an image job (serve/images.py).+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "tools"))+sys.path.insert(0, str(ROOT / "tools" / "image"))+import qimage as QI # noqa: E402+++def detect_gpu(S) -> tuple[dict | None, bool]:+ """setup.py's view of this PC's GPU: (gpu dict, AMD?) - an NVIDIA card first, else an AMD one, else none."""+ try:+ g = S.gpu_info()+ if g:+ return {**g, "vendor": "nvidia"}, False+ except Exception: # noqa: BLE001 - no NVIDIA driver+ pass+ try:+ amd = S.amd_gpus_win() if S.WIN else S.amd_gpus()+ if amd:+ g = min(amd, key=S.amd_rank)+ return S.amd_apply_uma(dict(g)), True+ except Exception: # noqa: BLE001+ pass+ return None, False+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--backend", choices=QI.BACKENDS)+ ap.add_argument("--arch", help="the GPU architecture to compile for (CUDA: 86, ...; HIP: gfx1103, ...)")+ ap.add_argument("--quant", choices=QI.QUANTS)+ ap.add_argument("--gpu-gb", type=float, help="the GPU memory the quant is picked for (default: detected)")+ ap.add_argument("--models-dir", help="where the model files go (default: the data folder's models)")+ ap.add_argument("--config", help="a run config (strata-<model>.json) to write the \"images\" section into")+ ap.add_argument("--gpu-policy", choices=["auto", "keep", "shrink", "unload"], default="auto")+ ap.add_argument("--gpu", type=int, help="the GPU's number for the image job (default: the backend's first)")+ 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")+ a = ap.parse_args(argv)+ import setup as S+ gpu, amd = detect_gpu(S) if not (a.backend and (a.arch or a.backend in ("vulkan", "cpu"))) else (None, False)+ gpu = dict(gpu or {})+ if a.arch:+ gpu["arch"] = a.arch+ if a.gpu_gb is not None:+ gpu["vram_gb"] = a.gpu_gb+ ns = argparse.Namespace(images="qwen-image", image_backend=a.backend, image_quant=a.quant,+ image_gpu_policy=a.gpu_policy, yes=a.yes)+ backend, quant, gb = S.image_backend_choice(ns, gpu or None, amd or a.backend == "hip")+ 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)+ if a.build_only:+ return 0+ if a.models_dir:+ models = Path(a.models_dir).expanduser()+ else:+ data, _ = S.data_folder(None)+ models = data / "models"+ S.say(" " + QI.LICENSE_NOTE)+ for name in (quant, "vae", "llm"):+ repo, path, size, sha = QI.FILES[name]+ dst = QI.local_path(models, name)+ 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)+ if a.print or not a.config:+ print(json.dumps({"images": section}, indent=1))+ return 0+ path = Path(a.config)+ cfg = json.loads(path.read_text(encoding="utf-8-sig")) if path.is_file() else {}+ cfg["images"] = section+ S.write_config(path, cfg)+ S.ok(f"{path.name}: image generation added (POST /v1/images/generations once the server starts again)")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/image/qimage.py b/tools/image/qimage.pynew file mode 100644index 000000000..386f27e18--- /dev/null+++ b/tools/image/qimage.py@@ -0,0 +1,181 @@+"""tools/image/qimage.py - Qwen-Image-2.1-Turbo for Strata's image endpoint: stable-diffusion.cpp (sd-cli) at a pinned+commit, built for this PC's GPU, and the model's three files at pinned Hugging Face revisions.++setup.py (--images qwen-image) and tools/image/install.py use these pieces; serve/images.py runs the result.++ backend CUDA on an NVIDIA card, HIP on an AMD card with its own memory (Linux), Vulkan on an APU/iGPU (AMD's shared+ memory: the HIP path's queue evictions reset a 780M on current firmware, NEW-MODELS-PLAN.md section 4),+ on Intel and on AMD under Windows; CPU without a GPU. --image-backend picks another.+ 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+ LPIPS vs bf16: 0.153 / 0.055 / 0.036); the VAE (bf16); the Qwen3-VL-8B text encoder UD-Q4_K_XL (the+ model card's choice). Each file is checked against the SHA-256 the Hugging Face API lists for it at the+ pinned revision.+ defaults 8 steps, CFG 1, euler, Turbo's own sigmas (serve/images.py), --diffusion-fa; on Vulkan also --vae-tiling+ (an untiled 1024x1024 VAE decode is one dispatch long enough to trip the amdgpu job timeout on a 780M).+"""+from __future__ import annotations++import os+import shutil+import zipfile+from pathlib import Path++SD_CPP_COMMIT = "2988060a4338a5dcd94721c964a8e87003c1ac8b" # "add TAEQI2.1 support for Qwen Image 2.1" (#2123)+SD_GGML_COMMIT = "d25b121ce1d6ae0c7e62ad080460d9fc1e46dd93" # its ggml submodule (leejet/ggml)+SD_CPP_ZIP = f"https://github.com/leejet/stable-diffusion.cpp/archive/{SD_CPP_COMMIT}.zip"+SD_GGML_ZIP = f"https://github.com/leejet/ggml/archive/{SD_GGML_COMMIT}.zip"++# the LunarG Vulkan SDK for a Linux PC without Vulkan development files (headers, glslc): unpacked into third_party,+# no sudo; the version the 780M builds were made with+VULKAN_SDK_VERSION = "1.4.363.0"+VULKAN_SDK_URL = (f"https://sdk.lunarg.com/sdk/download/{VULKAN_SDK_VERSION}/linux/"+ f"vulkansdk-linux-x86_64-{VULKAN_SDK_VERSION}.tar.xz")+VULKAN_SDK_SIZE = 366_564_872+VULKAN_SDK_SHA256 = "197962f5cbf80baf2775a03336a01cee7c8745686c65aaa70d3f751ade4d7e43"++REVISIONS = { # the `sha` of https://huggingface.co/api/models/<repo>, 2026-10-12+ "unsloth/Qwen-Image-2.1-Turbo-GGUF": "5d1f9f759ea877ae556cda88dbec958b62ad3809",+ "unsloth/Qwen-Image-2.1-FP8": "bb21a8ba7f0371c19ad1f72c82a5e8fc10f39939",+ "unsloth/Qwen3-VL-8B-Instruct-GGUF": "b93a7ee713758252c555be4210c00540df954dc2",+}+_DIT = "unsloth/Qwen-Image-2.1-Turbo-GGUF"+# name -> (repo, path in the repo, bytes, sha256): the Hub's LFS pointers at the pinned revisions+FILES = {+ "Q4_K_M": (_DIT, "qwen-image-2.1-turbo-Q4_K_M.gguf", 4_199_565_120,+ "8940e8b522af886e0c0f5afddf720e82dd223cb9a43580b5f61c4d740452ac20"),+ "Q6_K": (_DIT, "qwen-image-2.1-turbo-Q6_K.gguf", 6_271_551_296,+ "f4560fb47ad863ffed7e32737d3c42988c44bd0c459606777d7ffe2e895d0a70"),+ "Q8_0": (_DIT, "qwen-image-2.1-turbo-Q8_0.gguf", 7_640_860_480,+ "399d2ddc3636f36456e2f5bfa57187da4e38721bc046430317f42a9eab5b1712"),+ "vae": ("unsloth/Qwen-Image-2.1-FP8", "vae/qwen_image_2.1_vae_bf16.safetensors", 675_508_656,+ "71879ffd5321e6d10c3c87513e2b474b1252efa7f3dec2969214a9bf06a6dd5c"),+ "llm": ("unsloth/Qwen3-VL-8B-Instruct-GGUF", "Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf", 5_148_699_488,+ "e3d1a6e87c5cb31e054f2c3bc0dd82ffde052f613de5eef3665b7bd33c9b703e"),+}+QUANTS = ("Q4_K_M", "Q6_K", "Q8_0")+BACKENDS = ("cuda", "hip", "vulkan", "cpu")+LICENSE_NOTE = ("Qwen-Image-2.1-Turbo is under the Qwen Research License (not Apache 2.0): "+ "https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo/blob/main/LICENSE - read it before you use the images "+ "commercially")+MODEL_DIR = "qwen-image-2.1-turbo"+SD_EXE = "sd-cli.exe" if os.name == "nt" else "sd-cli"+++def pick_quant(gpu_gb: float) -> str:+ """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."""+ if gpu_gb <= 8:+ return "Q4_K_M"+ if gpu_gb <= 12:+ return "Q6_K"+ return "Q8_0"+++# AMD APUs (integrated GPUs on shared memory) by gfx target: Rembrandt 680M/660M, Mendocino 610M, Phoenix 780M/760M/+# 740M, Strix Point 890M/880M, Strix Halo 8060S, Krackan, Raven/Renoir/Cezanne+APU_ARCHS = ("gfx1035", "gfx1036", "gfx1037", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx1153",+ "gfx902", "gfx909", "gfx90c")+++def is_apu(gpu: dict | None) -> bool:+ """An integrated GPU on shared memory: setup's "uma" mark, or an APU's gfx target (setup marks only the APUs the+ text engine supports)."""+ if not gpu:+ return False+ return bool(gpu.get("uma")) or str(gpu.get("arch") or "").split(":")[0] in APU_ARCHS+++def pick_backend(gpu: dict | None, win: bool) -> str:+ """sd.cpp's backend for setup's GPU dict (vendor, uma, arch): see the module's docstring."""+ if not gpu:+ return "cpu"+ vendor = (gpu.get("vendor") or "nvidia").lower()+ if vendor == "nvidia":+ return "cuda"+ if vendor == "amd":+ return "vulkan" if is_apu(gpu) or win else "hip"+ return "vulkan" # Intel (Arc) and others+++def default_args(backend: str) -> list[str]:+ """sd-cli's fixed arguments besides the ones serve/images.py writes per request."""+ return ["--diffusion-fa"] + (["--vae-tiling"] if backend == "vulkan" else [])+++def file_url(name: str, endpoint: str = "https://huggingface.co") -> str:+ repo, path, _, _ = FILES[name]+ return f"{endpoint.rstrip('/')}/{repo}/resolve/{REVISIONS[repo]}/{path}"+++def local_path(models_dir: Path, name: str) -> Path:+ return Path(models_dir) / MODEL_DIR / Path(FILES[name][1]).name+++def cmake_defs(backend: str, arch=None, rocm: Path | None = None, cuda_root: Path | None = None) -> list[str]:+ """CMake definitions for sd-cli on `backend`: arch = the CUDA compute capability ("86") or the gfx target."""+ defs = ["-DSD_BUILD_EXAMPLES=ON", "-DSD_WEBP=OFF", "-DSD_WEBM=OFF", "-DSD_BUILD_SHARED_LIBS=OFF",+ "-DGGML_NATIVE=ON"]+ if backend == "cuda":+ defs += ["-DSD_CUDA=ON"] + ([f"-DCMAKE_CUDA_ARCHITECTURES={arch}"] if arch else [])+ if cuda_root:+ defs += [f"-DCUDAToolkit_ROOT={cuda_root}"]+ elif backend == "hip":+ if not rocm:+ raise ValueError("the HIP build needs the ROCm folder")+ gfx = str(arch).split(":")[0]+ llvm = rocm / "lib" / "llvm" if (rocm / "lib" / "llvm" / "bin").is_dir() else rocm / "llvm"+ bitcode = next((p for p in (llvm / "amdgcn" / "bitcode", rocm / "amdgcn" / "bitcode") if p.is_dir()),+ llvm / "amdgcn" / "bitcode")+ defs += ["-DSD_HIPBLAS=ON", f"-DGPU_TARGETS={gfx}", f"-DAMDGPU_TARGETS={gfx}",+ f"-DCMAKE_C_COMPILER={llvm / 'bin' / 'clang'}", f"-DCMAKE_CXX_COMPILER={llvm / 'bin' / 'clang++'}",+ f"-DCMAKE_HIP_COMPILER={llvm / 'bin' / 'clang++'}",+ f"-DCMAKE_PREFIX_PATH={rocm};{rocm / 'lib' / 'rocm_sysdeps'};{llvm}",+ f"-DCMAKE_HIP_FLAGS=--rocm-path={rocm} --rocm-device-lib-path={bitcode}"]+ elif backend == "vulkan":+ defs += ["-DSD_VULKAN=ON"]+ elif backend != "cpu":+ raise ValueError(f"unknown backend {backend!r}")+ return defs+++def unpack_source(third_party: Path, sd_zip: Path, ggml_zip: Path) -> Path:+ """stable-diffusion.cpp's zip with its ggml submodule's zip inside (GitHub's archives leave submodules out) ->+ third_party/stable-diffusion.cpp, stamped with the two commits."""+ dst = Path(third_party) / "stable-diffusion.cpp"+ tmp = Path(third_party) / "_unpack-sd"+ shutil.rmtree(tmp, ignore_errors=True)+ for z, sub in ((sd_zip, "sd"), (ggml_zip, "ggml")):+ with zipfile.ZipFile(z) as f:+ f.extractall(tmp / sub)+ top = next((tmp / "sd").iterdir())+ gtop = next((tmp / "ggml").iterdir())+ shutil.rmtree(top / "ggml", ignore_errors=True)+ shutil.move(str(gtop), str(top / "ggml"))+ shutil.rmtree(dst, ignore_errors=True)+ shutil.move(str(top), str(dst))+ shutil.rmtree(tmp, ignore_errors=True)+ (dst / ".strata-pin").write_text(f"{SD_CPP_COMMIT}\n{SD_GGML_COMMIT}\n", encoding="utf-8")+ return dst+++def source_ok(src: Path) -> bool:+ pin = Path(src) / ".strata-pin"+ return pin.is_file() and pin.read_text(encoding="utf-8").split() == [SD_CPP_COMMIT, SD_GGML_COMMIT] \+ and (Path(src) / "ggml" / "CMakeLists.txt").is_file()+++def build_stamp(backend: str, arch) -> dict:+ return {"sd_cpp": SD_CPP_COMMIT, "ggml": SD_GGML_COMMIT, "backend": backend, "arch": str(arch or "")}+++def image_config(backend: str, quant: str, exe: Path, models_dir: Path, *, uma: bool = False, gpu=None,+ lib_dirs=(), policy: str = "auto") -> 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")),+ "llm": str(local_path(models_dir, "llm")), "args": default_args(backend), "gpu_policy": policy,+ "uma": bool(uma), "sd_cpp": SD_CPP_COMMIT[:7]}+ if gpu is not None:+ cfg["gpu"] = gpu+ if lib_dirs:+ cfg["lib_dirs"] = [str(d) for d in lib_dirs]+ return cfgdiff --git a/tools/test_qimage.py b/tools/test_qimage.pynew file mode 100644index 000000000..b38507981--- /dev/null+++ b/tools/test_qimage.py@@ -0,0 +1,166 @@+"""Tests for image generation's setup side (tools/image/qimage.py, setup.py --images): the pins, the quant and backend+choices, the CMake definitions, the source unpacking and the run config's "images" section. No GPU, no network.++ python -m unittest tools.test_qimage+"""+from __future__ import annotations++import argparse+import contextlib+import io+import json+import re+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "tools"))+sys.path.insert(0, str(ROOT / "tools" / "image"))+import qimage as QI # noqa: E402+import setup # noqa: E402+++def quiet(fn, *args, **kw):+ with contextlib.redirect_stdout(io.StringIO()):+ return fn(*args, **kw)+++class Pins(unittest.TestCase):+ def test_shapes(self):+ for c in (QI.SD_CPP_COMMIT, QI.SD_GGML_COMMIT, *QI.REVISIONS.values()):+ self.assertRegex(c, r"^[0-9a-f]{40}$")+ for name, (repo, path, size, sha) in QI.FILES.items():+ self.assertIn(repo, QI.REVISIONS, name)+ self.assertRegex(sha, r"^[0-9a-f]{64}$")+ self.assertGreater(size, 100 << 20)+ self.assertEqual(QI.file_url("Q8_0"), "https://huggingface.co/unsloth/Qwen-Image-2.1-Turbo-GGUF/resolve/"+ "5d1f9f759ea877ae556cda88dbec958b62ad3809/qwen-image-2.1-turbo-Q8_0.gguf")+ self.assertEqual(QI.local_path(Path("m"), "vae"),+ Path("m") / "qwen-image-2.1-turbo" / "qwen_image_2.1_vae_bf16.safetensors")++ def test_sigmas_are_the_models(self):+ """serve/images.py's schedule is model_index.json's sample_sigmas plus the terminal 0."""+ from serve import images+ sample = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]+ self.assertEqual([float(x) for x in images.TURBO_SIGMAS.split(",")], sample + [0.0])+++class Choices(unittest.TestCase):+ def test_quant_by_memory(self):+ self.assertEqual([QI.pick_quant(g) for g in (4, 8, 8.5, 12, 12.1, 16, 32)],+ ["Q4_K_M", "Q4_K_M", "Q6_K", "Q6_K", "Q8_0", "Q8_0", "Q8_0"])++ def test_backend(self):+ self.assertEqual(QI.pick_backend(None, False), "cpu")+ self.assertEqual(QI.pick_backend({"vendor": "nvidia"}, True), "cuda")+ self.assertEqual(QI.pick_backend({"vendor": "amd"}, False), "hip")+ self.assertEqual(QI.pick_backend({"vendor": "amd", "uma": True}, False), "vulkan") # the 780M, Strix Halo+ self.assertEqual(QI.pick_backend({"vendor": "amd"}, True), "vulkan") # AMD on Windows+ self.assertEqual(QI.pick_backend({"vendor": "intel"}, False), "vulkan")+ self.assertEqual(QI.pick_backend({"vendor": "amd", "arch": "gfx1103"}, False), "vulkan") # no uma mark+ self.assertEqual(QI.pick_backend({"vendor": "amd", "arch": "gfx1100"}, False), "hip")+ self.assertTrue(QI.is_apu({"arch": "gfx1151:xnack-"}))++ def test_default_args(self):+ self.assertEqual(QI.default_args("cuda"), ["--diffusion-fa"])+ self.assertEqual(QI.default_args("vulkan"), ["--diffusion-fa", "--vae-tiling"])++ def test_setup_recommends_never_forces(self):+ ns = argparse.Namespace(image_backend=None, image_quant=None)+ self.assertEqual(quiet(setup.image_backend_choice, ns, {"vram_gb": 12.0, "arch": 86}, False)[:2],+ ("cuda", "Q6_K"))+ self.assertEqual(quiet(setup.image_backend_choice, ns, {"vram_gb": 32.3, "uma": True, "arch": "gfx1103"},+ True)[:2], ("vulkan", "Q8_0"))+ ns.image_quant = "Q8_0" # more than recommended: kept, with a warning+ out = io.StringIO()+ with contextlib.redirect_stdout(out):+ r = setup.image_backend_choice(ns, {"vram_gb": 8.0, "arch": 86}, False)+ self.assertEqual(r[:2], ("cuda", "Q8_0"))+ self.assertIn("recommends Q4_K_M", out.getvalue())+ ns.image_quant, ns.image_backend = None, "cpu"+ self.assertEqual(quiet(setup.image_backend_choice, ns, {"vram_gb": 24.0}, False)[:2], ("cpu", "Q4_K_M"))+++class Build(unittest.TestCase):+ def test_cmake_defs(self):+ d = QI.cmake_defs("cuda", arch=86, cuda_root=Path("/usr/local/cuda"))+ self.assertIn("-DSD_CUDA=ON", d)+ self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=86", d)+ self.assertIn("-DSD_WEBP=OFF", d)+ self.assertIn("-DSD_VULKAN=ON", QI.cmake_defs("vulkan"))+ with tempfile.TemporaryDirectory() as r:+ rocm = Path(r)+ (rocm / "lib" / "llvm" / "bin").mkdir(parents=True)+ d = QI.cmake_defs("hip", arch="gfx1103:sramecc-:xnack-", rocm=rocm)+ self.assertIn("-DGPU_TARGETS=gfx1103", d)+ self.assertIn(f"-DCMAKE_HIP_COMPILER={rocm / 'lib' / 'llvm' / 'bin' / 'clang++'}", d)+ with self.assertRaises(ValueError):+ QI.cmake_defs("hip", arch="gfx1103")+ with self.assertRaises(ValueError):+ QI.cmake_defs("metal")++ def test_unpack_puts_ggml_in_place(self):+ with tempfile.TemporaryDirectory() as d:+ d = Path(d)+ z1, z2 = d / "sd.zip", d / "ggml.zip"+ with zipfile.ZipFile(z1, "w") as z:+ z.writestr(f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT}/CMakeLists.txt", "project(sd)")+ z.writestr(f"stable-diffusion.cpp-{QI.SD_CPP_COMMIT}/ggml/", "")+ with zipfile.ZipFile(z2, "w") as z:+ z.writestr(f"ggml-{QI.SD_GGML_COMMIT}/CMakeLists.txt", "project(ggml)")+ src = QI.unpack_source(d, z1, z2)+ self.assertEqual((src / "ggml" / "CMakeLists.txt").read_text(), "project(ggml)")+ self.assertTrue(QI.source_ok(src))+ (src / ".strata-pin").write_text("0" * 40 + "\n" + QI.SD_GGML_COMMIT + "\n")+ self.assertFalse(QI.source_ok(src)) # another pin: unpacked again++ def test_build_is_skipped_when_the_stamp_matches(self):+ with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "IMAGE_ENGINE", Path(d)):+ (Path(d) / QI.SD_EXE).write_bytes(b"x")+ (Path(d) / "BUILD.json").write_text(json.dumps({**QI.build_stamp("cuda", 86), "lib_dirs": [d]}))+ with mock.patch.object(setup, "cmake_build") as cb:+ exe, libs = quiet(setup.build_image_engine, "cuda", {"arch": 86})+ cb.assert_not_called()+ self.assertEqual((exe, libs), (Path(d) / QI.SD_EXE, [d]))+ with mock.patch.object(setup, "cmake_build") as cb, mock.patch.object(setup, "get_sd_cpp"), \+ mock.patch.object(setup, "find_nvcc", return_value=(None, None)):+ with self.assertRaises(SystemExit): # another arch: compiled again (here: no nvcc, so it stops)+ quiet(setup.build_image_engine, "cuda", {"arch": 89})+++class Config(unittest.TestCase):+ def test_section(self):+ c = QI.image_config("vulkan", "Q8_0", Path("/e/sd-cli"), Path("/m"), uma=True, lib_dirs=["/l"])+ self.assertEqual(c["diffusion_model"], str(Path("/m/qwen-image-2.1-turbo/qwen-image-2.1-turbo-Q8_0.gguf")))+ self.assertEqual(c["args"], ["--diffusion-fa", "--vae-tiling"])+ self.assertTrue(c["uma"])+ self.assertEqual(c["gpu_policy"], "auto")+ from serve.images import ImageGen+ with tempfile.TemporaryDirectory() as d:+ ImageGen({**c, "out_dir": d}) # serve accepts what setup writes++ def test_images_no_drops_the_section(self):+ with tempfile.TemporaryDirectory() as d:+ p = Path(d) / "strata-q2_0.json"+ p.write_text(json.dumps({"exe": "x", "images": {"exe": "sd-cli"}, "mine": 1}))+ quiet(setup.write_setup_config, p, {"exe": "y", "images": None})+ cfg = json.loads(p.read_text())+ self.assertNotIn("images", cfg)+ self.assertEqual(cfg["mine"], 1)+ p.write_text(json.dumps({"exe": "x", "images": {"exe": "sd-cli"}}))+ quiet(setup.write_setup_config, p, {"exe": "y"}) # not asked: carried over+ self.assertEqual(json.loads(p.read_text())["images"], {"exe": "sd-cli"})++ def test_flags(self):+ src = (ROOT / "setup.py").read_text(encoding="utf-8")+ for flag in ("--images", "--image-quant", "--image-backend", "--image-gpu-policy"):+ self.assertRegex(src, re.escape(f'ap.add_argument("{flag}"'))+++if __name__ == "__main__":+ unittest.main()