Repository navigation
Studio: sd.cpp on Macs, CPU backend on a paravirtual GPU and no direct conv on Metal - #13369
Conversation
…tchdog on SD1.5, 5.5x slower VAE)
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3c13152c88
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _runs_on_apple_metal(): | ||
| return ["--diffusion-fa"] |
There was a problem hiding this comment.
Keep direct convolution for forced CPU runs
On a physical ARM Mac this assumes that the process always executes on Metal, but _restart_server_on_cpu() rebuilds the server with extra_args=["--backend", "cpu"] while retaining the same native speed mode. Because speed flags are computed before those backend overrides are considered, the recovered CPU process loses --diffusion-conv-direct, even though that is the CPU optimization this profile previously enabled; explicit CPU overrides on Apple Silicon have the same regression. Base this decision on the effective command backend rather than only the host platform.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 23621f9. native_speed_flags now takes the command's other flags and keeps --diffusion-conv-direct whenever they select a bare --backend cpu, so the CPU-backend restart and an explicit --backend cpu on Apple Silicon keep direct conv. The sd-server builder (offload, placement and extra_args) and SdCppEngine.generate both pass them through; Metal runs still drop it. Covered by test_native_speed_keeps_direct_conv_on_a_forced_cpu_backend and test_engine_generate_keeps_direct_conv_on_a_forced_cpu_backend.
| if metal_is_paravirtual(): | ||
| return list(CPU_BACKEND_FLAGS) |
There was a problem hiding this comment.
Propagate the forced CPU device into backend state
When this branch forces a paravirtual Mac onto --backend cpu, SdCppDiffusionBackend._run_load() still stores the previously resolved mps device because the placement change happens only while constructing argv. Consequently the load log and public status() response report device: "mps" even though all computation is on CPU, and CPU-side failures can also enter _restart_server_on_cpu() because its state.device == "cpu" guard is false. Record the effective forced device in the backend state rather than hiding it solely in the command builder.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 23621f9. The paravirtual placement only lived in the argv builders, so _run_load kept the resolved mps device: the load log and status() reported mps, offload flags were derived as for a GPU, and the state.device == "cpu" guard in _restart_server_on_cpu_backend could not stop a pointless CPU restart. _run_load now records cpu when the resolved device is mps and the Metal device is paravirtual, so state, status, offload and the restart guard match what actually runs. Physical Apple Silicon still records mps. Covered by test_paravirtual_mac_load_records_the_cpu_device.
| def metal_placement_flags(offload: Sequence[str]) -> list[str]: | ||
| """``metal_text_encoder_flags()`` minus what ``offload`` already says. | ||
|
|
||
| ``--backend cpu`` is a flag pair: per-item filtering would leave a dangling ``cpu``, so an explicit pin drops it.""" | ||
| flags = metal_text_encoder_flags() | ||
| if flags == list(CPU_BACKEND_FLAGS): | ||
| return [] if "--backend" in offload else flags |
There was a problem hiding this comment.
Apply paravirtual CPU placement to upscale commands
metal_placement_flags() is added to the image, video, and server builders, but build_sd_cpp_upscale_command() remains unchanged and SdCppEngine.upscale() supplies no backend override by default. Thus an ESRGAN upscale on a paravirtual Mac still launches sd-cli on the default paravirtual Metal backend, bypassing the CPU safety policy introduced here and leaving that mode exposed to the same unsupported/fallback behavior. Apply the placement policy to the upscale builder as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 23621f9. build_sd_cpp_upscale_command now adds --backend cpu when the Metal device is paravirtual, unless the caller already passed a --backend in extra_args (sd.cpp concatenates repeated backend specs, so a second one would change the caller's choice). It does not add --clip-on-cpu, since upscale has no text encoder. Covered by test_upscale_on_paravirtual_metal_runs_on_the_cpu_backend.
…PU backend, CPU placement for upscale
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23621f9b4e
ℹ️ 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".
| offload = list(offload or []) | ||
| if offload: | ||
| cmd += offload | ||
| cmd += [f for f in metal_text_encoder_flags() if f not in offload] | ||
| cmd += metal_placement_flags(offload) |
There was a problem hiding this comment.
Record paravirtual H3 video runs as CPU
When MiniMax-H3 is loaded on a paravirtual Mac, this forces the actual video command onto CPU, but the H3 loader in video.py still retains native_device = "mps". It consequently commits an MPS device to status, selects the GPU-oriented auto/offload policy at lines 3778-3801, and skips the GPU-arbiter release guarded by native_device == "cpu" at lines 3955-3961. Thus a CPU-only video runtime can continue holding the VIDEO GPU claim and evict or block unrelated workloads; propagate the effective CPU placement into the H3 load state before deriving policy and resource accounting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f3add34. The H3 loader kept native_device as mps on a paravirtual Mac, so it chose the GPU offload policy, committed mps to status and skipped the VIDEO release that is guarded on a CPU device. _run_load_h3_native now sets native_device to cpu right where it is resolved when sd.cpp will run a paravirtual Metal GPU on the CPU backend, so the offload policy, the committed state and the VIDEO claim release all follow the actual placement. Covered by test_h3_on_a_paravirtual_mac_commits_cpu_and_drops_the_video_claim.
| else resolve_diffusion_device_target().device | ||
| ) | ||
| # A paravirtual Mac GPU runs sd.cpp on the CPU backend (see metal_text_encoder_flags), so record that. | ||
| if device == "mps" and sd_cpp_args_mod.metal_is_paravirtual(): |
There was a problem hiding this comment.
Release the image GPU claim after forcing CPU
When native image rendering is enabled on MPS with UNSLOTH_DIFFUSION_SD_CPP_MPS=1, /images/load computes needs_gpu = device != "cpu" and acquires the DIFFUSION GPU claim before this worker runs (routes/inference.py lines 46502-46700). Changing only the committed state here does not revisit that decision, so on a paravirtual Mac the command runs on CPU and status says CPU while the load has already evicted the previous GPU owner and continues holding the DIFFUSION claim, potentially blocking or evicting chat/video workloads. Propagate the effective placement before route arbitration or explicitly release the claim when this forced-CPU load commits.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f3add34. The route had already taken the DIFFUSION claim from the resolved mps device before the worker ran. Rather than release it afterwards, the image load route now treats this case like the existing off-torch native case: once the activated engine is known to be sd.cpp and the device is a paravirtual mps GPU, needs_gpu is False, so the load goes through the owner-guarded release path without acquiring or evicting anything. Loads that land on diffusers are unchanged. The check is a shared forces_cpu_backend helper, which the image backend's committed state and the H3 video loader now use too.
|
|
||
| if sys.platform != "darwin" or platform.machine().lower() not in ("arm64", "aarch64"): | ||
| return False | ||
| return not metal_is_paravirtual() |
There was a problem hiding this comment.
Respect explicit Metal pins when choosing convolution flags
metal_placement_flags() explicitly allows an offload --backend pin to override the paravirtual CPU placement, and the added test demonstrates this with diffusion=MTL0,te=cpu,vae=MTL0. On that supported path the graph runs on Metal, but this unconditional paravirtual result makes native_speed_flags("default"/"max") retain --diffusion-conv-direct, reintroducing the Metal watchdog failure this change is intended to prevent. Determine whether Metal is effective from backend_args when an explicit pin suppresses the CPU guard rather than assuming every paravirtual command runs on CPU.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f3add34. On darwin arm64 the Metal decision now comes from the command's own --backend values when there are any: the run counts as Metal unless every spec maps all modules to cpu, and with no pin it falls back to not paravirtual as before. So an explicit diffusion=MTL0,te=cpu,vae=MTL0 pin on a paravirtual GPU drops --diffusion-conv-direct, while the paravirtual CPU placement and the CPU restart keep it. Covered by test_native_speed_honours_an_explicit_metal_pin_on_a_paravirtual_gpu.
… image GPU claim; honour explicit Metal pins for direct conv
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f3add34988
ℹ️ 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".
| else: | ||
| _guard_diffusion_load_against_training() | ||
| # sd.cpp runs a paravirtual Mac GPU on the CPU backend, so it takes no DIFFUSION claim. | ||
| if activated == ENGINE_SD_CPP and forces_cpu_backend(device): |
There was a problem hiding this comment.
Move the paravirtual probe off the event loop
On the first native image load on macOS, this synchronous call can execute metal_is_paravirtual(), which imports the llama backend and may run sysctl and system_profiler subprocesses with 30-second timeouts. Because load_diffusion_model_gated is async and this call is not wrapped in asyncio.to_thread, the probe can block every request handled by the event loop until it completes; resolve the forced-CPU decision off-thread as the surrounding hardware probes do.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1a131bb. The forced-CPU check ran synchronously in the async load handler, and its first call can run the paravirtual probe (sysctl / system_profiler). It now runs through asyncio.to_thread like the surrounding hardware probes, and only when sd.cpp is the activated engine and the resolved device is mps, so other hosts skip the extra hop.
| if sd_cpp_args_mod.forces_cpu_backend(native_device): | ||
| native_device = "cpu" |
There was a problem hiding this comment.
Decide H3 CPU placement before acquiring the GPU
For a paravirtual Mac H3 load, routes/video.py still sees the resolved device as mps and calls acquire_for_request(VIDEO, ...) before this worker rewrites the committed device to CPU. That acquisition can evict an active chat/image model and holds the VIDEO claim throughout the binary/model download even though the eventual runtime never uses the GPU. The new post-commit release_if fixes the previously reported stale ownership, but the route-level acquisition and eviction still occur; apply the forced-CPU decision before video arbitration, as the image route now does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1a131bb. The video load route now applies the same forced-CPU decision as the image route before arbitration: for an H3 native load on an mps device that sd.cpp will run on the CPU backend, the device is treated as CPU, so the route releases instead of acquiring and nothing is evicted. The probe runs off the event loop, and the worker-side release stays as a backstop.
| if sys.platform != "darwin" or platform.machine().lower() not in ("arm64", "aarch64"): | ||
| return False |
There was a problem hiding this comment.
Detect Metal independently of the Python architecture
On macOS processes that report x86_64—notably an Apple Silicon installation running under Rosetta—this returns before examining even an explicit --backend diffusion=MTL0 pin. The native speed profile therefore restores --diffusion-conv-direct while sd.cpp is actually executing on the same Apple Metal GPU for which this change documents watchdog timeouts. Base the decision on the effective backend/device rather than platform.machine(), or account for translated processes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1a131bb. On macOS an explicit --backend value now decides first, whatever the Python architecture, so a Metal pin always drops --diffusion-conv-direct. Without a pin, the Apple Silicon check uses a cached hw.optional.arm64 sysctl read (the same signal the installer uses for Rosetta) instead of platform.machine(), so an x86_64 Python under Rosetta is treated as Metal while a real Intel Mac keeps direct conv. Covered by test_metal_detection_does_not_trust_the_python_architecture.
…t before the VIDEO claim, Metal detection under Rosetta
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1a131bb2d1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if is_h3_native(fam, kind) and device == "mps" and await asyncio.to_thread(forces_cpu_backend, device): | ||
| device = "cpu" |
There was a problem hiding this comment.
Keep the VIDEO claim until the old MPS model is torn down
On a paravirtual Mac with a conventional MPS video model already resident, changing device to CPU sends this request through the release(VIDEO) branch before begin_load(). The fresh evidence in the revised path is that VideoBackend.begin_load() only schedules a background worker while preserving _state, and _run_load_h3_native() does not call _teardown_state_locked() until after the H3 assets have been downloaded. During that potentially long load, a chat or image acquisition therefore sees no VIDEO owner and cannot evict the still-resident MPS model, allowing overlapping GPU allocations; if the H3 load fails, the old model remains permanently ownerless. Avoid acquiring a new claim for the CPU load, but retain the existing VIDEO claim until the old state is actually torn down.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 15b8bca. Releasing VIDEO up front left a resident MPS model without an owner until the worker tore it down after the download, and for good if the H3 load failed. The forced-CPU H3 branch now neither acquires nor releases VIDEO; it only begins the load. An existing claim stays with the old model until the worker's teardown, after which the existing post-commit release_if(VIDEO, ...) drops it for the CPU runtime, and on failure the old model keeps its claim. The image route does not have the same gap: switching to the sd.cpp engine unloads the previous diffusers engine synchronously before the release.
| parts = [p for p in str(spec).split(",") if p.strip()] | ||
| return bool(parts) and all(p.split("=")[-1].strip().lower() == "cpu" for p in parts) |
There was a problem hiding this comment.
Resolve partial backend specs before enabling direct convolution
On a physical Apple Silicon Mac, a valid partial override such as --backend te=cpu or --backend vae=cpu makes this predicate return true because every module mentioned in the string is assigned to CPU. The fresh evidence after the earlier Metal-pin fix is this new whole-spec predicate: stable-diffusion.cpp leaves unassigned modules to auto-fit, which selects a GPU for the diffusion module, so _runs_on_apple_metal() incorrectly enables --diffusion-conv-direct and restores the documented Metal watchdog failure. Resolve the effective diffusion/default assignment rather than treating any all-CPU subset as a CPU-only graph. The upstream backend documentation confirms that modules without a runtime assignment are chosen by auto-fit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 15b8bca. The check now resolves the diffusion module's own backend from the --backend values (an explicit diffusion= entry wins over a bare default, as in sd.cpp). When neither is present the module is on auto-fit and the host decides (Apple Silicon and not paravirtual). So te=cpu or vae=cpu alone keeps the denoiser on Metal and drops --diffusion-conv-direct, while diffusion=cpu or a bare cpu keeps it. Covered by test_partial_backend_specs_leave_the_diffusion_model_on_metal.
…e the diffusion backend from partial specs
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…OS legs (#17107) ## Summary Two test files on main assume a Linux host. Any PR whose cross-platform run selects them goes red on the leg that is not Linux, whatever the PR changed. Two current examples: ``` windows-latest (#17067) FAILED test_diffusion_comfy_block.py::test_a_many_layer_nvfp4_fallback_load_that_fits_is_not_refused FAILED test_diffusion_comfy_block.py::test_block_dequant_is_checked_for_its_peak_intermediates[nvfp4] ... and four more, all: FileNotFoundError: [Errno 2] No such file or directory: '/proc/self/status' macos-15 (#17098) FAILED test_sd_cpp_args.py::test_native_speed_flags assert ['--diffusion-fa'] == ['--diffusion-fa', '--diffusion-conv-direct'] FAILED test_sd_cpp_args.py::test_minimax_h3_video_command_has_all_joint_av_components assert ['--offload-to-cpu', '--clip-on-cpu'] == ['--diffusion-fa', '--offload-to-cpu'] ``` In both files the product code is right and the tests are wrong. - **`test_diffusion_comfy_block.py`.** The six memory-peak tests already skip with `needs /proc/self/status RssAnon` when `_rss_anon_bytes()` returns `None`. But the helper opens `/proc/self/status` unguarded. Off Linux it raises `FileNotFoundError` instead of returning `None`, so the tests error out instead of skipping. - **`test_sd_cpp_args.py`.** On Apple Metal, sd.cpp deliberately drops `--diffusion-conv-direct` and adds `--clip-on-cpu` (#13369). Most tests in the file pin `sys.platform` before they build a command. These two do not, so on a Mac runner they get the Metal command and compare it against the Linux one. ## Change Tests only: - `_rss_anon_bytes()` returns `None` when `/proc/self/status` cannot be opened, so the existing skips fire on Windows and macOS. On Linux nothing changes. - The file's existing autouse fixture in `test_sd_cpp_args.py`, which already pins the host probes, also pins `sys.platform` to `linux`. Every test there now builds the same command on any host unless it sets the platform itself, as the Metal tests already do. That covers the two tests above and any later one that forgets the pin. ## Testing | | result | |---|---| | `test_sd_cpp_args.py`, `test_sd_cpp_backend.py`, `test_diffusion_comfy_block.py` on Linux, this branch | 345 passed, 5 skipped | | main, Windows and macOS legs of #17067 and #17098 | the failures above | | this branch, `test_diffusion_comfy_block.py` + `test_sd_cpp_args.py` on ubuntu-latest | 156 passed, 5 skipped | | this branch, same files on macos-15 | 150 passed, 11 skipped (the six RssAnon tests skip) | | this branch, same files on windows-latest | 150 passed, 11 skipped (the six RssAnon tests skip) |
Problem
Two problems in how Studio launches sd.cpp on a Mac, measured on GitHub
macos-15runners (Apple M1 virtual GPU) with the macOS arm64 sd.cpp build:--diffusion-fa --diffusion-conv-direct. Direct conv was measured as a win on the CPU backend, but ggml-metal's direct CONV_2D kernel is far slower than its im2col + matmul path. An SD1.5 512 px UNet with it exceeded the GPU watchdog on every run (kIOGPUCommandBufferCallbackErrorTimeout, 3/3 generations failed), and the VAE equivalent made decode 5.5x slower. Flash attention on its own is the big win there.MTLGPUFamilyApple5with no simdgroup or bfloat support. ggml-metal then runs most ops on the CPU, and the bundled ggml crashes: an in-place op stays on Metal while its source was computed on the CPU (ggml_metal_buffer_get_id: ... buffer is nil, then a segfault, 3/3 runs for SD-Turbo), and BF16 weights abort (pre-allocated tensor ... cannot run the operation, Z-Image-Turbo). The segfault carries no abort signature, so the existing CPU-backend restart never fires. Even with the crash fixed in ggml, that GPU is slower than the VM's own CPU because of the fallbacks.The darwin
--clip-on-cpupin and the CPU-backend restart were both added for aborts seen on these runners, i.e. on the paravirtual GPU.Change
studio/backend/core/inference/sd_cpp_args.py:metal_is_paravirtual(): cached, darwin-only wrapper around the existingllama_cpp._metal_device_is_paravirtualprobe (MLX device name,hw.model, SPDisplaysDataType; honoursUNSLOTH_ALLOW_PARAVIRTUAL_METAL=1). Imported lazily, so argv construction stays free of subprocesses off darwin.metal_text_encoder_flags()returns--backend cpuon a paravirtual GPU, else the existing--clip-on-cpurule. The three command builders now go throughmetal_placement_flags(offload), which treats--backend cpuas one flag pair (an explicit--backendpin in the offload flags wins, so no danglingcpuargument).native_speed_flags()keeps only--diffusion-fawhen sd.cpp runs on Apple Metal (darwin arm64, not paravirtual). Intel Macs (CPU-only build), paravirtual Macs (now on the CPU backend) and every other platform keep--diffusion-conv-direct.The router is unchanged: GGUF diffusion on a Mac still goes to diffusers on MPS unless
UNSLOTH_DIFFUSION_SD_CPP_MPS=1.Results
GitHub
macos-15, sd.cpp built like the release macOS arm64 leg, Metal features the VM GPU executes correctly but does not advertise turned on with a CI-only env var (so the runs behave like a physical M1), 3 interleaved repeats, one freshsd-cliper run:--diffusion-fa(this PR on Metal)--diffusion-fa --diffusion-conv-direct(main)--diffusion-fa --vae-conv-directZ-Image-Turbo Q2_K at 256 px, 4 steps:
--diffusion-faalone 48.3 s sampling vs 46.9 s with direct conv (no change from dropping it).Paravirtual GPU as the runner exposes it (no forcing), SD-Turbo f16 512 px, 2 steps: Metal 0/3 (segfault) with the sd.cpp build Studio installs today;
--backend cpu3/3, 61.8 s per image.Tests
studio/backend/tests/test_sd_cpp_args.py:test_paravirtual_metal_runs_the_whole_graph_on_the_cpu_backend: VM gets exactly one--backend cpuand no--clip-on-cpuin the server and CLI argv, also under themodeloffload policy; an explicit--backendpin wins; nothing changes off darwin.test_paravirtual_probe_is_darwin_only_and_survives_a_missing_probe.test_native_speed_on_apple_metal_drops_direct_conv: default and max on Apple Metal give--diffusion-faonly, and the server argv has no--diffusion-conv-direct; paravirtual and Intel Macs keep it.The new tests fail on main (missing
metal_is_paravirtual/ both flags on darwin) and pass here.test_sd_cpp_args.py,test_sd_cpp_engine.py,test_sd_cpp_backend.py,test_sd_cpp_cpu_defaults.py,test_sd_cpp_h3_matrix.py,test_sd_cpp_rocm_vulkan_fallback.py,test_diffusion_memory.py,test_diffusion_engine_router.py: all pass on Linux.Not covered
--clip-on-cpupin is left as is. On the runner the text encoder on Metal ran correctly (Z-Image Qwen3-4B, Qwen-Image-2.1 Qwen3-VL-8B) and keeping it on the CPU cost about 20 s of sampling through memory pressure, but the sd.cpp build Studio pins still has the in-place scheduler bug, so a CPU fallback inside the encoder could segfault. Revisit once the pinned build carries that fix.