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.8 KiB676 linesraw
1"""POST /v1/images/generations (serve/images.py): the request shape, the sd-cli command, the GPU turn and its policies,
2over HTTP with a stand-in sd-cli (serve/fixtures/fake_sd_cli.py) and the mock engine.
3
4    python -m serve.test_images
5"""
6import base64
7import json
8import os
9import sys
10import tempfile
11import threading
12import time
13import unittest
14import urllib.error
15import urllib.request
16from pathlib import Path
17from unittest import mock
18
19from serve import images as images_api
20from serve.frontend import ChatTemplate
21from serve.server import ByteTokenizer, MockEngine, Service, serve
22
23ROOT = Path(__file__).resolve().parents[1]
24FAKE = ROOT / "serve" / "fixtures" / "fake_sd_cli.py"
25REAL_ARGS = images_api.sd_cli_args
26
27
28def fake_args(cfg, job, out, prompt_file):
29    """sd-cli's command, run through Python (the stand-in is a script)."""
30    return [sys.executable, str(FAKE), *REAL_ARGS(cfg, job, out, prompt_file)[1:]]
31
32
33def image_cfg(d, **kw):
34    files = {}
35    for k in ("diffusion_model", "vae", "llm"):
36        p = Path(d) / f"{k}.bin"
37        p.write_bytes(b"x" * 1024)
38        files[k] = str(p)
39    return {"exe": str(FAKE), "backend": "vulkan", "quant": "Q8_0", "args": ["--diffusion-fa"],
40            "out_dir": str(Path(d) / "out"), **files, **kw}
41
42
43class Request(unittest.TestCase):
44    CFG = {"max_n": 4, "max_side": 2048}
45
46    def test_defaults(self):
47        j = images_api.parse_request({"prompt": "a cat"}, self.CFG)
48        self.assertEqual((j["width"], j["height"], j["n"], j["steps"], j["response_format"]),
49                         (1024, 1024, 1, 8, "b64_json"))
50        self.assertTrue(0 <= j["seed"] < 2**31)
51
52    def test_fields(self):
53        j = images_api.parse_request({"prompt": "a cat", "size": "1536x1024", "n": 2, "steps": 4, "seed": 7,
54                                      "response_format": "url", "quality": "hd", "model": "dall-e-3"}, self.CFG)
55        self.assertEqual((j["width"], j["height"], j["n"], j["steps"], j["seed"], j["response_format"]),
56                         (1536, 1024, 2, 4, 7, "url"))
57        self.assertEqual(images_api.parse_request({"prompt": "x", "size": "auto"}, self.CFG)["width"], 1024)
58
59    def test_refused(self):
60        bad = [{}, {"prompt": ""}, {"prompt": 5}, {"prompt": "x", "n": 0}, {"prompt": "x", "n": 5},
61               {"prompt": "x", "n": True}, {"prompt": "x", "size": "1000x1000"}, {"prompt": "x", "size": "128x128"},
62               {"prompt": "x", "size": "4096x1024"}, {"prompt": "x", "size": "big"}, {"prompt": "x", "steps": 0},
63               {"prompt": "x", "seed": -1}, {"prompt": "x", "seed": "1"}, {"prompt": "x", "response_format": "png"},
64               {"prompt": "x", "output_format": "jpeg"}, {"prompt": "a\0b"}]
65        for req in bad:
66            with self.subTest(req=req), self.assertRaises(images_api.ImageRequestError):
67                images_api.parse_request(req, self.CFG)
68
69
70class Command(unittest.TestCase):
71    def test_the_model_cards_command(self):
72        """Unsloth's stable-diffusion.cpp command for Turbo: 8 steps, CFG 1, euler, the Turbo sigmas, --diffusion-fa."""
73        cfg = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf",
74               "args": ["--diffusion-fa", "--vae-tiling"]}
75        job = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42}
76        self.assertEqual(images_api.sd_cli_args(cfg, job, "o/img_%d.png", "o/prompt.txt"), [
77            "sd-cli", "--diffusion-model", "dit.gguf", "--vae", "vae.st", "--llm", "te.gguf",
78            "--prompt-file", "o/prompt.txt",
79            "--steps", "8", "--cfg-scale", "1.0", "--sampling-method", "euler", "-W", "1024", "-H", "768",
80            "--sigmas", "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0",
81            "-s", "42", "-o", "o/img_%d.png", "--diffusion-fa", "--vae-tiling"])
82
83    def test_other_steps_and_batch(self):
84        cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l"}
85        cmd = images_api.sd_cli_args(cfg, {"prompt": "p", "width": 512, "height": 512, "n": 3, "steps": 4,
86                                           "seed": 1}, "x", "p.txt")
87        self.assertNotIn("--sigmas", cmd)          # Turbo's sigmas are an 8-step schedule
88        self.assertEqual(cmd[cmd.index("-b") + 1], "3")
89
90    def test_prompt_not_on_the_command_line(self):
91        """#4202: other local accounts can read process arguments: the prompt goes to sd-cli in an owner-only file."""
92        cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l"}
93        job = {"prompt": "a private\r\nprompt ü \U0001f98a", "width": 512, "height": 512, "n": 1, "steps": 8, "seed": 1}
94        with tempfile.TemporaryDirectory() as d:
95            path = images_api.write_prompt(Path(d), job["prompt"])
96            self.assertEqual(path.read_bytes(), job["prompt"].encode("utf-8"))      # no newline translation
97            if os.name != "nt":
98                self.assertEqual(path.stat().st_mode & 0o777, 0o600)
99            with self.assertRaises(FileExistsError):                                  # never writes through an existing file
100                images_api.write_prompt(Path(d), "again")
101            cmd = images_api.sd_cli_args(cfg, job, "x", str(path))
102        self.assertNotIn(job["prompt"], cmd)
103        self.assertFalse(any("private" in part for part in cmd), cmd)
104        self.assertNotIn("-p", cmd)
105        self.assertEqual(cmd[cmd.index("--prompt-file") + 1], str(path))
106
107    def test_native_switch(self):
108        cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "native": True}
109        job = {"prompt": "p", "width": 512, "height": 512, "n": 1, "steps": 8, "seed": 1}
110        self.assertEqual(images_api.sd_cli_args(cfg, job, "x", "p.txt")[-2:], ["--model-args", "qwen_image_2_1_native=1"])
111        cfg["native"] = False
112        self.assertNotIn("--model-args", images_api.sd_cli_args(cfg, job, "x", "p.txt"))
113
114    CARD = ["sd-cli", "--diffusion-model", "dit.gguf", "--vae", "vae.st", "--llm", "te.gguf",
115            "--prompt-file", "o/prompt.txt",
116            "--steps", "8", "--cfg-scale", "1.0", "--sampling-method", "euler", "-W", "1024", "-H", "768",
117            "--sigmas", "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0",
118            "-s", "42", "-o", "o/img_%d.png", "--diffusion-fa", "--vae-tiling"]
119
120    def test_noise_switch_off_leaves_the_command_line_alone(self):
121        """images "noise" absent or "sdcpp" (the default): the exact argument list of before the switch existed."""
122        job = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42}
123        base = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf",
124                "args": ["--diffusion-fa", "--vae-tiling"]}
125        for extra in ({}, {"noise": "sdcpp"}, {"noise": None}, {"native": False, "noise": "sdcpp"}):
126            with self.subTest(extra=extra):
127                self.assertEqual(images_api.sd_cli_args({**base, **extra}, job, "o/img_%d.png", "o/prompt.txt"), self.CARD)
128        # and the native switch alone is still the last two arguments, as before
129        self.assertEqual(images_api.sd_cli_args({**base, "native": True}, job, "o/img_%d.png", "o/prompt.txt"),
130                         self.CARD + ["--model-args", "qwen_image_2_1_native=1"])
131
132    def test_noise_switch_on_is_one_model_args_string(self):
133        job = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42}
134        base = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf",
135                "args": ["--diffusion-fa", "--vae-tiling"]}
136        self.assertEqual(images_api.sd_cli_args({**base, "noise": "strata"}, job, "o/img_%d.png", "o/prompt.txt"),
137                         self.CARD + ["--model-args", "strata_noise=1"])
138        both = images_api.sd_cli_args({**base, "noise": "strata", "native": True}, job, "o/img_%d.png", "o/prompt.txt")
139        self.assertEqual(both, self.CARD + ["--model-args", "qwen_image_2_1_native=1,strata_noise=1"])
140        self.assertEqual(both.count("--model-args"), 1)
141
142    def test_noise_value_is_checked(self):
143        with tempfile.TemporaryDirectory() as d:
144            cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "out_dir": d}
145            for ok in ("sdcpp", "strata"):
146                images_api.ImageGen({**cfg, "noise": ok})
147            for bad in ("on", "", "Strata", True, 1):
148                with self.subTest(bad=bad), self.assertRaises(ValueError):
149                    images_api.ImageGen({**cfg, "noise": bad})
150
151
152class NoiseRefusal(unittest.TestCase):
153    """images "noise": "strata" with an sd-cli that was built without the generator: the job is refused, in plain
154    words with one next step, instead of quietly running on stable-diffusion.cpp's noise."""
155
156    WORDS = ("Image generation is set to use Strata's own noise (\"noise\": \"strata\" in the images settings), but the "
157             "image program here was built without it. Run setup again with: --images qwen-image --image-noise on")
158
159    def gen(self, d, build=None, **kw):
160        cfg = image_cfg(d, noise="strata", **kw)
161        exe = Path(d) / "engine-image" / "sd-cli"
162        exe.parent.mkdir(exist_ok=True)
163        exe.write_bytes(b"x")
164        cfg["exe"] = str(exe)
165        if build is not None:
166            (exe.parent / "BUILD.json").write_text(build if isinstance(build, str) else json.dumps(build))
167        return images_api.ImageGen(cfg)
168
169    def test_the_words(self):
170        self.assertEqual(images_api.NOISE_MISSING, self.WORDS)
171
172    def test_problem_by_build_json(self):
173        with tempfile.TemporaryDirectory() as d:
174            self.assertEqual(self.gen(d).noise_problem(), self.WORDS)                       # no BUILD.json
175        for build in ({"sd_cpp": "x", "backend": "cuda"}, {"noise": ""}, "not json", "[1]", "{"):
176            with self.subTest(build=build), tempfile.TemporaryDirectory() as d:
177                self.assertEqual(self.gen(d, build).noise_problem(), self.WORDS)
178        with tempfile.TemporaryDirectory() as d:
179            self.assertIsNone(self.gen(d, {"sd_cpp": "x", "noise": "0123456789abcdef"}).noise_problem())
180
181    def test_switch_off_asks_nothing(self):
182        with tempfile.TemporaryDirectory() as d:
183            for extra in ({}, {"noise": "sdcpp"}):
184                cfg = {**image_cfg(d), **extra}
185                self.assertIsNone(images_api.ImageGen(cfg).noise_problem())      # no BUILD.json needed
186
187    def test_a_job_is_refused_before_sd_cli_starts(self):
188        with tempfile.TemporaryDirectory() as d:
189            g = self.gen(d)
190            job = images_api.parse_request({"prompt": "a cat"}, {})
191            before = sorted(p.name for p in g.dir.iterdir())
192            with mock.patch("serve.lifeline.popen") as popen, self.assertRaises(images_api.ImageJobFailed) as cm:
193                g.run(job)
194            popen.assert_not_called()
195            self.assertEqual(str(cm.exception), self.WORDS)
196            self.assertEqual(sorted(p.name for p in g.dir.iterdir()), before)       # no job folder left behind
197            self.assertEqual(g.totals["failed"], 1)
198
199    def test_env(self):
200        env = images_api.image_env({"backend": "cuda", "gpu": 1, "env": {"X": 2}}, {"PATH": "p"})
201        self.assertEqual((env["CUDA_VISIBLE_DEVICES"], env["CUDA_DEVICE_ORDER"], env["X"]), ("1", "PCI_BUS_ID", "2"))
202        self.assertEqual(images_api.image_env({"backend": "cuda", "gpu": [1, 0]}, {})["CUDA_VISIBLE_DEVICES"], "1,0")     # a list is a device list
203        with tempfile.TemporaryDirectory() as d:
204            env = images_api.image_env({"backend": "hip", "gpu": 0, "lib_dirs": [d, d + "-missing"]}, {})
205            self.assertEqual(env["HIP_VISIBLE_DEVICES"], "0")
206            self.assertEqual(env["PATH" if os.name == "nt" else "LD_LIBRARY_PATH"], d)
207        self.assertEqual(images_api.image_env({"backend": "vulkan", "gpu": 2}, {})["GGML_VK_VISIBLE_DEVICES"], "2")
208
209    def test_config_checked(self):
210        with self.assertRaises(ValueError):
211            images_api.ImageGen({"exe": "x", "diffusion_model": "d", "vae": "v"})
212        with tempfile.TemporaryDirectory() as d:
213            with self.assertRaises(ValueError):
214                images_api.ImageGen(image_cfg(d, gpu_policy="sometimes"))
215
216
217class LogFigures(unittest.TestCase):
218    def test_seconds_as_the_pinned_sd_cpp_prints_them(self):
219        log = ("[I] get_learned_condition completed, taking 0.70s --- image.cpp:529\n"
220               "[I] sampling completed, taking 19.27s --- image.cpp:899\n"
221               "[I] decode_first_stage completed, taking 3.40s --- image.cpp:624\n")
222        self.assertEqual(images_api.log_figures(log),
223                         {"text_encode_ms": 700.0, "sampling_s": 19.27, "vae_decode_s": 3.4})
224
225    def test_milliseconds_form(self):
226        log = "[INFO ] get_learned_condition completed, taking 12 ms\n[INFO ] sampling completed, taking 80ms\n"
227        self.assertEqual(images_api.log_figures(log), {"text_encode_ms": 12.0, "sampling_s": 0.08})
228
229    def test_the_last_line_counts_and_other_lines_are_ignored(self):
230        log = ("generating 1 latent images completed, taking 19.27s\n"
231               "[I] sampling completed, taking 1.00s\n[I] sampling completed, taking 2.50s\n")
232        self.assertEqual(images_api.log_figures(log), {"sampling_s": 2.5})
233
234
235def png_parts(data):
236    """(IHDR fields, [every chunk other than IHDR / IDAT, as bytes]) of a PNG."""
237    cs = images_api._png_chunks(data)
238    import struct
239    ihdr = struct.unpack(">IIBBBBB", cs[0][1][8:21])
240    others = [c for t, c in cs if t not in (b"IHDR", b"IDAT")]
241    return ihdr, others
242
243
244def rgb_pixels(data):
245    """RGB pixels of an 8-bit RGB filter-0 PNG (what flatten_png writes) as a list of rows of (r, g, b)."""
246    import zlib
247    cs = images_api._png_chunks(data)
248    w = int.from_bytes(cs[0][1][8:12], "big")
249    raw = zlib.decompress(b"".join(c[8:-4] for t, c in cs if t == b"IDAT"))
250    stride = 1 + 3 * w
251    rows = [raw[i:i + stride] for i in range(0, len(raw), stride)]
252    assert all(r[0] == 0 for r in rows)
253    return [[tuple(r[1 + 3 * x:4 + 3 * x]) for x in range(w)] for r in rows]
254
255
256class Transparency(unittest.TestCase):
257    """Qwen-Image-2.1 writes RGBA; flatten_png puts it on white as 8-bit RGB, other chunks byte for byte."""
258
259    def setUp(self):
260        sys.path.insert(0, str(FAKE.parent))
261        import fake_sd_cli
262        self.fake = fake_sd_cli
263        self.src = fake_sd_cli.rgba_png(512, 512, 7, "a sloth")
264        self.r, self.g, self.b = __import__("hashlib").sha256(b"7|512x512|a sloth").digest()[:3]
265
266    def expected(self, c, a):
267        return int(c * a / 255 + 255 * (1 - a / 255) + 0.5)
268
269    def check(self, out):
270        ihdr, others = png_parts(out)
271        self.assertEqual(ihdr, (4, 4, 8, 2, 0, 0, 0))                 # 8-bit RGB, no alpha
272        _, src_others = png_parts(self.src)
273        self.assertEqual(others, src_others)                         # "parameters" (and IEND) byte for byte
274        px = rgb_pixels(out)
275        self.assertEqual(px[0], [(255, 255, 255)] * 4)               # alpha 0 over the key colour: white
276        self.assertEqual(px[1], [tuple(self.expected(c, 128) for c in (self.r, self.g, self.b))] * 4)
277        self.assertEqual(px[2], [(self.r, self.g, self.b)] * 4)      # alpha 255: unchanged
278        self.assertEqual(px[3], [tuple(self.expected(c, a) for c in (self.r, self.g, self.b)) for a in (1, 64, 254, 255)])
279
280    def test_rgba_on_white(self):
281        self.check(images_api.flatten_png(self.src))
282
283    def test_without_pillow(self):
284        with mock.patch.dict(sys.modules, {"PIL": None, "PIL.Image": None}):
285            self.check(images_api.flatten_png(self.src))
286
287    def test_rgb_passes_untouched(self):
288        rgb = self.fake.png(512, 512, 7, "a sloth")
289        self.assertIs(images_api.flatten_png(rgb), rgb)
290
291    def test_broken_png_raises_and_the_job_keeps_the_original(self):
292        bad = self.fake.rgba_png(512, 512, 7, "a sloth", broken=True)
293        with self.assertRaises(ValueError):
294            images_api.flatten_png(bad)
295        with tempfile.TemporaryDirectory() as d:
296            gen = images_api.ImageGen(image_cfg(d))
297            said = []
298            gen._say = said.append
299            self.assertEqual(gen._flatten(bad), (bad, True))          # RGBA kept: the answer says transparent
300            self.assertEqual(len(said), 1)
301            self.assertIn("keeps its transparency", said[0])
302            self.assertEqual(gen._flatten(b"not a png"), (b"not a png", False))
303            self.assertEqual(gen._flatten(self.src)[1], False)
304            rgb = self.fake.png(512, 512, 7, "a sloth")
305            self.assertEqual(gen._flatten(rgb), (rgb, False))
306
307    def test_background_field(self):
308        cfg = {}
309        for v, want in ((None, "auto"), ("auto", "auto"), ("opaque", "opaque"), ("transparent", "transparent")):
310            req = {"prompt": "x"} if v is None else {"prompt": "x", "background": v}
311            self.assertEqual(images_api.parse_request(req, cfg)["background"], want)
312        for v in ("white", "TRANSPARENT", 1, True):
313            with self.assertRaises(images_api.ImageRequestError):
314                images_api.parse_request({"prompt": "x", "background": v}, cfg)
315
316
317class FakeEngine:
318    """An engine with the parts the GPU turn uses: alive/unload/restart, vram (elastic) and session files."""
319
320    def __init__(self, elastic=False):
321        self.up, self.calls, self.info = True, [], {"vram_elastic": elastic}
322        self.spawn = (["strata"], ["--vram-elastic"] if elastic else [])
323        self.unloaded = False
324
325    def alive(self):
326        return self.up
327
328    def exit_code(self):
329        return 0
330
331    def unload(self):
332        self.calls.append("unload")
333        self.up, self.unloaded = False, True
334
335    def restart(self):
336        self.calls.append("restart")
337        self.up, self.unloaded = True, False
338
339    def vram(self, reserve):
340        self.calls.append(("vram", reserve))
341        return {"vram_free_mib": 9000}
342
343    def session_file(self, action, path):
344        self.calls.append((action, os.path.basename(path)))
345        if action == "save":
346            Path(path).write_bytes(b"kv")
347        else:
348            assert Path(path).read_bytes() == b"kv"
349        return {"tokens": 123, "bytes": 2, "ms": 1.0}
350
351    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
352        return iter(())
353
354
355class Policy(unittest.TestCase):
356    def svc(self, engine):
357        tok = ByteTokenizer()
358        return Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
359
360    def test_resolve(self):
361        with tempfile.TemporaryDirectory() as d:
362            gen = images_api.ImageGen(image_cfg(d))
363            eng = FakeEngine()
364            svc = self.svc(eng)
365            with mock.patch.object(svc, "free_vram_mib", return_value=20000):
366                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")
367            with mock.patch.object(svc, "free_vram_mib", return_value=None):
368                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")
369            with mock.patch.object(svc, "free_vram_mib", return_value=4000):
370                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "unload")
371                svc.engine = FakeEngine(elastic=True)
372                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "shrink")
373                gen.cfg["uma"] = True
374                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")
375                gen.cfg["uma"] = False
376                gen.policy = "unload"
377                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "unload")
378                svc.engine.up = False                   # nothing loaded: nothing to give back
379                self.assertEqual(images_api.resolve_policy(svc, gen, 15000), "keep")
380            self.assertEqual(images_api.resolve_policy(self.svc(MockEngine(ByteTokenizer(), "x")), gen, 1), "keep")
381
382    def test_unload_saves_and_the_next_start_restores(self):
383        with tempfile.TemporaryDirectory() as d:
384            gen = images_api.ImageGen(image_cfg(d, gpu_policy="unload"))
385            eng = FakeEngine()
386            svc = self.svc(eng)
387            job = {"width": 1024, "height": 1024}
388            with images_api.gpu_turn(svc, gen, job) as policy:
389                self.assertEqual(policy, "unload")
390                self.assertTrue(svc.fifo.locked())          # no chat turn meanwhile
391                self.assertFalse(eng.up)
392                self.assertTrue(svc.status["busy"])
393            self.assertFalse(svc.fifo.locked())
394            self.assertFalse(svc.status["busy"])
395            self.assertEqual([c if isinstance(c, str) else c[0] for c in eng.calls], ["save", "unload"])
396            self.assertTrue(svc.restore_after_load)
397            with svc.fifo:
398                svc.ensure_loaded()                          # the next request: start, then the conversation back
399            self.assertEqual([c if isinstance(c, str) else c[0] for c in eng.calls],
400                             ["save", "unload", "restart", "restore"])
401            self.assertIsNone(svc.restore_after_load)
402            self.assertEqual(list(Path(gen.dir).glob("llm-session-*")), [])
403
404    def test_eager_reload(self):
405        with tempfile.TemporaryDirectory() as d:
406            gen = images_api.ImageGen(image_cfg(d, gpu_policy="unload", reload="eager"))
407            eng = FakeEngine()
408            svc = self.svc(eng)
409            with images_api.gpu_turn(svc, gen, {"width": 512, "height": 512}):
410                pass
411            self.assertEqual([c if isinstance(c, str) else c[0] for c in eng.calls],
412                             ["save", "unload", "restart", "restore"])
413            self.assertTrue(eng.up)
414
415    def test_shrink_gives_the_cache_back(self):
416        with tempfile.TemporaryDirectory() as d:
417            gen = images_api.ImageGen(image_cfg(d, gpu_policy="shrink"))
418            eng = FakeEngine(elastic=True)
419            svc = self.svc(eng)
420            svc.vram_reserve = 512
421            with images_api.gpu_turn(svc, gen, {"width": 1024, "height": 1024}):
422                self.assertEqual(eng.calls[0][0], "vram")
423                self.assertEqual(eng.calls[0][1], 6 * 1024)     # 2 GiB + 4 GiB per megapixel (+ 3 KiB of files)
424            self.assertEqual(eng.calls[-1], ("vram", 512))
425            self.assertTrue(eng.up)
426
427    def test_keep_touches_nothing(self):
428        with tempfile.TemporaryDirectory() as d:
429            gen = images_api.ImageGen(image_cfg(d, gpu_policy="keep"))
430            eng = FakeEngine()
431            svc = self.svc(eng)
432            with images_api.gpu_turn(svc, gen, {"width": 1024, "height": 1024}):
433                pass
434            self.assertEqual(eng.calls, [])
435
436
437@mock.patch.object(images_api, "sd_cli_args", fake_args)
438class OverHttp(unittest.TestCase):
439    def setUp(self):
440        self.tmp = tempfile.TemporaryDirectory()
441        tok = ByteTokenizer()
442        self.engine = MockEngine(tok, "</think>\n\nok")
443        self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
444        self.svc.images = images_api.ImageGen(image_cfg(self.tmp.name, keep_files=3))
445        self.httpd = serve(self.svc, port=0)
446        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
447
448    def tearDown(self):
449        self.httpd.shutdown()
450        self.httpd.server_close()
451        self.tmp.cleanup()
452
453    def post(self, body, path="/v1/images/generations"):
454        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
455                                     headers={"Content-Type": "application/json"})
456        try:
457            with urllib.request.urlopen(req, timeout=60) as r:
458                return r.status, json.loads(r.read())
459        except urllib.error.HTTPError as e:
460            with e:
461                return e.code, json.loads(e.read())
462
463    def get(self, path):
464        try:
465            with urllib.request.urlopen(self.base + path, timeout=30) as r:
466                return r.status, r.read(), r.headers.get("Content-Type")
467        except urllib.error.HTTPError as e:
468            with e:
469                return e.code, e.read(), None
470
471    def test_b64(self):
472        code, body = self.post({"prompt": "a red fox", "seed": 11, "n": 2, "size": "512x768"})
473        self.assertEqual(code, 200, body)
474        self.assertEqual(len(body["data"]), 2)
475        pngs = [base64.b64decode(x["b64_json"]) for x in body["data"]]
476        sys.path.insert(0, str(FAKE.parent))
477        import fake_sd_cli
478        self.assertEqual(pngs, [fake_sd_cli.png(512, 768, 11, "a red fox"), fake_sd_cli.png(512, 768, 12, "a red fox")])
479        self.assertEqual([x["seed"] for x in body["data"]], [11, 12])
480        self.assertEqual(body["size"], "512x768")
481        self.assertEqual(body["strata"]["steps"], 8)
482        self.assertEqual(body["strata"]["sampling_s"], 0.08)
483        self.assertEqual(body["strata"]["text_encode_ms"], 700.0)   # was never filled: sd.cpp prints seconds
484        self.assertEqual(body["strata"]["vae_decode_s"], 0.02)
485        self.assertEqual(body["strata"]["gpu_policy"], "keep")
486        self.assertEqual(self.svc.images.totals["images"], 2)
487        self.assertEqual([p.name for p in Path(self.svc.images.dir).iterdir()], [])   # nothing left behind
488
489    def test_the_prompt_reaches_sd_cli_in_a_file_and_not_in_its_arguments(self):
490        """#4202 with a canary: the stand-in records its argument list; the prompt is in the picture, not in the list."""
491        canary = "canary-7f3a91 private fox"
492        record = Path(self.tmp.name) / "argv.json"
493        with mock.patch.dict(os.environ, {"FAKE_SD_ARGS": str(record)}):
494            code, body = self.post({"prompt": canary, "seed": 5})
495        self.assertEqual(code, 200, body)
496        argv = json.loads(record.read_text(encoding="utf-8"))
497        self.assertNotIn("canary", " ".join(argv))
498        self.assertIn("--prompt-file", argv)
499        sys.path.insert(0, str(FAKE.parent))
500        import fake_sd_cli
501        self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]), fake_sd_cli.png(1024, 1024, 5, canary))
502        self.assertEqual([p.name for p in Path(self.svc.images.dir).iterdir() if p.name != "argv.json"], [])   # the prompt file is removed
503
504    def test_url(self):
505        names = []
506        for i in range(4):
507            code, body = self.post({"prompt": "a lighthouse", "seed": i, "response_format": "url"})
508            self.assertEqual(code, 200, body)
509            url = body["data"][0]["url"]
510            self.assertTrue(url.startswith(self.base + "/v1/images/files/"), url)
511            names.append(url.rsplit("/", 1)[1])
512            code, data, ctype = self.get(url[len(self.base):])
513            self.assertEqual((code, ctype), (200, "image/png"))
514            self.assertTrue(data.startswith(b"\x89PNG"))
515        self.assertEqual(self.get("/v1/images/files/" + names[0])[0], 404)   # keep_files 3: the oldest went
516        self.assertEqual(self.get("/v1/images/files/../../setup.py")[0], 404)
517        self.assertEqual(self.get("/v1/images/files/" + "0" * 32 + ".png")[0], 404)
518
519    def test_transparency_over_http(self):
520        sys.path.insert(0, str(FAKE.parent))
521        import fake_sd_cli
522        src = fake_sd_cli.rgba_png(512, 512, 5, "a sloth")
523        with mock.patch.dict(os.environ, {"FAKE_SD_RGBA": "1"}):
524            code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512"})
525            self.assertEqual(code, 200, body)
526            flat = base64.b64decode(body["data"][0]["b64_json"])
527            self.assertEqual(flat, images_api.flatten_png(src))
528            self.assertEqual(png_parts(flat)[0][3], 2)                     # RGB
529            self.assertEqual(body["background"], "opaque")
530            self.assertIn("flatten_s", body["strata"])
531            code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512", "response_format": "url"})
532            stored = self.get(body["data"][0]["url"][len(self.base):])[1]
533            self.assertEqual(stored, flat)                                 # the stored file is the white one
534            code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512", "background": "transparent"})
535            self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]), src)   # sd-cli's PNG, unchanged
536            self.assertEqual(body["background"], "transparent")
537            self.assertEqual(self.post({"prompt": "x", "background": "white"})[0], 400)
538        with mock.patch.dict(os.environ, {"FAKE_SD_RGBA": "1", "FAKE_SD_BROKEN": "1"}):
539            code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512"})
540        self.assertEqual(code, 200, body)                                   # never fails the request
541        self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]),
542                         fake_sd_cli.rgba_png(512, 512, 5, "a sloth", broken=True))
543        self.assertEqual(body["background"], "transparent")              # the picture kept its alpha
544        code, body = self.post({"prompt": "a fox", "seed": 5, "size": "512x512"})   # an RGB sd-cli picture
545        self.assertEqual(body["background"], "opaque")
546
547    def test_bad_request_and_failure(self):
548        self.assertEqual(self.post({"prompt": "x", "size": "999x999"})[0], 400)
549        with mock.patch.dict(os.environ, {"FAKE_SD_FAIL": "1"}):
550            code, body = self.post({"prompt": "x"})
551        self.assertEqual(code, 500)
552        self.assertIn("ErrorDeviceLost", body["error"]["message"])
553        self.assertEqual(self.svc.images.totals["failed"], 1)
554        self.assertFalse(self.svc.status["busy"])
555        self.assertFalse(self.svc.fifo.locked())
556
557    def test_listed(self):
558        code, data, _ = self.get("/v1/models")
559        ids = [m["id"] for m in json.loads(data)["data"]]
560        self.assertIn("qwen-image-2.1-turbo", ids)
561        st = json.loads(self.get("/v1/status")[1])
562        self.assertTrue(st["image_generation"]["enabled"])
563        self.assertTrue(json.loads(self.get("/health")[1])["image_generation"])
564
565    def test_not_set_up(self):
566        self.svc.images = None
567        code, body = self.post({"prompt": "x"})
568        self.assertEqual((code, body["error"]["code"]), (404, "images_not_set_up"))
569
570    def test_chat_waits_for_the_image(self):
571        """One job at a time on the GPU: a chat request sent during an image job is answered after it."""
572        done = {}
573        with mock.patch.dict(os.environ, {"FAKE_SD_SLEEP": "1.5"}):
574            t = threading.Thread(target=lambda: done.setdefault("img", (self.post({"prompt": "x"}), time.time())))
575            t.start()
576            time.sleep(0.5)
577            req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(
578                {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": "hi"}]}).encode(),
579                headers={"Content-Type": "application/json"})
580            with urllib.request.urlopen(req, timeout=60) as r:
581                self.assertEqual(r.status, 200)
582            chat_at = time.time()
583            t.join()
584        (code, _), img_at = done["img"]
585        self.assertEqual(code, 200)
586        self.assertGreaterEqual(chat_at, img_at - 0.05)
587
588
589class VaeDecoderSwitch(unittest.TestCase):
590    """images "vae_decoder" (OWN-5 step 2): "sdcpp" or absent changes nothing; "strata" adds strata_vae=1 to the one
591    --model-args string; a config that asks for it with an sd-cli built without it, or on a backend without it, is
592    refused before sd-cli starts (the owner's wording of 11-11, see serve/images.py)."""
593
594    def test_the_owners_words(self):
595        self.assertEqual(images_api.VAE_MISSING,
596                         "Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the "
597                         "images settings), but the image program here was built without it. Run setup again with: "
598                         "--images qwen-image --image-vae on")
599        self.assertEqual(images_api.VAE_BACKEND.format(backend="vulkan"),
600                         "Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the "
601                         "images settings), which needs the CUDA (NVIDIA) or ROCm (AMD) build of the image program; this "
602                         "one was built for vulkan. Set \"vae_decoder\" to \"sdcpp\" in the images settings.")
603
604    JOB = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42}
605    BASE = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf",
606            "args": ["--diffusion-fa", "--vae-tiling"]}
607
608    def test_off_leaves_the_command_line_alone(self):
609        for extra in ({}, {"vae_decoder": "sdcpp"}, {"vae_decoder": None}):
610            with self.subTest(extra=extra):
611                self.assertEqual(images_api.sd_cli_args({**self.BASE, **extra}, self.JOB, "o/img_%d.png", "o/prompt.txt"),
612                                 Command.CARD)
613
614    def test_on_is_one_model_args_string(self):
615        on = {**self.BASE, "vae_decoder": "strata"}
616        self.assertEqual(images_api.sd_cli_args(on, self.JOB, "o/img_%d.png", "o/prompt.txt"),
617                         Command.CARD + ["--model-args", "strata_vae=1"])
618        all3 = images_api.sd_cli_args({**on, "native": True, "noise": "strata"}, self.JOB, "o/img_%d.png", "o/prompt.txt")
619        self.assertEqual(all3, Command.CARD + ["--model-args", "qwen_image_2_1_native=1,strata_noise=1,strata_vae=1"])
620        self.assertEqual(all3.count("--model-args"), 1)
621
622    def test_value_is_checked(self):
623        with tempfile.TemporaryDirectory() as d:
624            cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "out_dir": d}
625            for ok in ("sdcpp", "strata"):
626                images_api.ImageGen({**cfg, "vae_decoder": ok})
627            for bad in ("on", "", "Strata", True, 1):
628                with self.subTest(bad=bad), self.assertRaises(ValueError):
629                    images_api.ImageGen({**cfg, "vae_decoder": bad})
630
631    def gen(self, d, build=None, backend="cuda"):
632        cfg = image_cfg(d, vae_decoder="strata", backend=backend)
633        exe = Path(d) / "engine-image" / "sd-cli"
634        exe.parent.mkdir(exist_ok=True)
635        exe.write_bytes(b"x")
636        cfg["exe"] = str(exe)
637        if build is not None:
638            (exe.parent / "BUILD.json").write_text(build if isinstance(build, str) else json.dumps(build))
639        return images_api.ImageGen(cfg)
640
641    def test_problem_by_build_json_and_backend(self):
642        with tempfile.TemporaryDirectory() as d:
643            self.assertEqual(self.gen(d).vae_problem(), images_api.VAE_MISSING)            # no BUILD.json
644        for build in ({"sd_cpp": "x", "backend": "cuda"}, {"vae_decoder": ""}, "not json", "[1]", "{",
645                      {"noise": "0123456789abcdef"}):
646            with self.subTest(build=build), tempfile.TemporaryDirectory() as d:
647                self.assertEqual(self.gen(d, build).vae_problem(), images_api.VAE_MISSING)
648        for backend in ("cuda", "hip"):
649            with tempfile.TemporaryDirectory() as d:
650                self.assertIsNone(self.gen(d, {"vae_decoder": "0123456789abcdef"}, backend).vae_problem())
651        for backend in ("vulkan", "cpu", "metal", None):
652            with self.subTest(backend=backend), tempfile.TemporaryDirectory() as d:
653                said = self.gen(d, {"vae_decoder": "0123456789abcdef"}, backend).vae_problem()
654                self.assertEqual(said, images_api.VAE_BACKEND.format(backend=backend or "another backend"))
655                self.assertIn(f"this one was built for {backend or 'another backend'}.", said)
656
657    def test_switch_off_asks_nothing(self):
658        with tempfile.TemporaryDirectory() as d:
659            for extra in ({}, {"vae_decoder": "sdcpp"}):
660                self.assertIsNone(images_api.ImageGen({**image_cfg(d), **extra}).vae_problem())
661
662    def test_a_job_is_refused_before_sd_cli_starts(self):
663        with tempfile.TemporaryDirectory() as d:
664            g = self.gen(d)
665            job = images_api.parse_request({"prompt": "a cat"}, {})
666            before = sorted(p.name for p in g.dir.iterdir())
667            with mock.patch("serve.lifeline.popen") as popen, self.assertRaises(images_api.ImageJobFailed) as cm:
668                g.run(job)
669            popen.assert_not_called()
670            self.assertEqual(str(cm.exception), images_api.VAE_MISSING)
671            self.assertEqual(sorted(p.name for p in g.dir.iterdir()), before)
672            self.assertEqual(g.totals["failed"], 1)
673
674
675if __name__ == "__main__":
676    unittest.main()