"""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, prompt_file): """sd-cli's command, run through Python (the stand-in is a script).""" return [sys.executable, str(FAKE), *REAL_ARGS(cfg, job, out, prompt_file)[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", "o/prompt.txt"), [ "sd-cli", "--diffusion-model", "dit.gguf", "--vae", "vae.st", "--llm", "te.gguf", "--prompt-file", "o/prompt.txt", "--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", "p.txt") self.assertNotIn("--sigmas", cmd) # Turbo's sigmas are an 8-step schedule self.assertEqual(cmd[cmd.index("-b") + 1], "3") def test_prompt_not_on_the_command_line(self): """#4202: other local accounts can read process arguments: the prompt goes to sd-cli in an owner-only file.""" cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l"} job = {"prompt": "a private\r\nprompt ΓΌ \U0001f98a", "width": 512, "height": 512, "n": 1, "steps": 8, "seed": 1} with tempfile.TemporaryDirectory() as d: path = images_api.write_prompt(Path(d), job["prompt"]) self.assertEqual(path.read_bytes(), job["prompt"].encode("utf-8")) # no newline translation if os.name != "nt": self.assertEqual(path.stat().st_mode & 0o777, 0o600) with self.assertRaises(FileExistsError): # never writes through an existing file images_api.write_prompt(Path(d), "again") cmd = images_api.sd_cli_args(cfg, job, "x", str(path)) self.assertNotIn(job["prompt"], cmd) self.assertFalse(any("private" in part for part in cmd), cmd) self.assertNotIn("-p", cmd) self.assertEqual(cmd[cmd.index("--prompt-file") + 1], str(path)) def test_native_switch(self): cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "native": True} job = {"prompt": "p", "width": 512, "height": 512, "n": 1, "steps": 8, "seed": 1} self.assertEqual(images_api.sd_cli_args(cfg, job, "x", "p.txt")[-2:], ["--model-args", "qwen_image_2_1_native=1"]) cfg["native"] = False self.assertNotIn("--model-args", images_api.sd_cli_args(cfg, job, "x", "p.txt")) CARD = ["sd-cli", "--diffusion-model", "dit.gguf", "--vae", "vae.st", "--llm", "te.gguf", "--prompt-file", "o/prompt.txt", "--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_noise_switch_off_leaves_the_command_line_alone(self): """images "noise" absent or "sdcpp" (the default): the exact argument list of before the switch existed.""" job = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42} base = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf", "args": ["--diffusion-fa", "--vae-tiling"]} for extra in ({}, {"noise": "sdcpp"}, {"noise": None}, {"native": False, "noise": "sdcpp"}): with self.subTest(extra=extra): self.assertEqual(images_api.sd_cli_args({**base, **extra}, job, "o/img_%d.png", "o/prompt.txt"), self.CARD) # and the native switch alone is still the last two arguments, as before self.assertEqual(images_api.sd_cli_args({**base, "native": True}, job, "o/img_%d.png", "o/prompt.txt"), self.CARD + ["--model-args", "qwen_image_2_1_native=1"]) def test_noise_switch_on_is_one_model_args_string(self): job = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42} base = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf", "args": ["--diffusion-fa", "--vae-tiling"]} self.assertEqual(images_api.sd_cli_args({**base, "noise": "strata"}, job, "o/img_%d.png", "o/prompt.txt"), self.CARD + ["--model-args", "strata_noise=1"]) both = images_api.sd_cli_args({**base, "noise": "strata", "native": True}, job, "o/img_%d.png", "o/prompt.txt") self.assertEqual(both, self.CARD + ["--model-args", "qwen_image_2_1_native=1,strata_noise=1"]) self.assertEqual(both.count("--model-args"), 1) def test_noise_value_is_checked(self): with tempfile.TemporaryDirectory() as d: cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "out_dir": d} for ok in ("sdcpp", "strata"): images_api.ImageGen({**cfg, "noise": ok}) for bad in ("on", "", "Strata", True, 1): with self.subTest(bad=bad), self.assertRaises(ValueError): images_api.ImageGen({**cfg, "noise": bad}) class NoiseRefusal(unittest.TestCase): """images "noise": "strata" with an sd-cli that was built without the generator: the job is refused, in plain words with one next step, instead of quietly running on stable-diffusion.cpp's noise.""" WORDS = ("Image generation is set to use Strata's own noise (\"noise\": \"strata\" in the images settings), but the " "image program here was built without it. Run setup again with: --images qwen-image --image-noise on") def gen(self, d, build=None, **kw): cfg = image_cfg(d, noise="strata", **kw) exe = Path(d) / "engine-image" / "sd-cli" exe.parent.mkdir(exist_ok=True) exe.write_bytes(b"x") cfg["exe"] = str(exe) if build is not None: (exe.parent / "BUILD.json").write_text(build if isinstance(build, str) else json.dumps(build)) return images_api.ImageGen(cfg) def test_the_words(self): self.assertEqual(images_api.NOISE_MISSING, self.WORDS) def test_problem_by_build_json(self): with tempfile.TemporaryDirectory() as d: self.assertEqual(self.gen(d).noise_problem(), self.WORDS) # no BUILD.json for build in ({"sd_cpp": "x", "backend": "cuda"}, {"noise": ""}, "not json", "[1]", "{"): with self.subTest(build=build), tempfile.TemporaryDirectory() as d: self.assertEqual(self.gen(d, build).noise_problem(), self.WORDS) with tempfile.TemporaryDirectory() as d: self.assertIsNone(self.gen(d, {"sd_cpp": "x", "noise": "0123456789abcdef"}).noise_problem()) def test_switch_off_asks_nothing(self): with tempfile.TemporaryDirectory() as d: for extra in ({}, {"noise": "sdcpp"}): cfg = {**image_cfg(d), **extra} self.assertIsNone(images_api.ImageGen(cfg).noise_problem()) # no BUILD.json needed def test_a_job_is_refused_before_sd_cli_starts(self): with tempfile.TemporaryDirectory() as d: g = self.gen(d) job = images_api.parse_request({"prompt": "a cat"}, {}) before = sorted(p.name for p in g.dir.iterdir()) with mock.patch("serve.lifeline.popen") as popen, self.assertRaises(images_api.ImageJobFailed) as cm: g.run(job) popen.assert_not_called() self.assertEqual(str(cm.exception), self.WORDS) self.assertEqual(sorted(p.name for p in g.dir.iterdir()), before) # no job folder left behind self.assertEqual(g.totals["failed"], 1) 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")) self.assertEqual(images_api.image_env({"backend": "cuda", "gpu": [1, 0]}, {})["CUDA_VISIBLE_DEVICES"], "1,0") # a list is a device list 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 LogFigures(unittest.TestCase): def test_seconds_as_the_pinned_sd_cpp_prints_them(self): log = ("[I] get_learned_condition completed, taking 0.70s --- image.cpp:529\n" "[I] sampling completed, taking 19.27s --- image.cpp:899\n" "[I] decode_first_stage completed, taking 3.40s --- image.cpp:624\n") self.assertEqual(images_api.log_figures(log), {"text_encode_ms": 700.0, "sampling_s": 19.27, "vae_decode_s": 3.4}) def test_milliseconds_form(self): log = "[INFO ] get_learned_condition completed, taking 12 ms\n[INFO ] sampling completed, taking 80ms\n" self.assertEqual(images_api.log_figures(log), {"text_encode_ms": 12.0, "sampling_s": 0.08}) def test_the_last_line_counts_and_other_lines_are_ignored(self): log = ("generating 1 latent images completed, taking 19.27s\n" "[I] sampling completed, taking 1.00s\n[I] sampling completed, taking 2.50s\n") self.assertEqual(images_api.log_figures(log), {"sampling_s": 2.5}) def png_parts(data): """(IHDR fields, [every chunk other than IHDR / IDAT, as bytes]) of a PNG.""" cs = images_api._png_chunks(data) import struct ihdr = struct.unpack(">IIBBBBB", cs[0][1][8:21]) others = [c for t, c in cs if t not in (b"IHDR", b"IDAT")] return ihdr, others def rgb_pixels(data): """RGB pixels of an 8-bit RGB filter-0 PNG (what flatten_png writes) as a list of rows of (r, g, b).""" import zlib cs = images_api._png_chunks(data) w = int.from_bytes(cs[0][1][8:12], "big") raw = zlib.decompress(b"".join(c[8:-4] for t, c in cs if t == b"IDAT")) stride = 1 + 3 * w rows = [raw[i:i + stride] for i in range(0, len(raw), stride)] assert all(r[0] == 0 for r in rows) return [[tuple(r[1 + 3 * x:4 + 3 * x]) for x in range(w)] for r in rows] class Transparency(unittest.TestCase): """Qwen-Image-2.1 writes RGBA; flatten_png puts it on white as 8-bit RGB, other chunks byte for byte.""" def setUp(self): sys.path.insert(0, str(FAKE.parent)) import fake_sd_cli self.fake = fake_sd_cli self.src = fake_sd_cli.rgba_png(512, 512, 7, "a sloth") self.r, self.g, self.b = __import__("hashlib").sha256(b"7|512x512|a sloth").digest()[:3] def expected(self, c, a): return int(c * a / 255 + 255 * (1 - a / 255) + 0.5) def check(self, out): ihdr, others = png_parts(out) self.assertEqual(ihdr, (4, 4, 8, 2, 0, 0, 0)) # 8-bit RGB, no alpha _, src_others = png_parts(self.src) self.assertEqual(others, src_others) # "parameters" (and IEND) byte for byte px = rgb_pixels(out) self.assertEqual(px[0], [(255, 255, 255)] * 4) # alpha 0 over the key colour: white self.assertEqual(px[1], [tuple(self.expected(c, 128) for c in (self.r, self.g, self.b))] * 4) self.assertEqual(px[2], [(self.r, self.g, self.b)] * 4) # alpha 255: unchanged 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)]) def test_rgba_on_white(self): self.check(images_api.flatten_png(self.src)) def test_without_pillow(self): with mock.patch.dict(sys.modules, {"PIL": None, "PIL.Image": None}): self.check(images_api.flatten_png(self.src)) def test_rgb_passes_untouched(self): rgb = self.fake.png(512, 512, 7, "a sloth") self.assertIs(images_api.flatten_png(rgb), rgb) def test_broken_png_raises_and_the_job_keeps_the_original(self): bad = self.fake.rgba_png(512, 512, 7, "a sloth", broken=True) with self.assertRaises(ValueError): images_api.flatten_png(bad) with tempfile.TemporaryDirectory() as d: gen = images_api.ImageGen(image_cfg(d)) said = [] gen._say = said.append self.assertEqual(gen._flatten(bad), (bad, True)) # RGBA kept: the answer says transparent self.assertEqual(len(said), 1) self.assertIn("keeps its transparency", said[0]) self.assertEqual(gen._flatten(b"not a png"), (b"not a png", False)) self.assertEqual(gen._flatten(self.src)[1], False) rgb = self.fake.png(512, 512, 7, "a sloth") self.assertEqual(gen._flatten(rgb), (rgb, False)) def test_background_field(self): cfg = {} for v, want in ((None, "auto"), ("auto", "auto"), ("opaque", "opaque"), ("transparent", "transparent")): req = {"prompt": "x"} if v is None else {"prompt": "x", "background": v} self.assertEqual(images_api.parse_request(req, cfg)["background"], want) for v in ("white", "TRANSPARENT", 1, True): with self.assertRaises(images_api.ImageRequestError): images_api.parse_request({"prompt": "x", "background": v}, cfg) 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"]["text_encode_ms"], 700.0) # was never filled: sd.cpp prints seconds self.assertEqual(body["strata"]["vae_decode_s"], 0.02) 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_the_prompt_reaches_sd_cli_in_a_file_and_not_in_its_arguments(self): """#4202 with a canary: the stand-in records its argument list; the prompt is in the picture, not in the list.""" canary = "canary-7f3a91 private fox" record = Path(self.tmp.name) / "argv.json" with mock.patch.dict(os.environ, {"FAKE_SD_ARGS": str(record)}): code, body = self.post({"prompt": canary, "seed": 5}) self.assertEqual(code, 200, body) argv = json.loads(record.read_text(encoding="utf-8")) self.assertNotIn("canary", " ".join(argv)) self.assertIn("--prompt-file", argv) sys.path.insert(0, str(FAKE.parent)) import fake_sd_cli self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]), fake_sd_cli.png(1024, 1024, 5, canary)) self.assertEqual([p.name for p in Path(self.svc.images.dir).iterdir() if p.name != "argv.json"], []) # the prompt file is removed 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_transparency_over_http(self): sys.path.insert(0, str(FAKE.parent)) import fake_sd_cli src = fake_sd_cli.rgba_png(512, 512, 5, "a sloth") with mock.patch.dict(os.environ, {"FAKE_SD_RGBA": "1"}): code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512"}) self.assertEqual(code, 200, body) flat = base64.b64decode(body["data"][0]["b64_json"]) self.assertEqual(flat, images_api.flatten_png(src)) self.assertEqual(png_parts(flat)[0][3], 2) # RGB self.assertEqual(body["background"], "opaque") self.assertIn("flatten_s", body["strata"]) code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512", "response_format": "url"}) stored = self.get(body["data"][0]["url"][len(self.base):])[1] self.assertEqual(stored, flat) # the stored file is the white one code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512", "background": "transparent"}) self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]), src) # sd-cli's PNG, unchanged self.assertEqual(body["background"], "transparent") self.assertEqual(self.post({"prompt": "x", "background": "white"})[0], 400) with mock.patch.dict(os.environ, {"FAKE_SD_RGBA": "1", "FAKE_SD_BROKEN": "1"}): code, body = self.post({"prompt": "a sloth", "seed": 5, "size": "512x512"}) self.assertEqual(code, 200, body) # never fails the request self.assertEqual(base64.b64decode(body["data"][0]["b64_json"]), fake_sd_cli.rgba_png(512, 512, 5, "a sloth", broken=True)) self.assertEqual(body["background"], "transparent") # the picture kept its alpha code, body = self.post({"prompt": "a fox", "seed": 5, "size": "512x512"}) # an RGB sd-cli picture self.assertEqual(body["background"], "opaque") 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) class VaeDecoderSwitch(unittest.TestCase): """images "vae_decoder" (OWN-5 step 2): "sdcpp" or absent changes nothing; "strata" adds strata_vae=1 to the one --model-args string; a config that asks for it with an sd-cli built without it, or on a backend without it, is refused before sd-cli starts (the owner's wording of 11-11, see serve/images.py).""" def test_the_owners_words(self): self.assertEqual(images_api.VAE_MISSING, "Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the " "images settings), but the image program here was built without it. Run setup again with: " "--images qwen-image --image-vae on") self.assertEqual(images_api.VAE_BACKEND.format(backend="vulkan"), "Image generation is set to use Strata's own picture decoder (\"vae_decoder\": \"strata\" in the " "images settings), which needs the CUDA (NVIDIA) or ROCm (AMD) build of the image program; this " "one was built for vulkan. Set \"vae_decoder\" to \"sdcpp\" in the images settings.") JOB = {"prompt": "a sloth", "width": 1024, "height": 768, "n": 1, "steps": 8, "seed": 42} BASE = {"exe": "sd-cli", "diffusion_model": "dit.gguf", "vae": "vae.st", "llm": "te.gguf", "args": ["--diffusion-fa", "--vae-tiling"]} def test_off_leaves_the_command_line_alone(self): for extra in ({}, {"vae_decoder": "sdcpp"}, {"vae_decoder": None}): with self.subTest(extra=extra): self.assertEqual(images_api.sd_cli_args({**self.BASE, **extra}, self.JOB, "o/img_%d.png", "o/prompt.txt"), Command.CARD) def test_on_is_one_model_args_string(self): on = {**self.BASE, "vae_decoder": "strata"} self.assertEqual(images_api.sd_cli_args(on, self.JOB, "o/img_%d.png", "o/prompt.txt"), Command.CARD + ["--model-args", "strata_vae=1"]) all3 = images_api.sd_cli_args({**on, "native": True, "noise": "strata"}, self.JOB, "o/img_%d.png", "o/prompt.txt") self.assertEqual(all3, Command.CARD + ["--model-args", "qwen_image_2_1_native=1,strata_noise=1,strata_vae=1"]) self.assertEqual(all3.count("--model-args"), 1) def test_value_is_checked(self): with tempfile.TemporaryDirectory() as d: cfg = {"exe": "sd-cli", "diffusion_model": "d", "vae": "v", "llm": "l", "out_dir": d} for ok in ("sdcpp", "strata"): images_api.ImageGen({**cfg, "vae_decoder": ok}) for bad in ("on", "", "Strata", True, 1): with self.subTest(bad=bad), self.assertRaises(ValueError): images_api.ImageGen({**cfg, "vae_decoder": bad}) def gen(self, d, build=None, backend="cuda"): cfg = image_cfg(d, vae_decoder="strata", backend=backend) exe = Path(d) / "engine-image" / "sd-cli" exe.parent.mkdir(exist_ok=True) exe.write_bytes(b"x") cfg["exe"] = str(exe) if build is not None: (exe.parent / "BUILD.json").write_text(build if isinstance(build, str) else json.dumps(build)) return images_api.ImageGen(cfg) def test_problem_by_build_json_and_backend(self): with tempfile.TemporaryDirectory() as d: self.assertEqual(self.gen(d).vae_problem(), images_api.VAE_MISSING) # no BUILD.json for build in ({"sd_cpp": "x", "backend": "cuda"}, {"vae_decoder": ""}, "not json", "[1]", "{", {"noise": "0123456789abcdef"}): with self.subTest(build=build), tempfile.TemporaryDirectory() as d: self.assertEqual(self.gen(d, build).vae_problem(), images_api.VAE_MISSING) for backend in ("cuda", "hip"): with tempfile.TemporaryDirectory() as d: self.assertIsNone(self.gen(d, {"vae_decoder": "0123456789abcdef"}, backend).vae_problem()) for backend in ("vulkan", "cpu", "metal", None): with self.subTest(backend=backend), tempfile.TemporaryDirectory() as d: said = self.gen(d, {"vae_decoder": "0123456789abcdef"}, backend).vae_problem() self.assertEqual(said, images_api.VAE_BACKEND.format(backend=backend or "another backend")) self.assertIn(f"this one was built for {backend or 'another backend'}.", said) def test_switch_off_asks_nothing(self): with tempfile.TemporaryDirectory() as d: for extra in ({}, {"vae_decoder": "sdcpp"}): self.assertIsNone(images_api.ImageGen({**image_cfg(d), **extra}).vae_problem()) def test_a_job_is_refused_before_sd_cli_starts(self): with tempfile.TemporaryDirectory() as d: g = self.gen(d) job = images_api.parse_request({"prompt": "a cat"}, {}) before = sorted(p.name for p in g.dir.iterdir()) with mock.patch("serve.lifeline.popen") as popen, self.assertRaises(images_api.ImageJobFailed) as cm: g.run(job) popen.assert_not_called() self.assertEqual(str(cm.exception), images_api.VAE_MISSING) self.assertEqual(sorted(p.name for p in g.dir.iterdir()), before) self.assertEqual(g.totals["failed"], 1) if __name__ == "__main__": unittest.main()