Skip to content

Studio diffusion (Phase 1): cross-platform device policy, fp16 guard, lock split, validate-before-evict - #6670

Merged
oobabooga merged 14 commits into
image-generationfrom
diffusion-phase1
Jun 30, 2026
Merged

oobabooga merged 14 commits into
image-generationfrom
diffusion-phase1

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Phase 1 of porting the richer diffusion stack onto the new image-generation backend from #6658. This is a focused, low-risk slice that makes diffusion work across more hardware and fixes two correctness issues in the GPU handoff, while staying small and well tested.

This PR is based on the #6658 branch because it modifies files that PR introduces. Once #6658 lands I will rebase onto main and retarget the base.

What it does

  • New device/dtype policy module (diffusion_device.py) resolving CUDA / ROCm / XPU / MPS / CPU with capability flags. It keeps the NVIDIA capability-based bf16 choice from Studio: add image generation with Unsloth GGUFs #6658 (not is_bf16_supported(), which pre-Ampere cards report true via emulation); ROCm and XPU are isolated; MPS uses bf16 or fp32, never a silent fp16.
  • A per-family fp16_incompatible flag (Z-Image) that promotes a resolved float16 to float32. Z-Image activations overflow float16's finite range and render a black image, so on pre-Ampere CUDA or older macOS the guard keeps output correct.
  • Lock split plus cancellation. A generation now holds only _generate_lock, so status polling, unload, and a new load are never blocked by a long denoise. An eviction or a superseding load preempts a running generation through callback_on_step_end (which sets pipe._interrupt), and a replacement load waits for the cancelled denoise to stop before allocating, so two pipelines never sit in VRAM at once. The cancel signal is a per-generation event registered under the state lock, so a cancel cannot be lost to a racing generation.
  • Validate before the GPU handoff. The image load route validates the request (family detection and local GGUF checks) before evicting the chat model, so an unloadable pick never unloads a working chat session. Missing local paths are rejected up front.

Out of scope (later phases)

GGUF text-encoder quantization, CPU and group offload policies, FP8 layerwise casting, torch.compile, the safetensors diffusion path, LoRA / image-to-image / editing / video, a native CPU and Mac engine, and an image quality-versus-quant harness.

Tests

CPU only, with torch and diffusers stubbed, run from studio/backend:

python -m pytest tests/test_diffusion_device.py tests/test_diffusion_backend.py tests/test_diffusion_routes.py tests/test_gpu_arbiter.py

73 tests pass, covering the device matrix, the fp16 guard and dtype promotion, the lock split and per-generation cancellation (including the lost-cancel and replacement-load races), and validate-before-evict.

Benchmark and regression

scripts/diffusion_bench.py drives the backend on a GPU and records load time, peak VRAM, generation latency, images per second, and PSNR against a saved reference image, with --write-baseline / --compare and thresholds for regression detection. Verified on Z-Image-Turbo (Q4_K_M) on a single B200: it loads in bf16, generates at about 1.88 seconds per 9-step 1024x1024 image, and the before/after comparison is byte-identical (PSNR inf) with no latency or VRAM regression.

danielhanchen and others added 2 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.

@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 standalone GPU benchmark script, refactors device and dtype resolution into a dedicated policy module, adds an fp16-incompatible guard for Z-Image models to prevent black outputs, and splits backend locks to ensure responsive status polling and cancellation. It also adds early validation to prevent evicting the chat model on invalid requests. The review feedback suggests improving path validation to support Windows backslashes and refactoring a test mock to be more hermetic across different hardware configurations.

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 +220 to +221
elif repo_id.startswith(("/", "~", "./", "../")) or local_root.is_absolute():
raise FileNotFoundError(f"Local model path does not exist: {repo_id}")

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

On Windows, local paths can start with backslashes (e.g., ..\\ or .\\). The current prefix check only looks for forward slashes, which means non-existent relative paths using backslashes won't be caught here and will instead fail later during the background load after evicting the chat model. Updating the prefix check to include backslashes and a general dot prefix makes this validation robust and cross-platform.

Suggested change
elif repo_id.startswith(("/", "~", "./", "../")) or local_root.is_absolute():
raise FileNotFoundError(f"Local model path does not exist: {repo_id}")
elif repo_id.startswith(("/", "\\", "~", ".")) or local_root.is_absolute():
raise FileNotFoundError(f"Local model path does not exist: {repo_id}")

Comment on lines +533 to +534
monkeypatch.setattr(torch.cuda, "is_available", lambda: True, raising = False)
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda: (7, 5), raising = False)

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

To make this test completely hermetic and independent of the host's actual hardware, monkeypatch _pick_device_and_dtype directly on DiffusionBackend instead of mocking torch.cuda methods. This ensures the test won't fail on machines where utils.hardware.get_device() returns XPU or MLX (which would bypass the CUDA check).

    monkeypatch.setattr(
        DiffusionBackend,
        "_pick_device_and_dtype",
        lambda self: ("cuda", torch.float16),
    )

@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: 8ef51d744b

ℹ️ 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 +399 to +401
with self._lock:
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()

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 Move load-token check before cancelling generations

When a cancelled/superseded background load eventually reaches load_pipeline (for example after unload() bumps _load_token and a newer model is already serving a generation), it executes this cancellation before the token mismatch check below. That stale worker will set the current generation's cancel event, wait for _generate_lock, and then raise Diffusion load was cancelled, so an unrelated in-flight generation from the current model is aborted. Check _load_token before signalling _active_generate_cancel.

Useful? React with 👍 / 👎.

Comment thread scripts/diffusion_bench.py Outdated

# PSNR vs the stored reference image.
ref_png = Path(baseline.get("accuracy", {}).get("reference_png", ""))
psnr = _psnr(ref_png, args._image_out) if ref_png.exists() else float("nan")

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 Fail when the PSNR reference is missing

If the baseline's reference PNG is absent (or the baseline directory was copied, because _write_baseline stores an absolute reference_png), this assigns NaN and the later not math.isnan(psnr) guard means no accuracy failure is recorded. The benchmark can therefore print PASS while doing no image comparison, defeating the regression guard; fail immediately or resolve reference.png relative to the baseline when the stored path is missing.

Useful? React with 👍 / 👎.

local_root = Path(repo_id).expanduser()
if local_root.exists():
resolve_local_gguf_child(local_root, gguf_filename)
elif repo_id.startswith(("/", "~", "./", "../")) or local_root.is_absolute():

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 Treat Windows relative paths as local before eviction

On Windows, a mistyped local repo like .\models\z-image or ..\z-image is path-shaped but does not match the POSIX-only prefixes here, so validation treats it as a remote repo and lets the route call acquire_for(DIFFUSION) before the background load fails. That still evicts a working chat model for an unloadable local selection; include the Windows .//../ forms (or use pathlib path parsing) in this pre-eviction check.

Useful? React with 👍 / 👎.

Comment on lines +582 to +583
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()

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 ownership until cancelled generation exits

When /images/unload is called during a generation, this only signals cancellation and returns without waiting for _generate_lock; the route then releases the diffusion owner, so a chat load can immediately acquire the GPU while the old diffusion pipeline is still running from its local reference. In that overlap window (or for a pipeline that ignores the callback), two large models can occupy VRAM and OOM despite the arbiter's sole-owner contract; defer release/unload completion until the cancelled denoise has actually exited.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 28, 2026 06:12
…eck before cancel, bench PSNR guard

- validate_load_request now also treats Windows-shaped paths as local (backslash separator,
  .\ ..\ prefixes, drive-absolute), so a mistyped local pick on Windows is rejected up front
  instead of being mistaken for a remote HF repo and evicting a working chat model.
- load_pipeline checks _load_token BEFORE signalling the active generation's cancel. A
  superseded/cancelled worker on its way out was aborting the current model's unrelated
  in-flight generation; it now bails on the token mismatch first (re-checked under the lock).
- diffusion_bench compare resolves reference.png next to the baseline JSON when the stored
  absolute path is gone, and a missing reference is now an accuracy failure instead of a
  silent PASS that did no image comparison.
@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 standalone GPU benchmark and regression harness (diffusion_bench.py) alongside a dedicated device and dtype policy module (diffusion_device.py) for the Studio diffusion backend. Key enhancements include splitting backend locks to keep status and unload operations responsive during active generations, implementing cheap pre-load validation to prevent premature chat model eviction, and adding a float16-to-float32 promotion guard for fp16-incompatible models like Z-Image. Additionally, comprehensive tests were added to verify these changes. The reviewer suggested using a context manager for Image.open in the benchmark script to ensure proper file closure and robust behavior across platforms.

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 scripts/diffusion_bench.py Outdated
Comment on lines +145 to +146
a = np.asarray(Image.open(ref_png).convert("RGB"), dtype = np.float64)
b = np.asarray(Image.open(cand_png).convert("RGB"), dtype = np.float64)

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 Image.open() without a context manager leaves the file descriptor open until the image object is garbage collected. It is safer and more robust (especially on Windows, where open files cannot be deleted or moved) to use a with statement to ensure the files are closed immediately after loading. Additionally, ensure images are unconditionally converted to 'RGB' mode to prevent errors from unsupported modes.

Suggested change
a = np.asarray(Image.open(ref_png).convert("RGB"), dtype = np.float64)
b = np.asarray(Image.open(cand_png).convert("RGB"), dtype = np.float64)
with Image.open(ref_png) as img_a:
a = np.asarray(img_a.convert("RGB"), dtype = np.float64)
with Image.open(cand_png) as img_b:
b = np.asarray(img_b.convert("RGB"), dtype = np.float64)
References
  1. When processing images from arbitrary sources with PIL, unconditionally convert them to 'RGB' mode to prevent errors from unsupported modes like CMYK, P, L, I, or F when saving to formats like PNG.

@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: 3f73da1c05

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

dtype = torch.bfloat16 if bf16_ok else torch.float16,
backend = "xpu",
vendor = "intel",
supports_model_cpu_offload = True,

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 Disable XPU offload unless the target device is passed

When an Intel XPU host requests cpu_offload, this flag makes diffusion.py take the offload branch, but the backend calls pipe.enable_model_cpu_offload() without a device argument, so diffusers uses its CUDA default instead of XPU. On XPU-only machines that turns an otherwise valid load into a failure (or targets the wrong backend); either keep this false for XPU or pass device="xpu" when enabling offload.

Useful? React with 👍 / 👎.

# is left for the background load to resolve.
local_root = Path(repo_id).expanduser()
if local_root.exists():
resolve_local_gguf_child(local_root, gguf_filename)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Reject GGUF directories before taking the GPU

For local repos this validation still accepts any existing child, including a directory named by gguf_filename, because resolve_local_gguf_child() only checks existence. In that case /images/load passes this preflight, proceeds to acquire_for(DIFFUSION) and evicts chat, then the background load fails later when from_single_file receives a directory; since this path is specifically meant to reject unloadable local picks before the handoff, validate that the resolved child is a file here.

Useful? React with 👍 / 👎.

Comment thread scripts/diffusion_bench.py Outdated
Comment on lines +361 to +364
ref_png = Path(baseline.get("accuracy", {}).get("reference_png", ""))
if not ref_png.exists():
ref_png = baseline_path.parent / "reference.png"
psnr = _psnr(ref_png, args._image_out) if ref_png.exists() else float("nan")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Treat empty reference paths as missing

If a baseline JSON lacks accuracy.reference_png (or has it as an empty string), Path("") resolves to the current directory, which usually exists, so the fallback to reference.png is skipped and _psnr() tries to open a directory instead of reporting the intended missing-reference failure. Check for a non-empty file path (or use is_file()) before running the PSNR comparison.

Useful? React with 👍 / 👎.

Comment on lines 596 to 598
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()
self._unload_locked()

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 Keep ownership until the cancelled denoise exits

When the arbiter evicts diffusion for chat while a generation is active, unload() now only signals the cancel event and drops _state; the generate thread still holds the local pipeline reference and its VRAM until the callback stops and the call returns. Since gpu_arbiter.acquire_for(CHAT) proceeds as soon as this method returns, chat can start allocating while the old diffusion pipeline is still resident, breaking the single-owner VRAM invariant and causing handoff OOMs. The eviction path needs to wait for _generate_lock (or otherwise keep ownership) before allowing another owner to allocate.

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 standalone GPU benchmark and regression harness (diffusion_bench.py) and refactors the Studio diffusion backend's device/dtype resolution, locking, and validation mechanisms. Key changes include centralizing device policy in a new diffusion_device.py module, promoting float16 to float32 for fp16-incompatible models (like Z-Image) to prevent black images, splitting locks to keep status and unload operations responsive during generation, and adding pre-GPU validation to avoid unnecessary chat model evictions. Feedback on these changes suggests using a context manager for Image.open in the benchmark script to avoid resource leaks, and safely handling None values for torch in _cpu_target to prevent potential AttributeError crashes.

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 scripts/diffusion_bench.py Outdated
Comment on lines +145 to +146
a = np.asarray(Image.open(ref_png).convert("RGB"), dtype = np.float64)
b = np.asarray(Image.open(cand_png).convert("RGB"), dtype = np.float64)

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 Image.open() without a context manager can leave file descriptors open, potentially leading to resource leaks. It is safer to use a with statement to ensure the image files are properly closed after loading. Additionally, unconditionally convert the images to 'RGB' mode to prevent errors from unsupported modes when processing images from arbitrary sources.

Suggested change
a = np.asarray(Image.open(ref_png).convert("RGB"), dtype = np.float64)
b = np.asarray(Image.open(cand_png).convert("RGB"), dtype = np.float64)
with Image.open(ref_png) as img_a:
a = np.asarray(img_a.convert("RGB"), dtype = np.float64)
with Image.open(cand_png) as img_b:
b = np.asarray(img_b.convert("RGB"), dtype = np.float64)
References
  1. When processing images from arbitrary sources with PIL, unconditionally convert them to 'RGB' mode to prevent errors from unsupported modes like CMYK, P, L, I, or F when saving to formats like PNG.

Comment on lines +240 to +242
def _cpu_target(torch: Any, dtype: Any = None) -> DiffusionDeviceTarget:
if dtype is None:
dtype = torch.float32

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 torch is passed as None (which occurs in diffusion_device_target_from_torch_device on line 144) and dtype is also None, accessing torch.float32 will raise an AttributeError. Lazily importing torch when it is None prevents this potential crash.

def _cpu_target(torch: Any, dtype: Any = None) -> DiffusionDeviceTarget:
    if dtype is None:
        if torch is None:
            import torch as torch_mod
            torch = torch_mod
        dtype = torch.float32

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 3f73da1c05

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

…er, recipe

Backend:
- diffusion._estimate_download_bytes: skip the Hub size lookup for a LOCAL gguf path so
  it does not raise and skip the base-repo metadata, which left the companion VAE/text
  encoders out of the cancellable prefetch (they downloaded under the load lock).
- image_gallery.list_images: page over readable records, not raw files, so a foreign or
  corrupt PNG in the window cannot drop valid images after it or make has_more wrong.
- routes/models._DIFFUSION_GGUF_ARCHS: restrict the Images-picker allow-list to the
  families the backend can assemble (flux.1 / flux.2-klein / qwen-image / z-image); SD,
  SDXL, PixArt, Lumina2, AuraFlow, Wan, HunyuanVideo would pass the filter then 400.
- recipe: persist batch_size alongside batch_index (GalleryImage + persist) so restoring
  a batched image can replay the batch it came from.
- scripts/diffusion_bench: open PNGs in a context manager (no leaked file descriptors).

Frontend:
- images-page: stop the multi-run generation loop when the page unmounts (isMounted ref),
  so navigating away does not keep issuing GPU generations.
- images-page: load a direct single-file local .gguf pick (parent dir + basename) instead
  of silently doing nothing; restore the saved batch_size on recipe restore.

Tests: gallery foreign-PNG-in-window paging.

Note: GGUF general.architecture family inference (so a renamed local GGUF loads without
family_override) is deferred; it needs an arch->family map threaded through the callers.

@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

fam = detect_family(repo_id, family_override)

P2 Badge Infer local GGUF families without relying on the folder name

For local GGUFs surfaced by the new architecture-based picker, the directory can be arbitrary (for example /models/downloads) while only the filename/header says z-image; this validation scans only repo_id, and the Images page calls load with dir plus gguf_filename and no family_override, so those valid local picks fail with a 400 before loading. Include gguf_filename or the local GGUF metadata in family detection for local paths.

ℹ️ 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 +3068 to +3071
# diffusion_families._FAMILIES). Other on-device diffusion archs (SD1/2/3,
# SDXL, PixArt, Lumina2, AuraFlow, Wan, HunyuanVideo, ...) would pass this
# Images-picker filter and then fail validate_load with a 400, so they are
# deliberately excluded until the backend supports them.

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 unsupported diffusion GGUFs out of chat

When a cached/local GGUF has one of the unsupported diffusion architectures named here (for example sdxl or pixart), removing it from _DIFFUSION_GGUF_ARCHS makes _arch_to_task() fall through to text-generation; passesTaskGate(..., filter undefined) then allows that image checkpoint in the chat picker and hides it from Images, even though chat cannot load it. Return an unsupported/unknown image task for known-but-unsupported diffusion archs instead of treating them as text models.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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

fam = detect_family(repo_id, family_override)

P2 Badge Include GGUF filename when inferring local families

For direct local .gguf selections, the new frontend splits the full file path into model_path = parent directory and gguf_filename = basename, but validation still calls detect_family() on only the parent. When users keep supported files in a generic folder such as /models/z-image-turbo-Q4_K_M.gguf or ~/Downloads/qwen-image.gguf, the family keyword is present only in gguf_filename, so the load 400s with “Could not infer a diffusion family” even though the selected file is supported. Consider detecting from the combined local path/filename or passing a family override for this direct-file path.

ℹ️ 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 600 to 602
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()
self._unload_locked()

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 Wait for active denoise before GPU handoff

When a user switches back to chat or unloads while an image is still generating, this only signals cancellation and drops _state; the generation thread still holds a local reference to the pipeline until the current step (or the whole denoise for pipelines without the callback) finishes. The unload route and gpu_arbiter._evict_diffusion() release diffusion ownership immediately after this returns, so chat can start allocating VRAM while the old diffusion pipeline is still executing, defeating the single-GPU handoff and risking OOM. The replacement-load path already waits on _generate_lock; unload used for arbiter handoff needs the same safety or a deferred release.

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.

Confirmed this is still the case: unload only signals cancel and returns before the denoise thread frees VRAM. Planning a bounded wait on the generate lock in the arbiter eviction path.

Comment on lines +3067 to +3071
# ONLY the families the diffusion backend can actually assemble (see
# diffusion_families._FAMILIES). Other on-device diffusion archs (SD1/2/3,
# SDXL, PixArt, Lumina2, AuraFlow, Wan, HunyuanVideo, ...) would pass this
# Images-picker filter and then fail validate_load with a 400, so they are
# deliberately excluded until the backend supports them.

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 unsupported diffusion GGUFs out of chat

By removing SD/SDXL/PixArt/Wan/etc. from the architecture set, _arch_to_task() now classifies those still-image/video GGUFs as text-generation instead of an image task. The chat picker only drops on-device rows whose reported task is one of IMAGE_GEN_TASKS, so a user with one of these cached/local diffusion GGUFs will now see it as a loadable chat model and hit the llama.cpp unsupported-architecture failure this classifier previously avoided. Consider separating “is a diffusion GGUF” from “is supported by the Images backend” rather than mapping unsupported diffusion archs to text generation.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 29, 2026 10:31
…ad drain, chat picker

Addresses Codex review on the pushed Phase 1 fixes:

- detect_family for a direct local .gguf pick: the frontend splits such a pick
  into (parent dir, basename), so the family keyword can live only in the
  filename (e.g. /models/z-image-turbo-Q4_K_M.gguf). validate_load_request and
  _run_load now fall back to scanning the combined path+filename when the parent
  directory alone is undetectable. Remote org/name picks and explicit overrides
  are unchanged; edit-checkpoint filenames are still rejected.

- unload() now signals the in-flight denoise then waits on _generate_lock for it
  to exit before freeing _state, mirroring the replacement-load path. The GPU
  arbiter hands the card to chat the instant unload returns, so the old pipeline
  must already be gone; the previous prompt-return left a window where chat began
  allocating while the old pipeline was still resident (dual-allocation OOM).
  status()/generate_progress() still read _state lock-free and do not block.

- _arch_to_task: known diffusion archs the backend cannot assemble (sd1/sd3/sdxl/
  aura/hidream/cosmos/ltxv/hyvid/wan/lumina2, kept in sync with
  LlamaCppBackend._DIFFUSION_ARCHES) were classified as text-generation, so a
  cached such GGUF showed in the chat picker and then died with unknown model
  architecture in llama.cpp. They now get a dedicated non-loadable diffusion task
  that the chat picker hides and the Images picker (filtered to IMAGE_GEN_TASKS)
  also excludes, since they would 400 in validate_load.

Tests: family-from-filename + edit rejection; unload drains the live denoise
before freeing state; arch-to-task hides every llama.cpp diffusion arch from chat
(with a drift guard). Frontend tsc clean.

@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: d0e33492e9

ℹ️ 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 +203 to +204
if fam is None and gguf_filename and not family_override:
fam = detect_family(f"{repo_id}/{gguf_filename}", family_override)

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 local GGUF families from metadata

When a loadable local/LM Studio image GGUF has a generic directory and filename (for example /models/model.gguf whose general.architecture is z_image), the Images picker can still show it because the local-model route classifies GGUFs by reading their architecture metadata, but this load path only searches the path string and no family_override is sent for direct local picks. Those valid local files therefore fail validation with “Could not infer a diffusion family”; resolve the family from the local GGUF architecture (or pass an override) instead of relying only on name substrings.

Useful? React with 👍 / 👎.

# Conflicts:
#	studio/backend/core/inference/diffusion.py
#	studio/backend/routes/inference.py
#	studio/backend/tests/test_cached_gguf_routes.py
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_diffusion_routes.py
#	studio/frontend/src/features/images/images-page.tsx
@oobabooga
oobabooga changed the base branch from pr6658-image-generation to image-generation June 30, 2026 19:05
@oobabooga

Copy link
Copy Markdown
Member
  • Merged the new image-generation base into the branch, resolving conflicts in the diffusion backend, load route, images page, and tests. The resolution keeps the base's training-VRAM guard along with Phase 1's validate-before-evict and the lock split.
  • Removed dead code from the Phase 1 refactor: validate_load, two unread device-target helpers, a redundant device-resolution layer, an unused param, and a dead bench helper.
  • Reject a local GGUF path that resolves to a directory before the GPU handoff, so it no longer evicts the chat model and then fails on load.
  • Benchmark no longer crashes when the reference-image path is empty or a directory: it uses is_file, so it falls back to the sibling reference or fails cleanly.
  • Device tests pin CUDA so they pass regardless of the host GPU.
  • Images page now stays mounted across tab switches like chat, so a long batch keeps generating when you switch tabs instead of stopping. Its model selector, recipe popover, and aspect dropdown close off-tab so they don't float over another tab, and model status re-syncs on return.

@oobabooga
oobabooga merged commit ecf0287 into image-generation Jun 30, 2026
43 of 44 checks passed
@oobabooga
oobabooga deleted the diffusion-phase1 branch June 30, 2026 19:33
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: ecf028780d

ℹ️ 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 +429 to +430
if self._active_generate_cancel is not None:
self._active_generate_cancel.set()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Guard pending generation cancellation before waiting

When a replacement load races with a generation that has taken _generate_lock but has not yet assigned _active_generate_cancel, this check observes None and then waits on _generate_lock without ever signalling that generation's cancel event. In that narrow startup window, a load/eject/chat handoff can block for the full denoise instead of the intended one-step interrupt; the unload path has the same pattern, so consider recording a pending cancel or registering the event before the wait can miss it.

Useful? React with 👍 / 👎.

Comment on lines +880 to +881
open={active && selectorOpen}
onOpenChange={(o) => setSelectorOpen(active && o)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Reset hidden popover state when leaving Images

If the model selector is open and the user navigates away from /images, active && selectorOpen hides the body-ported popover but leaves selectorOpen true, so returning to /images immediately reopens it. The same controlled-state pattern is used for the aspect select and recipe popover; clear these open states when active becomes false so hidden keep-alive UI does not reappear unexpectedly on the next visit.

Useful? React with 👍 / 👎.

Comment on lines +3105 to +3110
_UNSUPPORTED_DIFFUSION_GGUF_ARCHS = frozenset(
{
"sd1",
"sd2",
"sd3",
"sdxl",
"stable_diffusion",
"lumina2",
"qwen_image",
"qwenimage",
"auraflow",
"pixart",
"hunyuan_video",
"aura",

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 all unsupported diffusion archs out of chat

This new unsupported-arch set omits several diffusion GGUF architectures that the previous classifier treated as image models, including sd2, stable_diffusion, pixart, auraflow, and hunyuan_video (the adjacent comment still calls out PixArt/AuraFlow/HunyuanVideo). Those cached/local files now fall through to text-generation, so they reappear in the chat picker and can be sent to llama.cpp even though they are diffusion checkpoints; include the omitted arch values in the unsupported task set so they stay hidden from both pickers until supported.

Useful? React with 👍 / 👎.

Comment on lines +752 to +755
const d = defaultsFor(id);
setSteps(d.steps);
setGuidance(d.guidance);
void handleLoad(dir, filename);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Clear stale quant label for direct GGUF picks

When switching from a curated quant to a direct single-file local .gguf, this new path starts the load but never updates quant, so activeGgufVariant keeps showing the previously loaded quant in the selector even after the local file loads. In the direct-file branch, clear it or set it to the selected filename so the model pill does not display stale variant information.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants