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