Skip to content

Studio diffusion (Phase 4): native stable-diffusion.cpp engine for CPU/Mac - #6679

Merged
oobabooga merged 18 commits into
image-generationfrom
diffusion-phase4-native
Jul 1, 2026
Merged

oobabooga merged 18 commits into
image-generationfrom
diffusion-phase4-native

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Phase 4 of porting the richer diffusion stack onto the image-generation backend, building on #6675 (Phase 2: memory / speed / precision) and #6670 (Phase 1: device policy). This adds the native stable-diffusion.cpp engine, the CPU and Apple-Silicon tier of a two-engine strategy that mirrors the chat backend's llama.cpp shell-out.

Diffusers stays the default and only path on CUDA / ROCm / XPU. This engine exists for the hardware diffusers serves poorly (CPU, Apple MPS, and very low VRAM budgets), and it consumes the same split GGUF assets Studio already curates for the diffusers path, so a model loaded for one engine needs no re-download for the other.

Everything is additive: new modules plus a standalone installer and smoke script. Nothing in the existing diffusers path changes, so this is a no-op until the native engine is selected. Stacked on #6675; I will rebase onto main and retarget the base once the lower phases land.

What it does

  • Pure sd-cli command builder (sd_cpp_args.py). Maps each family to its text-encoder flag (Z-Image's Qwen3 to --llm, Qwen-Image's Qwen2-VL to --qwen2vl, FLUX.1's CLIP-L + T5 to --clip_l / --t5xxl) and the diffusers memory policy (none / group / model / sequential) to sd.cpp's own offload flags (--offload-to-cpu, --clip-on-cpu, --vae-on-cpu, --vae-tiling, --diffusion-fa). One user-facing memory knob drives both engines identically.
  • The engine (sd_cpp_engine.py). SdCppEngine over a located sd-cli: a find_sd_cpp_binary() with the same precedence as the llama finder (env override, then the Studio install root, then an in-tree build, then PATH), an is_available / version probe, and a one-shot subprocess generate that streams progress and returns the written PNG. runtime_env() prepends the binary's own directory to the platform library path (LD_LIBRARY_PATH / DYLD_LIBRARY_PATH / PATH) so a prebuilt's bundled libstable-diffusion.so resolves. select_diffusion_engine() is the pure routing decision: GPU backends stay on diffusers, CPU / MPS take the native engine when its binary is present, and a prefer_native override can force it anywhere.
  • Prebuilt installer (install_sd_cpp_prebuilt.py). Resolves and downloads the per-host stable-diffusion.cpp release zip (macOS-arm64 / Metal, Linux x86_64 CPU, plus Vulkan / ROCm / Windows variants) into the Studio install root, where the finder picks it up. resolve_release_asset() is a pure, unit-tested host-to-asset matrix, so Apple Silicon and CPU users get a working binary with nothing to compile.
  • Smoke harness (scripts/sd_cpp_smoke.py). Drives the real engine over a built or installed sd-cli and a set of split GGUF assets, the native analogue of scripts/diffusion_bench.py.

Verification (single B200 box)

Built sd-cli from source (CUDA) and installed the prebuilt (CPU), then generated Z-Image-Turbo Q4_K end to end through SdCppEngine, all producing coherent images:

binary memory mode offload flags generation
source (CUDA) balanced --offload-to-cpu --diffusion-fa 5.0 s
source (CUDA) low_vram --offload-to-cpu --clip-on-cpu --vae-on-cpu --vae-tiling --diffusion-fa 13.4 s
prebuilt (CPU) low_vram (same) 50.4 s on CPU

The CPU prebuilt run exercises the dynamically-linked path and confirms runtime_env() lets the bundled shared library load. The installer was verified live: resolve_release_asset selects the correct asset for Linux (CPU / Vulkan / ROCm), macOS-arm64, and Windows (avx2 / cuda12 / vulkan) against a real release, and a real download + extract produced a runnable sd-cli.

Tests

CPU only, with subprocess and the filesystem stubbed, run from studio/backend:

python -m pytest tests/test_sd_cpp_args.py tests/test_sd_cpp_engine.py tests/test_sd_cpp_install.py

49 new tests covering the command builder, the offload and family mappings, the binary finder precedence, the version probe, generate (success, nonzero exit, missing output, missing binary), runtime_env, the engine routing matrix, and the installer's host-to-asset resolver. The full diffusion suite is 166 passing.

Out of scope (later)

Wiring the route / backend to dispatch to the native engine (asset resolution for the split VAE / text-encoder files, status reporting which engine is active) and the image-to-image / editing / LoRA / upscale / video feature surface. This PR lands the engine, installer, and routing decision as a self-contained, tested unit.

danielhanchen and others added 12 commits June 25, 2026 11:14
…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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a native stable-diffusion.cpp (sd-cli) engine integration for the diffusion backend, including command-line argument building, engine execution, routing logic to select between diffusers and sd-cli, and a script to download prebuilt binaries. Feedback on the implementation highlights a potential infinite hang when synchronously reading subprocess output, which bypasses the timeout, and recommends using a background thread instead. Additionally, the reviewer suggests adding a custom User-Agent header to GitHub API requests to avoid 403 errors, and replacing the legacy urllib.request.urlretrieve with urlopen and an explicit timeout to prevent network-related hangs during binary downloads.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +230 to +246
stderr = subprocess.STDOUT,
text = True,
errors = "replace",
env = run_env,
)
tail: list[str] = []
try:
assert proc.stdout is not None
for line in proc.stdout:
line = line.rstrip("\n")
tail.append(line)
if len(tail) > 40:
tail.pop(0)
if on_log is not None:
on_log(line)
ret = proc.wait(timeout = timeout)
except subprocess.TimeoutExpired:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Synchronously iterating over proc.stdout is a blocking operation. If the subprocess hangs or becomes idle without closing its stdout stream, the loop for line in proc.stdout will block indefinitely. This completely bypasses the timeout parameter because proc.wait(timeout=timeout) is only called after the stdout stream is fully exhausted.

To ensure the timeout is strictly respected, read the subprocess output in a background thread and let the main thread wait on proc.wait(timeout=timeout). If a timeout occurs, the main thread will kill the process, which automatically closes the pipe and terminates the background thread.

        tail: list[str] = []
        import threading
        def read_output() -> None:
            assert proc.stdout is not None
            for line in proc.stdout:
                line = line.rstrip("\n")
                tail.append(line)
                if len(tail) > 40:
                    tail.pop(0)
                if on_log is not None:
                    on_log(line)

        reader_thread = threading.Thread(target=read_output, daemon=True)
        reader_thread.start()

        try:
            ret = proc.wait(timeout = timeout)
        except subprocess.TimeoutExpired:
            proc.kill()
            reader_thread.join(timeout=5.0)
            raise RuntimeError(f"sd-cli timed out after {timeout}s")
        finally:
            if proc.poll() is None:
                proc.kill()
            reader_thread.join(timeout=5.0)

sel = [a for a in pool if "avx2" in a.lower()]
return sel[0] if sel else (pool[0] if pool else None)

# linux (and anything else unix-like)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

GitHub API strictly requires a valid User-Agent header for all requests. While some environments or Python versions might fallback or be tolerated, requests without a custom User-Agent can be intermittently rejected with a 403 Forbidden error, especially under heavy load or from shared/corporate IPs. Adding a custom User-Agent ensures reliable API access.

Suggested change
# linux (and anything else unix-like)
req = urllib.request.Request(
RELEASES_API,
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "Unsloth-Studio",
}
)

names = [a["name"] for a in release.get("assets", [])]
chosen = resolve_release_asset(
names,
system = platform.system(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

urllib.request.urlretrieve is a legacy function that does not support a timeout parameter. If the network connection stalls or drops during the download of the prebuilt binary, the process can hang indefinitely.

Replacing it with urllib.request.urlopen using an explicit timeout and writing the chunks via shutil.copyfileobj prevents infinite hangs and allows setting a custom User-Agent for more reliable downloads.

Suggested change
system = platform.system(),
req = urllib.request.Request(url, headers={"User-Agent": "Unsloth-Studio"})
with urllib.request.urlopen(req, timeout=600.0) as response, open(archive, "wb") as out_file:
import shutil
shutil.copyfileobj(response, out_file)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a7b8f825da

ℹ️ 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".

tail: list[str] = []
try:
assert proc.stdout is not None
for line in proc.stdout:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the timeout while reading sd-cli output

When sd-cli hangs or simply runs longer than the requested timeout while keeping stdout open, this for line in proc.stdout loop blocks until EOF, so proc.wait(timeout=...) is only reached after the process has already exited. In that scenario the advertised timeout is ineffective and a Studio generation can hang indefinitely instead of killing the subprocess.

Useful? React with 👍 / 👎.

Comment on lines +115 to +116
base = Path(home).parent if home else Path.home() / ".unsloth"
return base / "stable-diffusion.cpp"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Probe the custom Studio install root

When UNSLOTH_STUDIO_HOME or STUDIO_HOME is set, the installer defaults to that custom root's parent, but find_sd_cpp_binary() only probes ~/.unsloth/stable-diffusion.cpp unless the user also sets UNSLOTH_SD_CPP_PATH. A user with a custom Studio home can therefore get a successful default install that the engine will not find on the next run.

Useful? React with 👍 / 👎.

Comment on lines +182 to +183
if params.batch_count and params.batch_count != 1:
cmd += ["--batch-count", str(int(params.batch_count))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle multi-image batch outputs before enabling them

When params.batch_count > 1, this emits --batch-count, but sd-cli saves batch results using suffixed output names rather than the exact output_path; SdCppEngine.generate() later requires that exact path to exist and returns only one Path. Any caller using the exposed batch count will get a false failure after a successful generation, so either reject batch counts above one here or teach the engine to return the generated batch paths.

Useful? React with 👍 / 👎.

Comment on lines +95 to +96
else: # auto / cpu -> the plain build with no accelerator marker
sel = [a for a in pool if not any(m in a.lower() for m in _LINUX_ACCEL_MARKERS)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unsupported Linux CUDA installs

When the installer runs on Linux with accelerator='cuda' (the CLI allows this value), cuda is not in _LINUX_ACCEL_TOKEN, so this falls through to the auto/CPU branch and returns the plain CPU archive. Users explicitly requesting a CUDA native binary will silently install the CPU build instead of getting an error or a CUDA asset, making generation unexpectedly slow.

Useful? React with 👍 / 👎.

Comment thread studio/install_sd_cpp_prebuilt.py Outdated

# accelerator -> the token that must appear in a Linux/Windows asset name.
_LINUX_ACCEL_TOKEN = {"rocm": "rocm", "vulkan": "vulkan"}
_WINDOWS_ACCEL_TOKEN = {"cuda": "cuda12", "vulkan": "vulkan", "rocm": "rocm", "cpu": "avx2", "auto": "avx2"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detect Windows CPU support before choosing AVX2

When Windows users run the installer with --accelerator auto or cpu, this mapping always selects the AVX2 x64 archive and the Windows resolver does not consult machine or CPU feature flags. On Windows ARM64 or older x64 CPUs without AVX2, installation can report success but the downloaded binary will not be runnable; choose an asset based on architecture/features or return no match.

Useful? React with 👍 / 👎.

from typing import Optional, Sequence

REPO = "leejet/stable-diffusion.cpp"
RELEASES_API = f"https://api.github.com/repos/{REPO}/releases/latest"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pin the sd.cpp release used by the installer

Because the installer always downloads /releases/latest, a fresh install after a stable-diffusion.cpp CLI change can pull an untested binary while this engine still hardcodes the current flags and output assumptions. Pin the release/tag the command builder was verified against, or probe capabilities before accepting the binary, so future upstream releases do not break new Studio installs without a Studio code change.

Useful? React with 👍 / 👎.

…output

Iterating proc.stdout directly blocks until the stream closes, so a sd-cli that hangs
without producing output (or without closing stdout) would never reach proc.wait and the
wall-clock timeout was silently bypassed. Drain stdout on a daemon thread and wait on the
PROCESS, so the main thread always enforces the timeout and kills a hung process (which
closes the pipe and ends the reader). Add a test that times out even when stdout blocks,
and make the no-binary test hermetic so a host-installed sd-cli can't leak in.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a native stable-diffusion.cpp (sd-cli) engine integration for the diffusion backend, including command building, subprocess execution with safe timeout handling, engine routing, and a prebuilt binary installer. The feedback highlights two key issues in the installer script: first, GitHub's REST API requires a valid User-Agent header to prevent 403 Forbidden errors, and second, the main entry point should catch specific network and OS exceptions (urllib.error.URLError, OSError) rather than just RuntimeError to ensure robust error handling.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.


def _fetch_latest_release(*, token: Optional[str] = None, timeout: float = 30.0) -> dict:
"""GET the latest-release JSON from GitHub (token optional, lifts rate limit)."""
req = urllib.request.Request(RELEASES_API, headers = {"Accept": "application/vnd.github+json"})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

GitHub's REST API strictly requires a valid User-Agent header for all requests. Requests without one are rejected with a 403 Forbidden error. Adding a custom User-Agent header ensures the request succeeds.

Suggested change
req = urllib.request.Request(RELEASES_API, headers = {"Accept": "application/vnd.github+json"})
req = urllib.request.Request(
RELEASES_API,
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "Unsloth-Studio",
},
)

Comment on lines +210 to +217
try:
install(
install_dir = Path(args.install_dir) if args.install_dir else None,
accelerator = args.accelerator,
)
except RuntimeError as exc:
print(f"error: {exc}", file = sys.stderr)
return 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In main, only RuntimeError is caught. However, network calls in install can raise urllib.error.URLError or OSError. To avoid broad exception handling while ensuring all expected failures are handled gracefully, catch specific exceptions (RuntimeError, urllib.error.URLError, OSError) and print the specific exception type and its details.

Suggested change
try:
install(
install_dir = Path(args.install_dir) if args.install_dir else None,
accelerator = args.accelerator,
)
except RuntimeError as exc:
print(f"error: {exc}", file = sys.stderr)
return 1
try:
install(
install_dir = Path(args.install_dir) if args.install_dir else None,
accelerator = args.accelerator,
)
except (RuntimeError, urllib.error.URLError, OSError) as exc:
print(f"error: {type(exc).__name__}: {exc}", file = sys.stderr)
return 1
References
  1. When handling exceptions, avoid broad except Exception clauses. Instead, catch specific exceptions and log them (at least at a debug level) to aid in troubleshooting. If a failure is expected, log the specific exception type and its details.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8cc0fe3790

ℹ️ 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".

return hit

# 3. Default install root (sibling of ~/.unsloth/llama.cpp).
hit = _first_file(_layout_candidates(Path.home() / ".unsloth" / "stable-diffusion.cpp"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Look in the custom Studio install root for sd-cli

When UNSLOTH_STUDIO_HOME/STUDIO_HOME is set, default_install_dir() no longer writes to ~/.unsloth; it writes to Path($STUDIO_HOME).parent / "stable-diffusion.cpp", while this finder still probes only ~/.unsloth/stable-diffusion.cpp. In custom Studio installs the install script can succeed, but a later SdCppEngine()/select_diffusion_engine() call reports native_available=False unless the user also sets UNSLOTH_SD_CPP_PATH. Please derive the managed root from the same storage-root/env logic used by the installer/llama finder.

Useful? React with 👍 / 👎.

accel = accelerator.lower()
arch = _arch_tokens(machine)
zips = [
a for a in asset_names if a.lower().endswith(".zip") and not a.lower().startswith("cudart")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install the CUDA runtime helper for Windows CUDA builds

For Windows with --accelerator cuda, resolve_release_asset() selects the sd-...-bin-win-cuda12-x64.zip archive, but this filter drops the paired cudart-sd-bin-win-cu12-x64.zip and install() only downloads the single selected archive. The release publishes CUDA runtime DLLs in that helper archive, so a fresh Windows CUDA install leaves sd-cli unable to load cudart/cublas unless a matching toolkit is already on PATH; please fetch and extract the helper whenever a CUDA asset is selected.

Useful? React with 👍 / 👎.


if ret != 0:
raise RuntimeError(f"sd-cli exited {ret}. Last output:\n" + "\n".join(tail[-12:]))
if not out.is_file():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject stale output files before returning success

When a caller reuses output_path, this check accepts any file that was already there before sd-cli ran. The code is trying to catch the zero-exit/no-output case, but if a previous generation left out behind, that failure path instead returns the old PNG as if it were the new result; unlink the target before launching or verify it was modified by this subprocess.

Useful? React with 👍 / 👎.

Comment on lines +182 to +183
if params.batch_count and params.batch_count != 1:
cmd += ["--batch-count", str(int(params.batch_count))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle sd-cli's suffixed outputs for batches

When params.batch_count > 1 and the caller passes a normal output like img.png, sd-cli does not write img.png; its save_results path writes suffixed files such as img_0.png, img_1.png unless the output contains a printf-style specifier. generate() later checks only the original output_path, so a successful batch generation is reported as missing output (or hits the stale-output case above); either disallow batches here or use a sequence output pattern and return the generated files.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a native stable-diffusion.cpp (sd-cli) engine integration for the diffusion backend, providing a CPU and Apple Silicon-optimized alternative to the diffusers path. It includes a command builder, an execution engine with device routing, an installer for prebuilt binaries, and comprehensive unit and smoke tests. The review feedback highlights several critical improvements: adding a network timeout to the prebuilt installer download, properly reaping killed subprocesses in the engine to prevent zombie processes, normalizing backend strings to lowercase to avoid routing bugs, and robustly handling None values for prompts to prevent literal "None" string generation.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread studio/install_sd_cpp_prebuilt.py Outdated
target.mkdir(parents = True, exist_ok = True)
archive = target / chosen
print(f"downloading {chosen} -> {archive}", flush = True)
urllib.request.urlretrieve(url, archive) # noqa: S310 (github release URL)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using urllib.request.urlretrieve without a timeout can cause the installation process to hang indefinitely if the network connection is lost or the server stops responding. It is safer to use urllib.request.urlopen with an explicit timeout and write the file in chunks or use shutil.copyfileobj.

Suggested change
urllib.request.urlretrieve(url, archive) # noqa: S310 (github release URL)
import shutil
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=300.0) as response, open(archive, "wb") as out_file:
shutil.copyfileobj(response, out_file)

Comment on lines +261 to +263
finally:
if proc.poll() is None:
proc.kill()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When terminating the subprocess due to an exception or timeout, calling proc.kill() without subsequently waiting/reaping the process can lead to zombie processes in long-running server environments. It is recommended to call proc.wait() with a short timeout after killing the process to ensure it is properly reaped.

Suggested change
finally:
if proc.poll() is None:
proc.kill()
finally:
if proc.poll() is None:
proc.kill()
try:
proc.wait(timeout=5.0)
except Exception:
pass

Comment on lines +302 to +306
if prefer_native and native_available:
return ENGINE_SD_CPP
if backend not in _GPU_BACKENDS and native_available:
return ENGINE_SD_CPP
return ENGINE_DIFFUSERS

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The backend string is matched against _GPU_BACKENDS (which contains lowercase strings like "cuda", "rocm", "xpu"). If backend is passed with uppercase characters (e.g., "CUDA"), the check backend not in _GPU_BACKENDS will evaluate to True, incorrectly routing the request to the native sd_cpp engine instead of diffusers. Normalizing the backend string to lowercase before checking prevents this routing bug.

Suggested change
if prefer_native and native_available:
return ENGINE_SD_CPP
if backend not in _GPU_BACKENDS and native_available:
return ENGINE_SD_CPP
return ENGINE_DIFFUSERS
backend_lower = backend.lower()
if prefer_native and native_available:
return ENGINE_SD_CPP
if backend_lower not in _GPU_BACKENDS and native_available:
return ENGINE_SD_CPP
return ENGINE_DIFFUSERS

Comment on lines +153 to +154
if not str(params.prompt).strip():
raise ValueError("prompt is required")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If params.prompt is None, str(params.prompt) evaluates to the literal string "None". This bypasses the empty/whitespace check and proceeds to generate an image with the prompt "None". Adding a check for None or falsy values first ensures that missing prompts are correctly caught and rejected.

Suggested change
if not str(params.prompt).strip():
raise ValueError("prompt is required")
if not params.prompt or not str(params.prompt).strip():
raise ValueError("prompt is required")

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8cc0fe3790

ℹ️ 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".

return hit

# 3. Default install root (sibling of ~/.unsloth/llama.cpp).
hit = _first_file(_layout_candidates(Path.home() / ".unsloth" / "stable-diffusion.cpp"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the custom Studio install root in discovery

When UNSLOTH_STUDIO_HOME or STUDIO_HOME is set, install_sd_cpp_prebuilt.default_install_dir() installs the binary under that custom root's sibling (for example /opt/unsloth/stable-diffusion.cpp), but this discovery path only checks ~/.unsloth/stable-diffusion.cpp unless the user also sets UNSLOTH_SD_CPP_PATH. In custom-root Studio installs, the installer can therefore succeed while find_sd_cpp_binary() still reports no native engine, so CPU/MPS users fall back to diffusers.

Useful? React with 👍 / 👎.

Comment on lines +182 to +183
if params.batch_count and params.batch_count != 1:
cmd += ["--batch-count", str(int(params.batch_count))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return batch outputs instead of checking only one path

When params.batch_count > 1, this emits --batch-count, but SdCppEngine.generate() still validates and returns only the exact output_path. I checked stable-diffusion.cpp's save_results behavior: for multiple images with an output like x.png, it writes indexed files such as x_0.png and x_1.png rather than x.png, so any Studio batch request routed through this engine will finish successfully in sd-cli and then raise “no image at ...”, discarding the generated batch.

Useful? React with 👍 / 👎.

Comment thread studio/install_sd_cpp_prebuilt.py Outdated
Comment on lines +169 to +173
url = next(a["browser_download_url"] for a in release["assets"] if a["name"] == chosen)
target.mkdir(parents = True, exist_ok = True)
archive = target / chosen
print(f"downloading {chosen} -> {archive}", flush = True)
urllib.request.urlretrieve(url, archive) # noqa: S310 (github release URL)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Download CUDA runtime on Windows

When a Windows user requests --accelerator cuda, the resolver selects the sd-...-bin-win-cuda12-x64.zip asset, but upstream stable-diffusion.cpp publishes the CUDA runtime DLLs as a separate cudart-sd-bin-win-cu12-x64.zip asset; this path downloads only the selected archive. On a fresh Windows machine without CUDA/cuBLAS DLLs already available, the installer will report success but the installed sd-cli.exe cannot start because its runtime DLLs are missing.

Useful? React with 👍 / 👎.

Comment thread studio/install_sd_cpp_prebuilt.py Outdated
Comment on lines +175 to +176
with zipfile.ZipFile(archive) as zf:
zf.extractall(target)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate zip members before extracting

If the downloaded release archive contains an absolute path or .. entry, extractall(target) can write files outside the intended install directory. This helper downloads archives from an external release at install time, and the repo's other prebuilt installers already route zip members through a containment check, so this should use the same safe-extract pattern before writing into the user's filesystem.

Useful? React with 👍 / 👎.

Comment thread studio/install_sd_cpp_prebuilt.py Outdated

try:
install(
install_dir = Path(args.install_dir) if args.install_dir else None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Expand --install-dir before installing

When users pass a shell-style path such as --install-dir ~/.unsloth/stable-diffusion.cpp, Path(args.install_dir) preserves the literal ~, so the installer creates a ~ directory under the current working directory instead of installing where the finder or the user expects. Expanding the path here matches the llama prebuilt installer and avoids a successful install that Studio cannot discover.

Useful? React with 👍 / 👎.

logger.info("sd-cli generate: %s", " ".join(cmd))

t0 = time.time()
proc = subprocess.Popen(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bind sd-cli children to the backend lifetime

For long native generations, this starts sd-cli without the parent-death protection used by the llama backend (utils.process_lifetime.child_popen_kwargs). If the Studio backend process is killed or crashes while sd-cli is denoising, the child can continue running as an orphan and keep consuming CPU/GPU resources until the user finds and kills it manually.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 29, 2026 05:46
…rdening

- install_sd_cpp_prebuilt: download the release archive with urlopen + an explicit
  timeout + copyfileobj (urlretrieve has no timeout and hangs on a stalled socket);
  extract through a per-member containment check (Zip-Slip guard); expanduser the
  --install-dir so a tilde path is not taken literally; and on Windows CUDA also fetch
  the separately-published cudart runtime DLL archive so sd-cli.exe can start.
- sd_cpp_engine: find_sd_cpp_binary honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the
  installer, so a custom-root install is discovered without UNSLOTH_SD_CPP_PATH; start
  sd-cli with the parent-death child_popen_kwargs so it is not orphaned on a backend
  crash; reap the SIGKILLed child (proc.wait) so a cancel/timeout does not leave a zombie.
- tests: Zip-Slip rejection, normal extraction, studio-home discovery.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7be5ec4fdd

ℹ️ 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".

Comment on lines +145 to +148
for stem in (_BINARY_STEM, _LEGACY_STEM):
on_path = shutil.which(stem)
if on_path:
return on_path

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate legacy sd binaries before selecting them

When sd-cli is absent but an unrelated sd command is on PATH (for example the common search-and-replace CLI), this loop returns that binary as the native diffusion engine. On CPU/MPS, select_diffusion_engine() can then route to sd_cpp because is_available() only checks that the file exists, and every generation will invoke the wrong executable with sd.cpp flags instead of falling back to diffusers. Please either restrict the legacy sd name to managed build layouts or version-probe PATH hits before accepting them.

Useful? React with 👍 / 👎.

Comment on lines +125 to +127
home = os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME")
base = Path(home).parent if home else Path.home() / ".unsloth"
return base / "stable-diffusion.cpp"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep custom installs under the resolved Studio root

When UNSLOTH_STUDIO_HOME/STUDIO_HOME points at a custom Studio root, this uses the root's parent, while the existing Studio root helper and llama.cpp custom-mode install/discovery put managed binaries under the resolved Studio root itself. For a custom path like /opt/unsloth/studio, the sd.cpp installer writes /opt/unsloth/stable-diffusion.cpp, outside the Studio-owned tree, which can be unwritable or skipped by the same cleanup/discovery assumptions used elsewhere; derive the base from the shared studio_root() logic and only keep the legacy ~/.unsloth sibling behavior for the legacy root.

Useful? React with 👍 / 👎.

Comment on lines +98 to +100
if not sel: # fall back to a plain avx2 CPU build
sel = [a for a in pool if "avx2" in a.lower()]
return sel[0] if sel else (pool[0] if pool else None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unavailable Windows accelerator builds

When a Windows user explicitly requests an accelerator whose asset is absent from the release, such as --accelerator vulkan on releases that only publish CPU/CUDA/ROCm Windows zips, this fallback first looks for AVX2 and then returns pool[0]. That makes the install report success with a CPU archive instead of telling the user the requested accelerator is unavailable, so generation silently runs much slower than requested; only fall back for auto/cpu, and return no match for missing explicit accelerators.

Useful? React with 👍 / 👎.

verbose = verbose,
extra_args = extra_args,
)
base = dict(os.environ)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scrub native path secrets before spawning sd-cli

When Studio is launched by the desktop shell, os.environ contains UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET; this copies it into the external sd-cli process, unlike the llama-server launches that use child_env_without_native_path_secret(). If a user points SD_CLI_PATH/UNSLOTH_SD_CPP_PATH at a custom or compromised binary, that process receives the lease-signing secret and can mint native path grants, so build base from the scrubbed helper before adding library paths.

Useful? React with 👍 / 👎.

Codex review: when batch_count > 1, stable-diffusion.cpp's save_results() writes
the numbered files <stem>_<idx><suffix> (base_0.png, base_1.png, ...) instead of
the literal --output path. SdCppEngine.generate checked only the literal path, so
a batch generation would exit 0 and then raise 'no image' (or return a stale
file). generate now returns the literal path when present and otherwise falls
back to the numbered siblings; single-image behavior is unchanged.

Test: a fake sd-cli that writes img_0.png/img_1.png (not img.png) is collected
without error.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4d87ff4b22

ℹ️ 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".



def test_generate_raises_when_binary_missing():
e = SdCppEngine(binary = None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stub discovery in the missing-binary test

When this test runs on a machine that already has sd-cli discoverable via the default install root or PATH, SdCppEngine(binary=None) auto-discovers that binary instead of representing a missing binary, so the test can invoke a real executable and fail with a different error. Patch find_sd_cpp_binary() to return None here, as the earlier unavailable test does, to keep this test hermetic.

Useful? React with 👍 / 👎.

_TE_FLAGS_BY_FAMILY: dict[str, tuple[str, ...]] = {
"z-image": ("--llm",),
"flux.2-klein": ("--llm",),
"qwen-image": ("--qwen2vl",),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass Qwen-Image text encoders via --llm

For Qwen-Image/Qwen-Image-2512, sd-cli expects the Qwen2.5-VL text encoder on --llm (the current Unsloth stable-diffusion.cpp tutorial's Qwen command uses --llm models/Qwen2.5-VL..., and sd.cpp logs it as llm_path). Returning --qwen2vl here means any native Qwen-Image wiring based on text_encoder_flags_for_family() builds an argv that current sd-cli will not load as the text encoder, so that family fails instead of generating.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked the pinned build (master-741-484baa4): --qwen2vl is kept as a deprecated alias of --llm, so Qwen-Image loads work as is. Will migrate the mapping to --llm since the alias is deprecated.

if verbose:
cmd += ["-v"]
if extra_args:
cmd += list(extra_args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Disallow output overrides in extra args

When a caller includes --output/-o in extra_args, these args are appended after Studio's --output, so sd-cli writes to the overridden path while SdCppEngine.generate() still validates and returns the original output_path. That makes a successful run report missing output, or worse return an old file at the original path; reject output overrides here or update the path that generate() checks.

Useful? React with 👍 / 👎.

try:
_download(cudart["browser_download_url"], dest)
with zipfile.ZipFile(dest) as zf:
_safe_extractall(zf, target)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Put CUDA DLLs beside sd-cli

For Windows CUDA installs, this extracts the helper archive under the install root, but upstream packs that archive from build\bin\cudart\*; those DLLs therefore land under a cudart subdirectory while runtime_env() only prepends the sd-cli.exe directory to PATH. On a fresh machine without CUDA already installed globally, sd-cli.exe still cannot find cudart64/cublas64, so copy or flatten the helper DLLs into the resolved binary directory after extraction.

Useful? React with 👍 / 👎.

Base automatically changed from diffusion-phase2-memory to image-generation June 30, 2026 22:31
…-phase4-native

# Conflicts:
#	scripts/diffusion_bench.py
#	scripts/diffusion_quality.py
#	studio/backend/core/inference/diffusion.py
#	studio/backend/core/inference/diffusion_device.py
#	studio/backend/core/inference/diffusion_families.py
#	studio/backend/core/inference/diffusion_memory.py
#	studio/backend/core/inference/diffusion_precision.py
#	studio/backend/core/inference/diffusion_speed.py
#	studio/backend/models/inference.py
#	studio/backend/routes/inference.py
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_diffusion_device.py
#	studio/backend/tests/test_diffusion_memory.py
#	studio/backend/tests/test_diffusion_precision.py
#	studio/backend/tests/test_diffusion_speed.py

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48628252bd

ℹ️ 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".

Comment on lines +724 to 728
# callback stops it. unload does NOT take _generate_lock — it must return
# promptly; the running generate keeps its own pipe reference, so freeing
# _state here can't crash it, and its VRAM is reclaimed when it returns
# (within ~one step thanks to the cancel).
if self._active_generate_cancel is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for cancelled generations before releasing GPU ownership

When unload() is invoked by gpu_arbiter._evict_diffusion() during a chat load, this path now only sets the cancel event and returns after clearing _state; the active generate() still holds a local pipeline reference until the next denoise step and its VRAM remains allocated. acquire_for(CHAT) assigns ownership to chat immediately after the evictor returns, so chat can start allocating over the still-running diffusion pipeline and OOM during handoff; keep unload blocking for ownership handoffs or otherwise delay release until the cancelled generation exits.

Useful? React with 👍 / 👎.