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