okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
35.4 KiB713 linesraw
1"""serve/images.py - image generation (Qwen-Image-2.1-Turbo) through stable-diffusion.cpp's sd-cli.
2
3POST /v1/images/generations takes OpenAI's request shape (prompt, size, n, response_format b64_json|url, background)
4plus Strata's own fields seed and steps.  Each request runs one `sd-cli` process with the arguments the model's card
5gives for stable-diffusion.cpp (8 steps, CFG 1, euler, Turbo's sigmas, --diffusion-fa).  The model writes RGBA; by
6default each picture is put on white and returned as an 8-bit RGB PNG with sd-cli's other chunks (its "parameters"
7text) unchanged (flatten_png); background "transparent" returns the PNG exactly as sd-cli wrote it.
8
9The GPU is shared with the text engine one job at a time: an image job takes the service's turn (the FIFO every chat
10request takes), so no chat turn runs on the GPU meanwhile, and the config's "gpu_policy" says what happens to the
11text engine during the job (gpu_turn):
12  keep    - it stays loaded and idle (an APU's shared memory, a card with room for both)
13  shrink  - an engine started with --vram-elastic gives the image job VRAM from its expert cache and takes it back
14            afterwards (POST /v1/vram's mechanism; the conversation stays in the engine)
15  unload  - its conversation is saved to a session file, the engine is stopped, and the next start restores it
16  auto    - (default) keep when there is room for the image job next to it, else shrink when the engine can,
17            else unload
18The process per request keeps nothing on the GPU between images: when the job ends, all of its memory is free again.
19
20The config's "images" section (written by setup --images, tools/image/install.py):
21  {"exe": "engine-image/sd-cli", "backend": "vulkan", "diffusion_model": "...Q8_0.gguf", "vae": "...",
22   "llm": "...Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf", "quant": "Q8_0", "args": ["--diffusion-fa"],
23   "gpu_policy": "auto", "reload": "lazy"|"eager", "max_n": 4, "max_side": 2048, "timeout_s": 3600,
24   "lib_dirs": [...], "uma": false, "need_mib": null, "out_dir": null, "keep_files": 64,
25   "native": false, "noise": "sdcpp"}
26   (native: Strata's own DiT runner, tools/image/sdcpp_native; CUDA / HIP builds.  noise: "sdcpp" (default) is
27   stable-diffusion.cpp's own noise; "strata" is Strata's generator, tools/image/sdcpp_noise: the same stream on every
28   operating system and CPU, built into sd-cli by setup --image-noise on.  "vae_decoder": "sdcpp" (default) is
29   stable-diffusion.cpp's VAE decoder; "strata" is Strata's own, src/image/vae via tools/image/sdcpp_vae, CUDA / HIP
30   builds only, built into sd-cli by setup --image-vae on)
31"""
32from __future__ import annotations
33
34import base64
35import contextlib
36import json
37import os
38import random
39import re
40import secrets
41import subprocess
42import tempfile
43import threading
44import time
45from pathlib import Path
46
47from strata_control.childenv import quiet_crash_env
48
49# Qwen-Image-2.1-Turbo's own schedule (model_index.json "sample_sigmas") plus the terminal 0, as Unsloth's card passes
50# it to sd-cli; it is an 8-step schedule, so another step count leaves the schedule to sd.cpp
51TURBO_SIGMAS = "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0"
52TURBO_STEPS = 8
53MODEL_NAME = "qwen-image-2.1-turbo"
54POLICIES = ("auto", "keep", "shrink", "unload")
55NOISES = ("sdcpp", "strata")
56# shown (log line at start, and as the failure of an image request) when the config asks for Strata's noise but the
57# built sd-cli does not have it: ONE next step, in plain words
58NOISE_MISSING = ("Image generation is set to use Strata's own noise (\"noise\": \"strata\" in the images settings), but "
59                 "the image program here was built without it. Run setup again with: --images qwen-image --image-noise on")
60VAE_DECODERS = ("sdcpp", "strata")
61VAE_DECODER_BACKENDS = ("cuda", "hip")
62# the same two cases for Strata's own VAE decoder (the owner's wording, 11-11)
63VAE_MISSING = ("Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the images "
64               "settings), but the image program here was built without it. Run setup again with: --images qwen-image "
65               "--image-vae on")
66VAE_BACKEND = ("Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the images "
67               "settings), which needs the CUDA (NVIDIA) or ROCm (AMD) build of the image program; this one was built "
68               "for {backend}. Set \"vae_decoder\" to \"sdcpp\" in the images settings.")   # {backend}: as setup prints it
69SIZE_STEP = 32                     # sd.cpp's Qwen-Image-2.1 docs: dimensions divisible by 32
70MIN_SIDE = 256
71FILE_NAME = re.compile(r"^[0-9a-f]{32}\.png$")
72STEP_LINE = re.compile(r"\|\s*(\d+)/(\d+)\s*-")      # sd.cpp's progress bar: "|====    | 3/8 - 14.1s/it"
73
74
75class ImageRequestError(ValueError):
76    """A request the image endpoint refuses (400)."""
77
78
79class ImageJobFailed(RuntimeError):
80    """sd-cli ended without the images (500); the message carries the end of its log."""
81
82
83def parse_size(value, max_side: int) -> tuple[int, int]:
84    """OpenAI's size, "1024x1024" (or "auto": 1024x1024) -> (width, height); each side a multiple of 32 from 256 to
85    max_side."""
86    if value is None or value == "auto":
87        return 1024, 1024
88    if not isinstance(value, str):
89        raise ImageRequestError("size: a string WIDTHxHEIGHT, e.g. \"1024x1024\"")
90    m = re.fullmatch(r"\s*(\d{2,5})\s*[xX×]\s*(\d{2,5})\s*", value)
91    if not m:
92        raise ImageRequestError(f"size: WIDTHxHEIGHT, e.g. \"1024x1024\", not {value!r}")
93    w, h = int(m.group(1)), int(m.group(2))
94    for side in (w, h):
95        if side < MIN_SIDE or side > max_side or side % SIZE_STEP:
96            raise ImageRequestError(f"size {w}x{h}: each side a multiple of {SIZE_STEP} from {MIN_SIDE} to {max_side}")
97    return w, h
98
99
100def _int_field(req: dict, key: str, lo: int, hi: int, default):
101    v = req.get(key)
102    if v is None:
103        return default
104    if isinstance(v, bool) or not isinstance(v, int) or not lo <= v <= hi:
105        raise ImageRequestError(f"{key}: a whole number from {lo} to {hi}")
106    return v
107
108
109def parse_request(req: dict, cfg: dict) -> dict:
110    """The fields of one /v1/images/generations request, checked.  Unknown OpenAI fields (quality, style, user,
111    moderation) are accepted and ignored; an output format other than PNG is refused.  OpenAI's background:
112    "transparent" keeps the model's own alpha; "opaque", "auto" or none puts the picture on white (flatten_png)."""
113    prompt = req.get("prompt")
114    if not isinstance(prompt, str) or not prompt.strip():
115        raise ImageRequestError("prompt: a non-empty string")
116    if len(prompt) > 16000:
117        raise ImageRequestError("prompt: at most 16000 characters")
118    if "\0" in prompt:
119        raise ImageRequestError("prompt: no NUL characters")
120    fmt = req.get("response_format") or "b64_json"
121    if fmt not in ("b64_json", "url"):
122        raise ImageRequestError("response_format: b64_json or url")
123    out_fmt = req.get("output_format")
124    if out_fmt not in (None, "png"):
125        raise ImageRequestError("output_format: only png")
126    background = req.get("background") or "auto"
127    if background not in BACKGROUNDS:
128        raise ImageRequestError("background: transparent, opaque or auto")
129    w, h = parse_size(req.get("size"), int(cfg.get("max_side") or 2048))
130    n = _int_field(req, "n", 1, int(cfg.get("max_n") or 4), 1)
131    steps = _int_field(req, "steps", 1, 100, int(cfg.get("steps") or TURBO_STEPS))
132    seed = _int_field(req, "seed", 0, 2**62, None)
133    if seed is None:
134        seed = random.SystemRandom().randrange(0, 2**31)
135    return {"prompt": prompt, "width": w, "height": h, "n": n, "steps": steps, "seed": seed, "response_format": fmt,
136            "background": background}
137
138
139def write_prompt(work: Path, prompt: str) -> Path:
140    """The job's prompt as a file for sd-cli's --prompt-file, readable by this user only (#4202).  Not on the command line:
141    every local account can read a process's arguments (ps, /proc/<pid>/cmdline).  Written as UTF-8 without newline
142    translation and read back by sd-cli as raw bytes, so the prompt is unchanged."""
143    path = work / "prompt.txt"
144    with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8", newline="") as f:
145        f.write(prompt)
146    return path
147
148
149def sd_cli_args(cfg: dict, job: dict, out_pattern: str, prompt_file: str) -> list[str]:
150    """The sd-cli command for one job: the model card's stable-diffusion.cpp command (8 steps, CFG 1, euler, Turbo's
151    sigmas, --diffusion-fa from the config's args), the prompt from `prompt_file` (write_prompt), the size, seed and
152    batch count, and the config's other args."""
153    cmd = [str(cfg["exe"]),
154           "--diffusion-model", str(cfg["diffusion_model"]), "--vae", str(cfg["vae"]), "--llm", str(cfg["llm"]),
155           "--prompt-file", prompt_file,
156           "--steps", str(job["steps"]), "--cfg-scale", "1.0", "--sampling-method", "euler",
157           "-W", str(job["width"]), "-H", str(job["height"])]
158    if job["steps"] == TURBO_STEPS:
159        cmd += ["--sigmas", str(cfg.get("sigmas") or TURBO_SIGMAS)]
160    cmd += ["-s", str(job["seed"])]
161    if job["n"] > 1:
162        cmd += ["-b", str(job["n"])]
163    cmd += ["-o", out_pattern]
164    cmd += [str(a) for a in (cfg.get("args") or [])]
165    model_args = []
166    if cfg.get("native") is True:                   # Strata's DiT runner inside sd-cli (CUDA / HIP builds)
167        model_args.append("qwen_image_2_1_native=1")
168    if cfg.get("noise") == "strata":                # Strata's noise generator inside sd-cli (tools/image/sdcpp_noise)
169        model_args.append("strata_noise=1")
170    if cfg.get("vae_decoder") == "strata":          # Strata's VAE decoder inside sd-cli (tools/image/sdcpp_vae)
171        model_args.append("strata_vae=1")
172    if model_args:
173        cmd += ["--model-args", ",".join(model_args)]
174    return cmd
175
176
177def image_env(cfg: dict, base: dict | None = None) -> dict:
178    """sd-cli's environment: the libraries its backend needs (ROCm's, setup's lib_dirs) first on the search path, the
179    GPU to use when the config names one, and the config's own "env"."""
180    env = quiet_crash_env(dict(os.environ if base is None else base))      # ggml's backtrace starts gdb: never on a user's machine
181    dirs = [str(d) for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()]
182    if dirs:
183        var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
184        env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else []))
185    gpu = cfg.get("gpu")
186    if gpu is not None:
187        var = {"cuda": "CUDA_VISIBLE_DEVICES", "hip": "HIP_VISIBLE_DEVICES",
188               "vulkan": "GGML_VK_VISIBLE_DEVICES"}.get(cfg.get("backend"))
189        if var:
190            # one card is "1"; a list ([1, 0], "1,0") is every one of them, in order - str() of a list is not a device list
191            env[var] = ",".join(str(x).strip() for x in gpu if str(x).strip() != "") if isinstance(gpu, (list, tuple)) else str(gpu)
192            if var == "CUDA_VISIBLE_DEVICES":
193                env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
194    for k, v in (cfg.get("env") or {}).items():
195        env[str(k)] = str(v)
196    return env
197
198
199# ------------------------------------------------------------------------------- the model's transparency
200# Qwen-Image-2.1's VAE decodes RGBA: the model leaves some backgrounds transparent, with a flat key colour (often
201# purple) under alpha 0.  By default the picture is put on white and written as an 8-bit RGB PNG; every chunk other
202# than IHDR / IDAT (sd-cli's "parameters" text above all) is copied byte for byte.  background: "transparent" keeps
203# sd-cli's PNG unchanged.
204BACKGROUNDS = ("auto", "opaque", "transparent")
205PNG_SIG = b"\x89PNG\r\n\x1a\n"
206FLATTEN_ZLIB_LEVEL = 6      # 1024x1024: 0.03 s, 1536x1024: 0.14 s to encode, the smallest file of levels 1/3/6
207
208
209def _png_chunks(data: bytes) -> list[tuple[bytes, bytes]]:
210    """[(type, the whole chunk's bytes)] of a PNG; ValueError on anything malformed."""
211    import struct
212    import zlib
213    if data[:8] != PNG_SIG:
214        raise ValueError("not a PNG")
215    out, i = [], 8
216    while i < len(data):
217        if i + 12 > len(data):
218            raise ValueError("truncated chunk")
219        n = struct.unpack(">I", data[i:i + 4])[0]
220        end = i + 12 + n
221        if end > len(data):
222            raise ValueError("truncated chunk")
223        t = data[i + 4:i + 8]
224        if struct.unpack(">I", data[end - 4:end])[0] != zlib.crc32(data[i + 4:end - 4]) & 0xFFFFFFFF:
225            raise ValueError(f"bad CRC in {t!r}")
226        out.append((t, data[i:end]))
227        i = end
228        if t == b"IEND":
229            break
230    if not out or out[0][0] != b"IHDR" or out[-1][0] != b"IEND":
231        raise ValueError("no IHDR / IEND")
232    return out
233
234
235def _rgba_pixels(data: bytes, w: int, h: int, cs):
236    """The RGBA pixels as a uint8 array [h, w, 4]: Pillow when it imports, else zlib + numpy (PNG filters undone
237    row by row; Average / Paeth rows go pixel by pixel, about 1-3 s for a large picture)."""
238    import numpy as np
239    try:
240        import io
241        from PIL import Image
242        with Image.open(io.BytesIO(data)) as im:
243            if im.mode == "RGBA":
244                a = np.asarray(im)
245                if a.shape == (h, w, 4):
246                    return a
247    except Exception:  # noqa: BLE001 - a missing or broken Pillow: the fallback below
248        pass
249    import zlib
250    raw = zlib.decompress(b"".join(c[8:-4] for t, c in cs if t == b"IDAT"))
251    stride = w * 4
252    if len(raw) != h * (1 + stride):
253        raise ValueError("IDAT size")
254    rows = np.frombuffer(raw, np.uint8).reshape(h, 1 + stride)
255    out = np.zeros((h, stride), np.uint8)
256    prev = np.zeros(stride, np.int32)
257    for y in range(h):
258        f, line = int(rows[y, 0]), rows[y, 1:].astype(np.int32)
259        if f == 0:
260            cur = line
261        elif f == 1:
262            cur = np.cumsum(line.reshape(w, 4), axis=0).reshape(-1) & 255
263        elif f == 2:
264            cur = (line + prev) & 255
265        elif f in (3, 4):
266            ln, pv = line.tolist(), prev.tolist()
267            cl = [0] * stride
268            for x in range(stride):
269                a = cl[x - 4] if x >= 4 else 0
270                b = pv[x]
271                if f == 3:
272                    cl[x] = (ln[x] + ((a + b) >> 1)) & 255
273                else:
274                    c = pv[x - 4] if x >= 4 else 0
275                    p = a + b - c
276                    pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
277                    cl[x] = (ln[x] + (a if pa <= pb and pa <= pc else (b if pb <= pc else c))) & 255
278            cur = np.array(cl, np.int32)
279        else:
280            raise ValueError(f"PNG filter {f}")
281        out[y] = cur
282        prev = cur
283    return out.reshape(h, w, 4)
284
285
286def png_has_alpha(data: bytes) -> bool:
287    """An alpha channel by the IHDR's colour type (4 grey + alpha, 6 RGBA); False for anything unreadable."""
288    return len(data) > 25 and data[:8] == PNG_SIG and data[12:16] == b"IHDR" and data[25] in (4, 6)
289
290
291def flatten_png(data: bytes) -> bytes:
292    """An 8-bit RGBA PNG -> the same picture on white as an 8-bit RGB PNG (round(rgb * a + 255 * (1 - a)), a in
293    [0, 1]), every chunk other than IHDR / IDAT copied byte for byte.  Any other PNG comes back unchanged.
294    Raises on a malformed PNG (the caller then keeps the original)."""
295    import struct
296    import zlib
297
298    import numpy as np
299    cs = _png_chunks(data)
300    w, h, depth, ctype, comp, filt, inter = struct.unpack(">IIBBBBB", cs[0][1][8:21])
301    if ctype != 6 or depth != 8:
302        return data                                  # RGB (or anything else): nothing to flatten
303    if comp or filt or inter:
304        raise ValueError("unsupported PNG layout")
305    rgba = _rgba_pixels(data, w, h, cs)
306    a = rgba[..., 3:4].astype(np.float64) / 255.0
307    rgb = np.floor(rgba[..., :3].astype(np.float64) * a + 255.0 * (1.0 - a) + 0.5)
308    rgb = np.clip(rgb, 0, 255).astype(np.uint8)
309    raw = np.concatenate([np.zeros((h, 1), np.uint8), rgb.reshape(h, w * 3)], axis=1).tobytes()   # filter 0 rows
310
311    def chunk(t: bytes, d: bytes) -> bytes:
312        return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
313    out, idat_done = [PNG_SIG], False
314    for t, c in cs:
315        if t == b"IHDR":
316            out.append(chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)))
317        elif t == b"IDAT":
318            if not idat_done:
319                out.append(chunk(b"IDAT", zlib.compress(raw, FLATTEN_ZLIB_LEVEL)))
320                idat_done = True
321        else:
322            out.append(c)                            # tEXt "parameters", IEND, ...: byte for byte
323    return b"".join(out)
324
325
326TIMING = re.compile(r"(get_learned_condition|sampling|decode_first_stage) completed, taking ([0-9]+(?:\.[0-9]+)?) ?(ms|s)\b")
327
328
329def log_figures(log: str) -> dict:
330    """The job's stage times from sd-cli's log: text_encode_ms, sampling_s, vae_decode_s (the last of each line).
331    stable-diffusion.cpp 2988060 (the pinned commit) prints seconds for all three ("taking 0.70s"); the "N ms" form is
332    read as well."""
333    out = {}
334    for stage, num, unit in TIMING.findall(log):
335        secs = float(num) / 1000 if unit == "ms" else float(num)
336        key, val = {"get_learned_condition": ("text_encode_ms", secs * 1000), "sampling": ("sampling_s", secs),
337                    "decode_first_stage": ("vae_decode_s", secs)}[stage]
338        out[key] = round(val, 3)
339    return out
340
341
342def need_mib(cfg: dict, width: int, height: int) -> int:
343    """The GPU memory an image job is planned with: the three model files plus the working buffers (about 2 GiB plus
344    4 GiB per megapixel at Turbo's settings; the 780M baseline peaked 7.4 GB over the weights at 1024x1024 on HIP);
345    the config's "need_mib" overrides it."""
346    if cfg.get("need_mib"):
347        return int(cfg["need_mib"])
348    files = 0
349    for k in ("diffusion_model", "vae", "llm"):
350        try:
351            files += Path(cfg[k]).stat().st_size
352        except (OSError, KeyError, TypeError):
353            pass
354    work = (2 << 30) + int(4 * (1 << 30) * width * height / (1024 * 1024))
355    return (files + work) >> 20
356
357
358class ImageGen:
359    """One sd-cli process per request, one request at a time (the service's turn, gpu_turn)."""
360
361    def __init__(self, cfg: dict, log=None):
362        self.cfg = dict(cfg)
363        policy = self.cfg.get("gpu_policy") or "auto"
364        if policy not in POLICIES:
365            raise ValueError(f'images "gpu_policy" must be one of {", ".join(POLICIES)}, not {policy!r}')
366        reload = self.cfg.get("reload") or "lazy"
367        if reload not in ("lazy", "eager"):
368            raise ValueError(f'images "reload" must be lazy or eager, not {reload!r}')
369        for k in ("exe", "diffusion_model", "vae", "llm"):
370            if not isinstance(self.cfg.get(k), str) or not self.cfg[k]:
371                raise ValueError(f'the config\'s "images" section needs "{k}" (run setup with --images again)')
372        if self.cfg.get("noise", "sdcpp") not in NOISES:
373            raise ValueError(f'images "noise" must be one of {", ".join(NOISES)}, not {self.cfg["noise"]!r}')
374        if self.cfg.get("vae_decoder", "sdcpp") not in VAE_DECODERS:
375            raise ValueError(f'images "vae_decoder" must be one of {", ".join(VAE_DECODERS)}, '
376                             f'not {self.cfg["vae_decoder"]!r}')
377        self.policy, self.reload = policy, reload
378        self.model = self.cfg.get("model_name") or MODEL_NAME
379        self.log = log
380        out = self.cfg.get("out_dir")
381        self.dir = Path(out) if out else Path(tempfile.mkdtemp(prefix="strata-images-"))
382        self.dir.mkdir(parents=True, exist_ok=True)
383        self.keep_files = int(self.cfg.get("keep_files") or 64)
384        self.lock = threading.Lock()              # one sd-cli at a time even when the service's turn is not taken
385        self.totals = {"images": 0, "jobs": 0, "seconds": 0.0, "failed": 0}
386        self.last = None                           # the last job's figures (/v1/status)
387        self.progress = None                       # (step, steps) of the running job
388
389    def missing(self) -> list[str]:
390        return [self.cfg[k] for k in ("exe", "diffusion_model", "vae", "llm") if not Path(self.cfg[k]).exists()]
391
392    def noise_problem(self) -> str | None:
393        """NOISE_MISSING when the config says "noise": "strata" and the sd-cli it runs was not built with Strata's noise
394        generator (its BUILD.json, written by setup, has no "noise" stamp); else None.  Without this the arg would be
395        ignored and the picture would quietly get stable-diffusion.cpp's noise."""
396        if self.cfg.get("noise") != "strata":
397            return None
398        try:
399            meta = json.loads(Path(self.cfg["exe"]).with_name("BUILD.json").read_text(encoding="utf-8"))
400        except (OSError, ValueError):
401            return NOISE_MISSING
402        return None if isinstance(meta, dict) and meta.get("noise") else NOISE_MISSING
403
404    def vae_problem(self) -> str | None:
405        """VAE_BACKEND when the config says "vae_decoder": "strata" for a backend that has no such decoder (Vulkan,
406        CPU), VAE_MISSING when the sd-cli it runs was not built with it (no "vae_decoder" stamp in its BUILD.json);
407        else None.  Without this sd-cli would ignore the arg and decode with stable-diffusion.cpp's decoder."""
408        if self.cfg.get("vae_decoder") != "strata":
409            return None
410        if self.cfg.get("backend") not in VAE_DECODER_BACKENDS:
411            return VAE_BACKEND.format(backend=self.cfg.get("backend") or "another backend")
412        try:
413            meta = json.loads(Path(self.cfg["exe"]).with_name("BUILD.json").read_text(encoding="utf-8"))
414        except (OSError, ValueError):
415            return VAE_MISSING
416        return None if isinstance(meta, dict) and meta.get("vae_decoder") else VAE_MISSING
417
418    def _say(self, text: str) -> None:
419        print(f"[strata] {text}", flush=True)
420        if self.log is not None:
421            try:
422                self.log.write(f"[images] {text}\n")
423                self.log.flush()
424            except (OSError, ValueError):
425                pass
426
427    def _prune(self) -> None:
428        """Keep the newest keep_files PNGs of response_format url (the oldest go)."""
429        files = sorted((p for p in self.dir.glob("*.png") if FILE_NAME.match(p.name)), key=lambda p: p.stat().st_mtime)
430        for p in files[:max(0, len(files) - self.keep_files)]:
431            with contextlib.suppress(OSError):
432                p.unlink()
433
434    def file(self, name: str) -> Path | None:
435        """A stored image (response_format url) by its name, or None."""
436        if not FILE_NAME.match(name or ""):
437            return None
438        p = self.dir / name
439        return p if p.is_file() else None
440
441    def run(self, job: dict, cancel: threading.Event | None = None) -> tuple[list[bytes], dict]:
442        """Run sd-cli for `job` (parse_request's dict) -> (the PNG files' bytes in order, figures).  The caller holds
443        the GPU turn.  ImageJobFailed when sd-cli fails, times out or is cancelled."""
444        problem = self.noise_problem() or self.vae_problem()
445        if problem:
446            self.totals["failed"] += 1
447            raise ImageJobFailed(problem)
448        work = Path(tempfile.mkdtemp(prefix="job-", dir=self.dir))
449        pattern = str(work / "img_%d.png")
450        try:
451            cmd = sd_cli_args(self.cfg, job, pattern, str(write_prompt(work, job["prompt"])))
452        except BaseException:                       # the prompt file was not made: nothing else is in the folder yet
453            for p in work.iterdir():
454                with contextlib.suppress(OSError):
455                    p.unlink()
456            with contextlib.suppress(OSError):
457                work.rmdir()
458            raise
459        timeout = float(self.cfg.get("timeout_s") or 3600)
460        logf = work / "sd-cli.log"
461        t0 = time.monotonic()
462        self.progress = (0, job["steps"])
463        with self.lock:
464            with open(logf, "w", encoding="utf-8", errors="replace") as lf:
465                try:
466                    from serve import lifeline
467                    proc = lifeline.popen(cmd, "image", stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
468                                          stdin=subprocess.DEVNULL, env=image_env(self.cfg),
469                                          cwd=str(work), text=True, errors="replace", bufsize=1)
470                except OSError as e:
471                    raise ImageJobFailed(f"sd-cli did not start ({cmd[0]}): {e}") from e
472                why = None
473
474                def pump():
475                    for line in proc.stdout:
476                        lf.write(line)
477                        m = STEP_LINE.search(line)
478                        if m:
479                            self.progress = (int(m.group(1)), int(m.group(2)))
480                reader = threading.Thread(target=pump, daemon=True)
481                reader.start()
482                while proc.poll() is None:
483                    if cancel is not None and cancel.is_set():
484                        why = "cancelled (the client left)"
485                    elif time.monotonic() - t0 > timeout:
486                        why = f"it ran past timeout_s ({timeout:g} s)"
487                    if why:
488                        proc.kill()
489                        break
490                    time.sleep(0.2)
491                with contextlib.suppress(subprocess.TimeoutExpired):
492                    proc.wait(timeout=30)
493                reader.join(timeout=10)
494        secs = time.monotonic() - t0
495        self.progress = None
496        log = logf.read_text(encoding="utf-8", errors="replace")
497        outs = [work / f"img_{i}.png" for i in range(job["n"])]
498        try:
499            if why or proc.returncode != 0 or not all(p.is_file() for p in outs):
500                self.totals["failed"] += 1
501                tail = "\n".join(log.strip().splitlines()[-12:])
502                what = why or (f"sd-cli exited with code {proc.returncode}" if proc.returncode
503                               else "sd-cli wrote no image")
504                self._say(f"image job failed: {what}\n{tail}")
505                raise ImageJobFailed(f"{what}; the end of its log:\n{tail}")
506            images = [p.read_bytes() for p in outs]
507        finally:
508            for p in work.iterdir():
509                with contextlib.suppress(OSError):
510                    p.unlink()
511            with contextlib.suppress(OSError):
512                work.rmdir()
513        figures = {"seconds": round(secs, 2), "steps": job["steps"], "n": job["n"],
514                   "size": f"{job['width']}x{job['height']}", "seed": job["seed"],
515                   "backend": self.cfg.get("backend"), "quant": self.cfg.get("quant")}
516        figures.update(log_figures(log))
517        if job.get("background", "auto") != "transparent":
518            t1 = time.monotonic()
519            flat = [self._flatten(png) for png in images]
520            images = [png for png, _ in flat]
521            job["alpha_kept"] = any(kept for _, kept in flat)     # a picture went out with its alpha after all
522            figures["flatten_s"] = round(time.monotonic() - t1, 3)
523        self.totals["jobs"] += 1
524        self.totals["images"] += job["n"]
525        self.totals["seconds"] += secs
526        self.last = figures
527        return images, figures
528
529    def _flatten(self, png: bytes) -> tuple[bytes, bool]:
530        """flatten_png, never failing the request -> (the picture, whether it still has an alpha channel).  On any
531        error the picture goes out as sd-cli wrote it."""
532        try:
533            out = flatten_png(png)
534            return out, png_has_alpha(out)
535        except Exception as e:  # noqa: BLE001 - numpy missing, a malformed PNG, ...: the original picture
536            self._say(f"image: the picture keeps its transparency (it could not be put on white: {e})")
537            return png, png_has_alpha(png)
538
539    def store(self, data: bytes) -> str:
540        """Keep one PNG for response_format url -> its file name (32 random hex digits: the name is the access)."""
541        name = secrets.token_hex(16) + ".png"
542        (self.dir / name).write_bytes(data)
543        self._prune()
544        return name
545
546    def response(self, images: list[bytes], job: dict, figures: dict, base_url: str) -> dict:
547        data = []
548        for i, png in enumerate(images):
549            item = {"revised_prompt": job["prompt"], "seed": job["seed"] + i}
550            if job["response_format"] == "url":
551                item["url"] = f"{base_url}/v1/images/files/{self.store(png)}"
552            else:
553                item["b64_json"] = base64.b64encode(png).decode("ascii")
554            data.append(item)
555        return {"created": int(time.time()), "data": data, "model": self.model,
556                "output_format": "png", "size": f"{job['width']}x{job['height']}", "strata": figures,
557                "background": "transparent" if job.get("background") == "transparent" or job.get("alpha_kept")
558                else "opaque"}
559
560    def status(self) -> dict:
561        out = {"enabled": True, "model": self.model, "backend": self.cfg.get("backend"),
562               "quant": self.cfg.get("quant"), "gpu_policy": self.policy, **self.totals}
563        if self.progress:
564            out["step"], out["steps"] = self.progress
565        if self.last:
566            out["last"] = self.last
567        return out
568
569
570# ------------------------------------------------------------------------------------------- the GPU turn
571def resolve_policy(svc, gen: ImageGen, need: int) -> str:
572    """auto -> keep / shrink / unload for this job (see the module's docstring); a fixed policy is kept, except that
573    an engine that is not running has nothing to give back (keep)."""
574    eng = svc.engine
575    running = not hasattr(eng, "alive") or eng.alive()
576    if not running or not hasattr(eng, "unload"):
577        return "keep"
578    if gen.policy != "auto":
579        return gen.policy
580    if gen.cfg.get("uma"):
581        return "keep"                         # an APU: the image job and the engine share the RAM either way
582    free = svc.free_vram_mib()
583    if free is None or free >= need:
584        return "keep"
585    if engine_elastic(eng):
586        return "shrink"
587    return "unload"
588
589
590def engine_elastic(eng) -> bool:
591    """An engine that resizes its expert cache on request (--vram-elastic, #533)."""
592    if not hasattr(eng, "vram"):
593        return False
594    if (getattr(eng, "info", None) or {}).get("vram_elastic"):
595        return True
596    spawn = getattr(eng, "spawn", None)
597    args = spawn[1] if isinstance(spawn, (list, tuple)) and len(spawn) > 1 else []
598    return "--vram-elastic" in (args or [])
599
600
601def _client_gone(svc) -> Exception:
602    """The server module's ClientGone (it may run as __main__, so not imported by name)."""
603    import sys
604    return getattr(sys.modules.get(type(svc).__module__), "ClientGone", RuntimeError)()
605
606
607@contextlib.contextmanager
608def gpu_turn(svc, gen: ImageGen, job: dict, cancel: threading.Event | None = None):
609    """The image job's turn on the GPU: the service's FIFO (and, with parallel requests, the engine's control lines
610    once no slot is generating), and the text engine made room for it per the policy.  Yields the policy used."""
611    with svc.status_lock:
612        svc.status["queued"] += 1
613    queued = True
614    try:
615        with svc._turn(cancel):
616            with svc.status_lock:
617                svc.status["queued"] -= 1
618            queued = False
619            ctl = getattr(svc.engine, "ctl", None) if getattr(svc.engine, "batch", 0) else None
620            if ctl is not None:
621                while not ctl.acquire(timeout=0.25):
622                    if cancel is not None and cancel.is_set():
623                        raise _client_gone(svc)
624            try:
625                if ctl is not None:                   # running parallel requests finish first
626                    while getattr(svc, "live_reqs", None):
627                        if cancel is not None and cancel.is_set():
628                            raise _client_gone(svc)
629                        time.sleep(0.25)
630                need = need_mib(gen.cfg, job["width"], job["height"])
631                policy = resolve_policy(svc, gen, need)
632                with svc.status_lock:
633                    svc.status.update(busy=True, phase="generating an image", started=time.time(),
634                                      first_token=None, prompt_tokens=None, generated=None, max_tokens=None)
635                restore = _make_room(svc, gen, policy, need)
636                try:
637                    yield policy
638                finally:
639                    _give_back(svc, gen, policy, restore)
640                    with svc.status_lock:
641                        svc.status["busy"] = False
642                    svc.last_request_at = time.time()
643            finally:
644                if ctl is not None:
645                    ctl.release()
646    finally:
647        if queued:
648            with svc.status_lock:
649                svc.status["queued"] -= 1
650
651
652def _make_room(svc, gen: ImageGen, policy: str, need: int):
653    """Do what `policy` says before the job; -> what _give_back needs."""
654    eng = svc.engine
655    if policy == "shrink":
656        try:
657            out = eng.vram(need)
658            gen._say(f"image job: the engine's expert cache gave VRAM back ({out.get('vram_free_mib')} MiB free)")
659            return "shrunk"
660        except Exception as e:                       # noqa: BLE001 - the job still runs, with what is free
661            gen._say(f"image job: the engine could not give VRAM back ({e}); the job runs with what is free")
662            return None
663    if policy == "unload":
664        saved = None
665        if hasattr(eng, "session_file") and not getattr(eng, "batch", 0):
666            path = str(gen.dir / f"llm-session-{secrets.token_hex(6)}.bin")
667            try:
668                r = eng.session_file("save", path)
669                saved = path
670                gen._say(f"image job: the conversation ({r.get('tokens')} tokens) saved; unloading the model")
671            except Exception as e:                   # noqa: BLE001 - unloading still frees the GPU
672                gen._say(f"image job: the conversation could not be saved ({e}); unloading the model")
673                with contextlib.suppress(OSError):
674                    os.unlink(path)
675        eng.unload()
676        if svc.vision is not None and hasattr(svc.vision, "unload"):
677            svc.vision.unload()
678        return saved or "unloaded"
679    return None
680
681
682def _give_back(svc, gen: ImageGen, policy: str, restore) -> None:
683    eng = svc.engine
684    if restore == "shrunk":
685        try:
686            eng.vram(svc.vram_reserve)               # the reserve asked for last (None: the start's)
687        except Exception as e:                       # noqa: BLE001
688            gen._say(f"image job: the expert cache did not grow back ({e}); POST /v1/vram can retry")
689    elif policy == "unload" and restore:
690        if restore != "unloaded":
691            svc.restore_after_load = restore         # Service.ensure_loaded restores it after the next start
692        if gen.reload == "eager":
693            try:
694                svc.ensure_loaded()                  # the caller still holds the FIFO
695            except Exception as e:                   # noqa: BLE001 - the next request tries again
696                gen._say(f"image job: the model did not load again yet ({e}); the next request loads it")
697
698
699def restore_session(svc) -> None:
700    """After an engine start: restore the conversation an image job saved before it unloaded the engine."""
701    path = getattr(svc, "restore_after_load", None)
702    if not path:
703        return
704    svc.restore_after_load = None
705    try:
706        r = svc.engine.session_file("restore", path)
707        print(f"[strata] the conversation from before the image job is back ({r.get('tokens')} tokens)", flush=True)
708    except Exception as e:                           # noqa: BLE001 - the engine runs, without the old cache
709        print(f"[strata] the conversation from before the image job was not restored ({e}); the next request "
710              "reads its prompt again", flush=True)
711    finally:
712        with contextlib.suppress(OSError):
713            os.unlink(path)