Repository navigation
Studio diffusion: persistent sd-server for the native engine (load once, serve many) - #6768
Conversation
…t, validate-before-evict Phase 1 of porting the richer diffusion stack onto the image-generation backend. - Add a compartmentalized device/dtype policy module (diffusion_device.py) resolving CUDA/ROCm/XPU/MPS/CPU with capability flags. Keeps the NVIDIA capability-based bf16 choice; ROCm and XPU are isolated; MPS uses bf16 or fp32, never a silent fp16 that renders a black image. - Add a per-family fp16_incompatible flag (Z-Image) and promote a resolved float16 to float32 for those families so they do not produce black images. - Split the backend locks: a generation holds only _generate_lock, so status, unload, and a new load are never blocked by a long denoise. Add per-generation cancellation via callback_on_step_end so an eviction or a superseding load preempts a running generation; a replacement load waits for it to stop before allocating, so two pipelines never sit in VRAM at once. - Validate a load request before the GPU handoff so an unloadable pick never evicts a working chat model, and reject missing local paths up front. - Add CPU-only tests for the device policy, dtype guard, lock split and cancellation, and validate-before-evict, plus a GPU benchmark/regression script (scripts/diffusion_bench.py) measuring latency, peak VRAM, and PSNR against a saved reference.
…/VAE policy Add a lean, backend-agnostic memory policy that picks a CPU-offload policy and VAE tiling/slicing from measured free device memory vs the model's estimated resident footprint, then applies it to the built pipeline. auto stays resident when the model fits (byte-identical to the prior resident path), and falls to whole-module offload when tight; fast/balanced/low_vram are explicit overrides. Sequential submodule offload is unreliable for GGUF transformers on diffusers 0.38, so it falls back to whole-module offload and status reports the policy actually engaged. Verified on Z-Image-Turbo Q4_K_M (B200): auto reproduces the resident image with no VRAM/latency regression (PSNR inf); balanced/low_vram cut generation peak VRAM 47.9% (15951 -> 8318 MB) with byte-identical output, at the expected latency cost. 73 prior + 35 new CPU tests pass.
…l VAE tiling Add a streamed 'group' offload tier (diffusers apply_group_offloading, block_level, use_stream) that keeps the transformer flowing through the GPU a few blocks at a time while the text encoder / VAE stay resident, and fix VAE tiling to drive the VAE submodule (pipelines like Z-Image expose enable_tiling on pipe.vae, not the pipeline). apply_memory_plan now returns the (policy, tiling) actually engaged so status never overstates either, and group falls back to whole-module offload when the transformer can't be streamed. Measured on Z-Image (B200), all lossless (PSNR inf vs resident): balanced/group cuts generation peak VRAM 32% (15951 -> 10840 MB) at near-resident speed (2.07 -> 2.99s); low_vram/model cuts it 48% (-> 8318 MB) but is slower (7.99s). Mode names now match that tradeoff: balanced = stream the transformer, low_vram = offload every component. auto picks group when the companions fit resident, else model. 112 CPU tests pass.
Add scripts/diffusion_quality.py, the accuracy analogue of the KLD workflow: hold prompt + seed fixed, render a grid with a reference quant (default BF16), then render each candidate quant and measure drift from the reference. Records mean PSNR + SSIM (pure-numpy, no skimage/scipy) and optional CLIP text-alignment + image-similarity (transformers, --clip), plus file size, latency, and peak VRAM, then prints a quality-vs-cost table and recommends the smallest quant within a quality budget. --selftest validates the metrics on synthetic images with no GPU or model. Verified on Z-Image (B200): the table degrades monotonically with quant size (Q8 -> Q4 -> Q2: PSNR 21.7 -> 15.5, SSIM 0.82 -> 0.61), while CLIP-text stays flat (~0.34) -- quantization erodes fine detail far more than prompt adherence.
…le / TF32) Add a speed_mode knob (off by default, so the render path stays bit-identical): default applies channels_last VAE + regional torch.compile of the denoiser's repeated block where eligible; max also enables TF32 matmul and fused QKV. Regional compile is gated off for the GGUF transformer (dequantises per-op) and for families flagged not compile-friendly (a new supports_torch_compile flag, False for Z-Image), so it activates automatically only once a non-GGUF bf16 transformer is loaded. Speed optims run before placement/offload, per the diffusers composition order. status now reports speed_mode + the optims actually engaged. Verified on Z-Image (B200): default -> ['channels_last'], max -> ['channels_last', 'tf32'], compile correctly skipped for GGUF; generation works in every mode. 121 CPU tests pass.
Add a text_encoder_fp8 knob that casts the companion text encoder(s) to fp8 (e4m3) storage via diffusers apply_layerwise_casting, upcasting per layer to the bf16 compute dtype while normalisations and embeddings stay full precision. Applied before placement, gated to CUDA + bf16, best-effort (a failure leaves the encoder dense). status reports which encoders were cast. Verified on Z-Image (B200, balanced/group mode where the encoder stays resident): generation peak VRAM dropped 37% (10840 -> 6791 MB, below the lowest-VRAM offload) at near-resident speed. It is a memory-vs-quality tradeoff, not free -- ~20 dB PSNR vs the bf16 encoder, a larger shift than one transformer quant step -- so it is off by default and documented as such, with the Phase 5 harness to size the cost. 127 CPU tests pass.
…p8 knob) Generalise the text-encoder precision knob from a fp8 bool to text_encoder_quant (fp8 | nvfp4). nvfp4 quantises the companion text encoder to 4-bit via torchao NVFP4 weight-only (two-level microscaling) on Blackwell's FP4 tensor cores; fp8 stays the broader-hardware path (cc>=8.9). Both are gated, best-effort, and run before placement; status reports the mode actually engaged. This is the lean realisation of GGUF-native text-encoder quant: 4-bit on the encoder without the 3045-line port. Verified on Z-Image (B200, balanced/group where the encoder stays resident), vs the bf16 encoder: nvfp4 cut generation peak VRAM 48% (10840 -> 5593 MB, the lowest TE option, below whole-model offload) at near-fp8 quality (16.4 vs 17.1 dB PSNR), and both quants ran faster than bf16. A memory-vs-quality tradeoff (off by default); size it per model with the Phase 5 quality harness. diffusion_bench gains --text-encoder-quant. 129 CPU tests pass.
…U/Mac Adds the CPU / Apple-Silicon tier of the two-engine strategy, mirroring the chat backend's llama.cpp shell-out. Diffusers stays the default on CUDA / ROCm / XPU; this covers the hardware diffusers serves poorly, consuming the same split GGUF assets Studio already curates. - sd_cpp_args.py: pure sd-cli command builder. Maps the family to its text-encoder flag (Z-Image Qwen3 to --llm, Qwen-Image to --qwen2vl, FLUX.1 CLIP-L + T5), and the diffusers memory policy (none/group/model/sequential) to sd.cpp's offload flags (--offload-to-cpu / --clip-on-cpu / --vae-on-cpu / --vae-tiling / --diffusion-fa), so one user knob drives both engines. - sd_cpp_engine.py: SdCppEngine over a located sd-cli. find_sd_cpp_binary() with the same precedence as the llama finder (env override, then the Studio install root, then in-tree, then PATH), an is_available/version probe, and a one-shot subprocess generate that streams progress and returns the PNG. runtime_env() prepends the binary's directory to the platform library path so a prebuilt's bundled libstable-diffusion.so resolves. select_diffusion_engine() is the pure routing decision (GPU backends to diffusers, CPU/MPS to native when present). - install_sd_cpp_prebuilt.py: resolve + download the per-host prebuilt (macOS-arm64/Metal, Linux x86_64 CPU, Vulkan/ROCm/Windows variants) into the Studio install root. resolve_release_asset() is a pure, unit-tested host-to-asset matrix. - scripts/sd_cpp_smoke.py: end-to-end native generation harness. Tests (CPU-only, subprocess/filesystem stubbed): 49 new across args, engine, routing, runtime env, and the installer resolver. Full diffusion suite 166 passing. Verified on a B200 box: built sd-cli (CUDA) and the prebuilt (CPU) both generate Z-Image-Turbo Q4_K end to end through SdCppEngine: balanced (group offload, 5.0s gen), low_vram (full CPU offload + VAE tiling, 13.4s), and the dynamically-linked CPU prebuilt (50.4s on CPU), all producing coherent images.
… on the native engine
Builds on Phase 4's native stable-diffusion.cpp engine, extending it from
text-to-image to the wider feature surface, since sd.cpp supports all of these
through the binary already. Pure command-builder additions plus one engine
method, so the txt2img path is unchanged.
- sd_cpp_args.py: SdCppGenParams gains image-conditioning fields. init_img +
strength make a run img2img, adding mask makes it inpaint, ref_images drives
FLUX-Kontext / Qwen-Image-Edit style editing (repeated --ref-image), and
lora_dir + the <lora:name:weight> prompt syntax select LoRAs. New
SdCppUpscaleParams + build_sd_cpp_upscale_command for the ESRGAN upscale run
mode (input image + esrgan model, no prompt / text encoders).
- sd_cpp_engine.py: the subprocess runner is factored into a shared _run() so
generate() (now carrying the conditioning flags) and a new upscale() reuse
the same streaming / error / output-check path.
- scripts/sd_cpp_smoke.py: --task {txt2img,img2img,upscale} with --init-img /
--strength / --upscale-model / --upscale-repeats.
Tests: 10 new across the img2img / inpaint / edit / LoRA flag construction, the
upscale builder and its validation, and the engine's img2img + upscale paths.
Full diffusion suite 176 passing.
Verified on a B200 box through SdCppEngine: img2img (Z-Image-Turbo Q4_K, the
init image conditioned at strength 0.6, 4.8s) and ESRGAN upscale
(512x512 -> 2048x2048 via RealESRGAN_x4plus_anime_6B, 2.7s), both producing
coherent images. Video and the diffusers-path feature wiring are deferred.
Re-review of the diffusion stack (#6675/#6679/#6680) surfaced one real accuracy bug and a dead-on-arrival speed path; this fixes both and adds the lossless / near-lossless wins, all measured on a B200. Correctness: - TF32 global-state leak (fix). speed_mode=max flipped torch.backends.*.allow_tf32 process-wide and never restored them, so a later `off` load silently inherited TF32 and was no longer bit-identical. Added snapshot_backend_flags / restore_backend_flags (TF32 + cudnn.benchmark), captured before the speed layer runs and restored on unload. Verified: load max -> unload -> load off is now byte-identical (PSNR inf) to a fresh off. - sd-cli timeout could hang forever. _run() blocked in `for line in stdout` and only checked the timeout after EOF, so a child stuck in model load / GPU init with no output ignored the timeout. Drained stdout on a reader thread with a wall-clock deadline. Added a silent-hang regression test. Speed (diffusers path), near-lossless, opt-in tiers: - Regional torch.compile now runs on the GGUF transformer. The is_gguf gate (and Z-Image's supports_torch_compile=False) were stale: compile_repeated_blocks compiles and runs ~2.2x faster on the GGUF Z-Image transformer on torch 2.9.1 / diffusers 0.38 (the per-op dequant stays eager, the rest of the block compiles). Measured: off 1.80s -> default 0.82s/gen (+54.7%), PSNR 37.7 dB vs eager -- far above the Q4 quant noise floor (~21 dB), so it does not move output quality. Gate relaxed; default tier delivers it. - cudnn.benchmark added to the default tier (autotunes the fixed-shape VAE convs). - torch.inference_mode() around the pipeline call (lossless, strictly faster than the no_grad diffusers uses internally). Memory path: - VAE tiling (not bit-identical >1MP) restricted to the model/sequential/CPU tiers; the balanced (group) tier keeps exact slicing only, so it is now bit-identical to the resident image (verified PSNR inf) and slightly faster. - Group offload adds non_blocking + record_stream on the CUDA stream path to overlap each block's H2D copy with compute (lossless; gated on the installed diffusers signature so older versions still work). Native (sd.cpp) path: - native_speed_flags: a first-class speed knob (default -> --diffusion-fa, a near-lossless CUDA win that was previously only added on offload tiers; max also -> --diffusion-conv-direct). conv-direct stays opt-in: measured +45% on CUDA, so it is never auto-on. Engine generate() merges it, de-duped against offload flags. Default profile: a GGUF model with no explicit speed_mode now resolves to the `default` profile (resolve_speed_mode), since compile's perturbation sits below the quantisation noise floor and so does not reduce quality versus the dense reference; out of the box a GGUF Z-Image generation drops from 1.80s to 0.81s. Dense models stay `off` / bit-identical, and an explicit speed_mode -- including "off" -- is always honored, so the byte-identical path remains one flag away and is the regression reference. Tooling: scripts/compile_probe.py (eager vs compiled GGUF probe), scripts/ perf_verify.py (the B200 verification above), and diffusion_bench.py gains --speed-mode so the speed tiers are benchmarkable. Tests: 183 passing (was 166); new coverage for the backend-flag snapshot/restore, GGUF compile eligibility, the balanced tiling/slicing split, native_speed_flags + the engine de-dup, and the sd-cli silent-hang timeout.
…+ engine/lever benchmarks The opt-in `max` speed tier now compiles the repeated block with mode=max-autotune-no-cudagraphs (dynamic=False) instead of the default mode: Triton autotuning for GEMM/conv-heavier models, gated to the tier where a longer cold compile is acceptable. CUDA-graph modes (reduce-overhead / max-autotune) are deliberately avoided -- both crash on the regionally-compiled block (its static output buffer is overwritten across denoise steps), measured. Adds two reproducible benchmarks used to validate the optimization research: - scripts/compare_engines.py: PyTorch (diffusers GGUF) vs native sd.cpp head-to-head. - scripts/leverage_probe.py: coordinate_descent_tuning + FirstBlockCache probes. Measured on B200 (Z-Image Q4_K_M, 1024px, 8 steps): default compile 0.80s/gen; coordinate_descent_tuning 0.79s (within noise, already covered by max-autotune); FirstBlockCache does not run on Z-Image (diffusers 0.38 block-detection / Dynamo).
…/fp4 on a dense source) Add an opt-in transformer_quant mode that loads the dense bf16 transformer and torchao-quantises it onto the low-precision tensor cores, instead of the GGUF transformer (which dequantises to bf16 per matmul and so runs at bf16 rate). On a B200 (Z-Image-Turbo, 1024px/8 steps): auto picks fp8 at 0.614s vs GGUF+compile's 0.823s (1.34x), int8 0.626s (1.32x), both at lower LPIPS than GGUF's own 4-bit floor. GGUF+compile stays the low-memory default and the fallback. The mode is gated on CUDA + bf16 + resident VRAM headroom (the dense load peaks ~21GB vs GGUF's 13GB); any unsupported arch/scheme, OOM, or quant failure falls back to GGUF with a logged reason. auto picks the best scheme per GPU via a real quantise+matmul smoke probe (Blackwell nvfp4/fp8/mxfp8, Ada/Hopper fp8, Ampere int8); a min-features filter skips the tiny projections that crash int8's torch._int_mm. New module mirrors diffusion_precision.py; quant runs before compile before placement. 184 -> tests pass; new test_diffusion_transformer_quant.py plus backend/route coverage. scripts/diffusion_bench.py gains --transformer-quant; scripts/quant_probe.py is the standalone torchao lever probe.
…ulate, prefer fp8 over mxfp8, reject 2:4 sparsity Consumer Blackwell halves tensor-core throughput on FP32 accumulate (fp8 419 vs 838 TFLOPS with FP16 accumulate; bf16 209), so: - fp8 config locks use_fast_accum=True (Float8MMConfig). torchao already defaults it on; pinning it guards consumer cards against a default change. On B200 it is identical speed and slightly better quality (LPIPS 0.050 vs 0.091). - the Blackwell auto ladder prefers fp8 over mxfp8 (measured faster + more accurate). 2:4 semi-structured sparsity evaluated and rejected (scripts/sparse_accum_probe.py): 2:4 magnitude-prune + fp8 gives LPIPS 0.858 (broken image) with no fine-tune, the cuSPARSELt kernel errors on torch 2.9, and it does not compose with torch.compile (our main ~2x). Documented as a dead end, not shipped.
…probe scripts/fp8_overflow_check.py hooks every quantised linear during a real Z-Image generation and reports max-abs + non-finite counts for use_fast_accum True vs False. Confirms fast accumulation is an accumulation-precision knob, not an overflow one: across 276 linears, including Z-Image's ~1.0e6 activation peaks (which overflow FP16), 0 non-finite elements and identical max-abs for both modes.
…8 accumulate, with user override Consumer/workstation GPUs (GDDR) halve fp8 FP32-accumulate throughput, so they want fast (FP16) accumulate; data-center HBM parts (B200/H100/A100/L40) are not nerfed and prefer the higher-precision FP32 accumulate. Add _is_consumer_gpu() (token-exact match on the device name per NVIDIA's GPU list, so workstation A4000 != data-center A40; GeForce/TITAN and unknown default to consumer) and gate the fp8 use_fast_accum on it. Measured: fast accumulate is ~2x on consumer Blackwell and ~8% on B200 (0.608 vs 0.665s), no overflow, quality below the quant noise floor. So the default leans to accuracy on data-center; a new request field transformer_quant_fast_accum (null=auto, true/false=force) lets the operator override per load (scripts/diffusion_bench.py --fp8-fast-accum auto|on|off). 187 diffusion tests pass (+ consumer detection, _resolve_fast_accum, and the override threading).
… a win on torch 2.9 scripts/nvfp4_probe.py measures NVFP4 via torchao on the real Z-Image transformer. Finding (B200, 1024px/8 steps): NVFP4 is a torchao feature and DOES run with use_triton_kernel=False (the default triton path needs the missing MSLK library), but only at bf16-compile rate (0.667s vs fp8 0.592s) -- it dequantises FP4->bf16 rather than using the FP4 tensor cores. The real FP4 speedup needs MSLK or torch>=2.11 + torchao's CUTLASS FP4 GEMM. The smoke probe (default triton=True) already keeps NVFP4 out of auto on this env, so auto correctly stays on fp8; NVFP4 activates automatically once fast.
…adder Validated NVFP4 on torch 2.11 + torchao CUTLASS FP4 in an isolated env. The FP4 tensor-core GEMM is genuinely active there (a 16384^3 GEMM hits ~3826 TFLOPS, 2.52x bf16 and 1.37x fp8), but it only beats fp8 on very large GEMMs. At the diffusion transformer's shapes (hidden ~3072, MLP ~12288, M~4096) NVFP4 is both slower (0.81x fp8 end to end on Z-Image 1024px) and less accurate (LPIPS 0.166 vs fp8's 0.044). Reorder the Blackwell auto ladder to fp8 before nvfp4 so auto is correct even on a future MSLK-equipped box; nvfp4 stays an explicit opt-in. Add scripts/nvfp4_t211_probe.py (extension diagnostics + GEMM micro + end-to-end).
…diffusion-phase14-int8-modulation
…n' into diffusion-phase15-int8-prequant
… into diffusion-phase16-native-engine-routing
…routing' into diffusion-sdserver
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c4e89ce8b6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if self._engine is not None: | ||
| return "oneshot", None, self._resolve_engine() |
There was a problem hiding this comment.
Don't let a cached fallback block server retries
After any fallback to one-shot calls _resolve_engine(), self._engine remains cached, so every later load takes this guard and returns oneshot before checking ensure_sd_server_binary(). In a session where sd-server was temporarily missing/unusable, or one model-specific server start failed and fell back to sd-cli, subsequent loads can never use a now-available/working resident server until the backend process restarts; distinguish an explicitly injected engine from the lazily cached fallback engine before forcing one-shot here.
Useful? React with 👍 / 👎.
| if self._stopped or not self.is_alive(): | ||
| raise RuntimeError("sd-server is not running.") |
There was a problem hiding this comment.
Surface pre-submit server stops as cancellation
When /images/unload or a superseding load sets the generation cancel event and stops the resident server after generate() has captured state.server but before this submit begins, this guard raises a generic RuntimeError("sd-server is not running."). The route only treats messages containing “cancelled” as client-state 409s, so this normal cancellation race is reported as a 500 generation failure; if cancel_event is already set here, raise SdCppCancelled instead.
Useful? React with 👍 / 👎.
# Conflicts: # studio/backend/core/inference/sd_cpp_args.py # studio/backend/core/inference/sd_cpp_backend.py # studio/backend/core/inference/sd_cpp_engine.py # studio/backend/tests/test_sd_cpp_args.py # studio/backend/tests/test_sd_cpp_backend.py # studio/backend/tests/test_sd_cpp_engine.py # studio/install_sd_cpp_prebuilt.py
…-sdserver # Conflicts: # studio/backend/core/inference/sd_cpp_backend.py # studio/backend/core/inference/sd_cpp_engine.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bc2afd491b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "transformer_cache": None, | ||
| "engine": "sd_cpp", | ||
| # "server" = resident sd-server (load once); "oneshot" = legacy per-image sd-cli. | ||
| "native_mode": state.mode, |
There was a problem hiding this comment.
Add native_mode to the status response schema
This field is added to the backend status, but the /images/load, /images/unload, and /images/status routes wrap the dict in DiffusionStatusResponse, and that model does not define native_mode, so FastAPI/Pydantic will drop it from the actual API response. In server/fallback scenarios users and the UI still cannot tell whether the resident sd-server path or one-shot fallback is active, despite this status value being populated here.
Useful? React with 👍 / 👎.
| cfg_scale = cfg_scale, | ||
| distilled_guidance = flux_guidance, | ||
| ) | ||
| blobs = state.server.img_gen(payload, on_step = self._on_log, cancel_event = cancel) |
There was a problem hiding this comment.
Scale the server timeout with batch size
This submits the whole batch as one sd-server job but leaves SdCppServer.img_gen() on its fixed 1800s deadline. On CPU/native loads where each image can legitimately take many minutes, a batch of 2–8 can exceed 30 minutes total even though the previous one-shot path gave each image its own 1800s timeout, so valid batches are cancelled partway through. Pass a timeout proportional to the requested batch size or chunk the batch so server mode preserves the old per-image budget.
Useful? React with 👍 / 👎.
Addresses review findings on the sd-server backend: - Router: treat a runnable sd-server as native availability, so an sd-server-only install (no sd-cli) still routes to the native engine instead of silently falling back to diffusers. - Backend: probe the sd-server binary before the multi-GB asset download, falling back to one-shot sd-cli up front when it cannot run. - Backend: a lazily cached one-shot fallback engine no longer pins the backend to one-shot; only an explicitly injected engine does, so a now-available server can be used on the next load. - Backend: mask explicit seeds to sd.cpp's signed int64 range before submitting a server job (large seeds were rejected/wrapped in server mode only), and split batches above the server's per-job limit into chunks, each with a timeout proportional to its image count. - Backend/server: make server startup cancellable. stop() signals an abort event before taking the lifecycle lock so a blocking readiness wait bails promptly; unload() stops a not-yet-committed pending server. - Backend: status() clears stale loaded state when the resident server has exited, so clients reload instead of hammering a dead process with 500s. - Server: abandon a poll whose best-effort cancel is not honored within a grace window (releasing the generate lock), report a pre-submit stop/cancel as cancellation (409, not 500), and verify JSON responses are the expected type before indexing. - Server: use a bounded deque for the stdout tail buffer. - Add native_mode to DiffusionStatusResponse so the field is not dropped by the response model. Adds regression tests for each behavioral change.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 852c734246
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # non-runnable binary (wrong arch, missing shared libs, no execute bit) would | ||
| # otherwise pass as available and only fail inside the background load, instead | ||
| # of falling back to diffusers now. | ||
| binary = ensure_sd_cpp_binary(allow_install = _install_allowed()) |
There was a problem hiding this comment.
Check sd-server before installing sd-cli
When SD_SERVER_PATH points to a runnable server but no sd-cli is present, this call runs first with installation enabled by default, so selection may download/install the sd-cli archive before line 145 ever considers the existing preferred server. That makes server-only installs pay avoidable network/startup cost and mutates the local install even though the backend would use sd-server; probe the server first, or only allow CLI installation after the server path is absent/unusable.
Useful? React with 👍 / 👎.
| if env: | ||
| run_env.update(env) | ||
| logger.info("starting sd-server: %s", " ".join(cmd)) | ||
| self._tail = [] |
There was a problem hiding this comment.
Keep the sd-server log tail bounded
In a resident server that stays up across many generations, resetting _tail to a plain list discards the deque(maxlen=200) created in __init__. Because _drain_stdout appends every verbose sampling/log line for the process lifetime, long Studio sessions can accumulate an unbounded in-memory log; reset this to a bounded deque or clear the existing deque instead.
Useful? React with 👍 / 👎.
| threads: Optional[int] = None | ||
| sampling_method: Optional[str] = None | ||
| flow_shift: Optional[float] = None | ||
| server: Optional[SdCppServer] = None |
There was a problem hiding this comment.
Unload resident sd-server before training
When native sd.cpp is enabled on a non-CPU target (for example MPS or forced sd_cpp on GPU), this resident server keeps the diffusion weights in a child process after /images/load. I checked the training pre-spawn cleanup in routes/training.py, and it still imports core.inference.diffusion.get_diffusion_backend() and unloads only that diffusers singleton before releasing the arbiter, so starting training after a native image load can leave sd-server holding VRAM and trigger OOM instead of freeing diffusion first.
Useful? React with 👍 / 👎.
| # Set for the duration of a generation so the continuous stdout drain can feed | ||
| # the active request's step-progress callback; cleared in img_gen's finally. | ||
| self._step_listener: Optional[Callable[[str], None]] = None | ||
| self._client = httpx.Client(timeout = 30.0) |
There was a problem hiding this comment.
Bypass proxies for the loopback sd-server client
This client talks only to the loopback sd-server, but httpx.Client honors proxy environment variables by default. In environments with HTTP_PROXY/HTTPS_PROXY set and no matching NO_PROXY for 127.0.0.1, readiness and generation requests can be sent to the proxy instead of the local child process; the other local llama-server clients in this repo set trust_env=False, and this one should too.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 852c734246
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if env: | ||
| run_env.update(env) | ||
| logger.info("starting sd-server: %s", " ".join(cmd)) | ||
| self._tail = [] |
There was a problem hiding this comment.
Keep the server log tail bounded
In server mode this resets the fixed-size deque(maxlen=200) to a plain list, so the stdout drain now retains every verbose sd-server line for the lifetime of the resident process. Long-running sessions or many generations will steadily grow this in-memory log instead of keeping only the diagnostic tail; reset it to a new bounded deque(maxlen=200) to preserve the intended cap.
Useful? React with 👍 / 👎.
| with Image.open(out_path) as im: | ||
| images.append(im.copy()) | ||
| seeds.append(seed_i) | ||
| if state.mode == "server" and state.server is not None: |
There was a problem hiding this comment.
Clear dead server state before generating
If the resident sd-server exits while idle and a client goes straight to /images/generate without first polling /images/status, this branch still treats the model as loaded and calls img_gen, which raises RuntimeError("sd-server is not running."); the route maps that to a 500 and _state remains stale until some later status call. Check state.server.is_alive() here, clear the loaded state, and raise DIFFUSION_NOT_LOADED_MSG so the client gets the recoverable 409/reload path.
Useful? React with 👍 / 👎.
| # non-runnable binary (wrong arch, missing shared libs, no execute bit) would | ||
| # otherwise pass as available and only fail inside the background load, instead | ||
| # of falling back to diffusers now. | ||
| binary = ensure_sd_cpp_binary(allow_install = _install_allowed()) |
There was a problem hiding this comment.
Check sd-server before auto-installing sd-cli
When a CPU/MPS host already has only SD_SERVER_PATH/UNSLOTH_SD_CPP_PATH pointing at a runnable sd-server, this line still calls ensure_sd_cpp_binary(...allow_install=True) first. With the default install policy that can trigger an unnecessary prebuilt download or a network timeout before the router ever checks the resident server that the backend prefers and can use without sd-cli; check/probe sd-server first, or avoid auto-installing sd-cli unless no server is available.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e9d8588798
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| jr = self._client.get(f"{self.base_url}{_JOBS_PATH}/{job_id}", timeout = 10.0) | ||
| except (*_TRANSPORT_ERRORS, httpx.TimeoutException): |
There was a problem hiding this comment.
Handle closed-client races as cancellation
When /images/unload or a superseding load calls stop() during an active server generation, it sets the cancel event and closes the shared httpx client from another thread. If that happens after this loop's cancel/is_alive checks but before this GET starts, httpx raises a closed-client RuntimeError, which is not caught here and bubbles to the route as a 500 instead of the normal cancelled 409. Treat a closed-client RuntimeError as SdCppCancelled when cancel_event is set, or avoid closing the client until the poller exits.
Useful? React with 👍 / 👎.
| cancel_event = cancel, | ||
| total_timeout = _SERVER_PER_IMAGE_TIMEOUT_S * count, | ||
| ) | ||
| images.extend(Image.open(io.BytesIO(b)).convert("RGB") for b in blobs) |
There was a problem hiding this comment.
Reject incomplete server batches
If sd-server completes a batched job but returns fewer image blobs than the requested batch_count (for example one image in the batch failed to encode while another succeeded), this accepts and persists the short result as a successful Studio generation. The one-shot path either produced every requested image or raised, so server mode should verify len(blobs) == count here and fail/retry the chunk instead of silently dropping images from the user's requested batch.
Useful? React with 👍 / 👎.
| return False # cannot exec at all (wrong arch / no execute bit / missing loader) | ||
| except Exception: # noqa: BLE001 -- timeout or anything odd: don't block on a flaky probe | ||
| return True | ||
| return proc.returncode not in (126, 127) |
There was a problem hiding this comment.
Treat crashed sd-server probes as unavailable
On hosts where the discovered sd-server starts but immediately dies from a signal (for example an incompatible prebuilt hitting SIGILL on an older CPU), subprocess.run reports a negative return code, but this treats every code except 126/127 as runnable. The router can then mark a server-only install as native-available and route CPU/MPS loads into sd_cpp, only for the background load to download assets and fail during server startup instead of falling back to diffusers up front. Return false for signal exits (or non-zero --help failures) so crashing servers do not hijack the load path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d511569b92
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| """ | ||
| with self._lifecycle_lock: | ||
| self._stopped = False | ||
| self._abort.clear() |
There was a problem hiding this comment.
Honor stops that arrive before server startup
When /images/unload or a superseding load calls stop() after _pending_server is published but before this start() acquires _lifecycle_lock, stop() sets _abort and disposes the client while no process exists. This line then clears that already-delivered abort and proceeds to spawn sd-server; the readiness probe uses the closed httpx client and raises outside the if not _wait_ready(...) cleanup path, so the just-spawned model process can be left running after the load was cancelled. The fresh evidence is that the pending-server handoff now allows stop() to run in this pre-start window, but start() still unconditionally clears _abort.
Useful? React with 👍 / 👎.
…-sdserver # Conflicts: # studio/backend/core/inference/diffusion_engine_router.py # studio/backend/tests/test_sd_cpp_backend.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ae269fc820
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| """ | ||
| if self._engine_injected and self._engine is not None: | ||
| return "oneshot", None, self._resolve_engine() | ||
| server_binary = ensure_sd_server_binary(allow_install = _install_allowed()) |
There was a problem hiding this comment.
Pass the accelerator when installing sd-server
When the native engine is forced/enabled on a non-CPU backend and the machine has an older sd-cli-only install, this server lookup can trigger ensure_sd_server_binary() with its default CPU/auto accelerator. The installer then selects the plain Linux build rather than the ROCm/Vulkan/CUDA build that ensure_sd_cpp_binary(... accelerator=_install_accelerator_for(backend)) would use, so the newly preferred resident sd-server runs without the requested GPU backend; pass the resolved accelerator through this path too.
Useful? React with 👍 / 👎.
| self.cancel(job_id) | ||
| raise RuntimeError(f"sd-server generation timed out after {total_timeout}s") |
There was a problem hiding this comment.
When an sd-server generation exceeds this deadline (for example an unusually slow CPU chunk), this sends the best-effort cancel and immediately returns a failure, but current sd-server does not interrupt already-generating jobs via /cancel (cancel_generating=false / 409). Unlike the one-shot path, which kills the sd-cli process on timeout, the resident server keeps denoising in the background while Studio reports failure, so later generations or reloads queue/block behind the abandoned job until it naturally finishes; stop/restart the server or mark it unloaded on timeout.
Useful? React with 👍 / 👎.
- Treat a crashed sd-server probe (signal death / non-127 nonzero) as unavailable so a broken prebuilt falls back to diffusers instead of routing to a server that dies on startup. - Drop stale loaded state when a resident server has exited before a generate, returning the recoverable not-loaded path rather than a 500. - Reject incomplete server batches (fewer blobs than requested) like the one-shot path instead of silently dropping images. - Bound the server log tail in place (keep the deque(maxlen)) and bypass HTTP(S) proxies for the loopback client (trust_env=False). - Honor a stop() that arrives after the server is published but before start() takes the lock, so a cancelled load cannot leak a spawned model process. - Map a closed-client RuntimeError during poll to a cancellation when the generation is being cancelled, so unload races surface as 409 not 500. - Stop a timed-out server job (best-effort cancel then teardown) so an abandoned generation cannot keep denoising and block later loads. - Install the accelerator-matched sd-server build (ROCm/Vulkan/CUDA) and probe the resident server before auto-installing sd-cli, so a server-only or GPU host does not fetch the wrong or an unused binary.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb2d0956b5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| resp = self._client.post( | ||
| f"{self.base_url}{_IMG_GEN_PATH}", json = payload, timeout = submit_timeout | ||
| ) |
There was a problem hiding this comment.
Handle closed-client submit races as cancellation
When /images/unload or a superseding load sets the generation cancel event and calls stop() after this method passes the initial is_alive() guard but before this POST is sent, stop() closes the shared httpx client and post() raises a plain closed-client RuntimeError. Unlike the poll GET path below, this submit path does not translate that race to SdCppCancelled, so a normal user cancellation is reported by the route as a 500 generation failure instead of the recoverable cancelled 409.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f0b2daff15
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| with self._lock: | ||
| self._pending_server = server |
There was a problem hiding this comment.
Re-check cancellation before starting a pending server
When /images/unload or an arbiter eviction arrives after the token check above but while old_state.server.stop() is still running, it observes no _pending_server, increments _load_token, and returns; this assignment then publishes and starts a stale server without re-checking the token. The fresh evidence is that the old-server stop now happens before _pending_server is published, so a cancelled load can still spend up to the startup timeout loading a new model under _generate_lock and block the next load until the post-start token check. Re-check _load_token under this lock before assigning/starting the server.
Useful? React with 👍 / 👎.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Summary
The native diffusion tier (stable-diffusion.cpp) ran
sd-clione-shot per image.begin_loadonly resolved and downloaded asset paths into a frozen state, so no model was ever held in memory, and everygeneratere-spawnedsd-cliand reloaded the multi-GB GGUF from disk. A batch of N images was N full weight loads, and for large checkpoints the reload dominated the wall clock. The "loaded" state in the UI was effectively a label.This makes the native tier a resident backend backed by stable-diffusion.cpp's persistent
sd-server(theexamples/servertarget), mirroring the chat backend'sllama-serverlifecycle:begin_loadspawnssd-serveronce (the model loads there, for real) and pollsGET /sdcpp/v1/capabilitiesuntil ready;unloadterminates it.generatesubmits ONE asyncPOST /sdcpp/v1/img_genjob for the whole batch (no reload), polls it to completion, and decodes the returned images.The one-shot
sd-clipath is kept as an automatic fallback for builds that lacksd-server, so behavior is strictly backwards compatible. The backend's public surface (begin_load/load_progress/generate/generate_progress/unload/status) is unchanged, so the routes and the engine router need no change.Why sd-server is a true "load once"
Upstream
main.cpploads the model (new_sd_ctx) before it binds the port and printslistening on:, so a 200 from/sdcpp/v1/capabilitiesis an unambiguous ready signal and a failed load exits the process before listening (surfaced with the captured log tail). The native async API takes the whole batch in one request (batch_count) and supports cancellation (/sdcpp/v1/jobs/{id}/cancel).Changes
studio/backend/core/inference/sd_cpp_server.py: theSdCppServerprocess + HTTP manager (spawn, readiness poll, job submit/poll, cancel, SIGTERM to SIGKILL stop). Reuses the shared process-lifetime, subprocess, and env helpers the chat backend uses. The process is spawned inside the stdout-drain thread so its parent-death binding (PR_SET_PDEATHSIG, which is per-thread on Linux) is tied to the interpreter's life, not a transient spawner thread.sd_cpp_engine.py:find_sd_server_binary()(same precedence as the sd-cli finder), one-shot engine kept for the fallback and the ESRGAN upscale mode.sd_cpp_args.py:build_sd_cpp_server_command(model + offload/speed + listen flags only, no per-request params) andbuild_img_gen_request(Studio params to the native job JSON, with the same FLUX-distilled vs classifier-free guidance split as the one-shot mapping).sd_cpp_backend.py: server-first with one-shot fallback (_resolve_backend); loads/reloads stop the old server before starting the new one under the generation lock;statusreportsnative_mode(serveroroneshot).install_sd_cpp_prebuilt.py: locate andchmodsd-server(it ships in the same prebuilt archive assd-cli, verified against the current release).Verification
sd-server) and CPU (the CPU prebuiltsd-server, CUDA hidden). In each case: a single model load across multiple generations (server pid stable across gens, exactly onelistening on:), abatch_size=2request served from one job with distinct per-image seeds, the second generation faster than the first (no reload), andunloadthen reload spawning a fresh process.Stacking
Based on and targeting
diffusion-phase16-native-engine-routing(the head of #6724, which descends from theimage-generationbase now tracked by #6763; #6763 reposts the same branch insideunslothai/unslothand supersedes the now-closed #6658), so it applies cleanly on top of the current diffusion stack. Addresses oobabooga's review of the Phase 16 native-engine PR. It is independent of the image-workflows follow-up; both touchsd_cpp_backend.py, so whichever lands second needs a trivial reconcile there.