From a5b3b6c27b56a69df5f845c6a500e111a529428c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 20:18:33 +0200 Subject: [PATCH 1/2] Image generation: Qwen-Image-2.1-Turbo through stable-diffusion.cpp (POST /v1/images/generations) - serve/images.py: OpenAI's images API (prompt, size, n, response_format b64_json|url) plus seed and steps; one sd-cli process per request with the model card's arguments (8 steps, CFG 1, euler, Turbo's sigmas, --diffusion-fa), the PNGs returned unchanged. The job takes the service's turn (one job at a time on the GPU) and the config's gpu_policy says what the text engine does meanwhile: keep, shrink (--vram-elastic), unload (its conversation saved to a session file and restored after the next start), auto. - setup.py --images qwen-image (--image-quant, --image-backend, --image-gpu-policy): sd.cpp 2988060 + its ggml as zips, built for CUDA / HIP / Vulkan (LunarG SDK into third_party when the PC has no Vulkan dev files) / CPU; DiT quant by GPU memory (Q4_K_M <= 8 GB, Q6_K <= 12, Q8_0 above), VAE and the Qwen3-VL-8B UD-Q4_K_XL text encoder at pinned revisions, each checked against the Hub's SHA-256. tools/image/install.py adds it to an existing install. - Web page: an Images tab when the server has image generation. - docs/IMAGES.md; tests: serve/test_images.py, tools/test_qimage.py. --- docs/IMAGES.md | 79 ++++++ serve/fixtures/fake_sd_cli.py | 57 +++++ serve/images.py | 468 ++++++++++++++++++++++++++++++++++ serve/server.py | 73 +++++- serve/test_images.py | 334 ++++++++++++++++++++++++ serve/web/app.css | 8 + serve/web/app.js | 40 ++- serve/web/index.html | 23 ++ setup.py | 190 +++++++++++++- tools/image/install.py | 99 +++++++ tools/image/qimage.py | 181 +++++++++++++ tools/test_qimage.py | 166 ++++++++++++ 12 files changed, 1714 insertions(+), 4 deletions(-) create mode 100644 docs/IMAGES.md create mode 100644 serve/fixtures/fake_sd_cli.py create mode 100644 serve/images.py create mode 100644 serve/test_images.py create mode 100644 tools/image/install.py create mode 100644 tools/image/qimage.py create mode 100644 tools/test_qimage.py diff --git a/docs/IMAGES.md b/docs/IMAGES.md new file mode 100644 index 00000000..7f627355 --- /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-.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/.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.py new file mode 100644 index 00000000..3dd80a6b --- /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=: waits that long first (cancel tests). +FAKE_SD_ARGS=: 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.py new file mode 100644 index 00000000..de155286 --- /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)() + + +@contextlib.contextmanager +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.py index ff1b935c..a0f88350 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 and non-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 that ask 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: E402 from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 from serve import responses as responses_api # noqa: E402 from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 +from serve import images as images_api # noqa: E402 IM_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" -> False self.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 unloaded self.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() raise print("[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 last try: 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 answer return @@ -5099,7 +5122,11 @@ def make_handler(svc: Service): if svc.aliases: # #297: the aliases, and each one listed under its own id model["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 KeepAwake diff --git a/serve/test_images.py b/serve/test_images.py new file mode 100644 index 00000000..5d9a7870 --- /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, []) + + +@mock.patch.object(images_api, "sd_cli_args", fake_args) +class OverHttp(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + tok = ByteTokenizer() + self.engine = MockEngine(tok, "\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.css index b0a57c6a..0c75e60e 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.js index 4460a95a..d3ad404f 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.h loadHealth().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.html index 79cc6b7c..0c7847f2 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -23,6 +23,8 @@