Repository navigation
Studio: int8 ConvRot Qwen-Image-2.1 text encoder on Apple Silicon, and release text encoders during denoise on unified memory - #13026
Conversation
…on, and release text encoders during denoise on unified memory
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 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 |
|
Codex Review: Didn't find any major issues. 🚀 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". |
…apacity fix for its pre-download check (#14379) Refs #14267 On Apple Silicon and other unified-memory devices, Studio refuses a diffusion load whose weights it estimates will not fit. The only way past that refusal was the server env var `UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1`, which a Desktop install launched from Finder or the Dock cannot set. This PR adds a per-load override and a persistent setting, with a confirmation step. It also fixes one real sizing bug found while auditing the reported numbers. ## Where the reported numbers come from The refusal in #14267 reads "needs about 56 GB ... only about 51 GB is usable (after reserving room for the operating system)". It has no "currently free" clause, so it comes from the pre-download verdict (Hub metadata, judged at capacity), not the in-load check. The numbers match the bf16 `Qwen/Qwen-Image` pipeline (`Qwen-Image-2512` has the same sizes) on a 64 GiB unified pool: | Term | MiB | | --- | --- | | transformer (40,861,227,138 bytes) | 38,968 | | text encoder, Qwen2.5-VL-7B (16,584,475,660 bytes) | 15,816 | | VAE | 242 | | flat base overhead | 2,048 | | **required** | **57,074 (56 GB)** | | 64 GiB minus the 20% unified reserve | **52,429 (51 GB)** | ### What is not over-counted - **Weights are counted once.** The bf16 shards are what lands resident. - **The text encoder is needed at load.** Releasing it after encoding (#13026) frees about 15 GB during denoise. The pipeline still materialises every weight before the first encode, so the load peak includes it. - **An explicit int8 on MPS is built from bf16.** The transformer is quantized in place after a bf16 build, so the build peak is still bf16. - **Quantized parts are sized as stored.** A GGUF transformer is sized at its file size times 1.05, not unpacked. A hosted pre-cast encoder replaces the dense encoder shards in the declared total, rather than adding to them. - **MPS gets the bf16 encoder.** MPS has no fp8 storage, and Qwen-Image's hosted encoder is fp8 only. So 56 GB is an accurate estimate for that pick. This PR keeps the refusal as the default. ### Reserve, compared with ComfyUI and Studio's own allocator cap | | Weights ceiling on 64 GiB | | --- | --- | | This refusal: total minus 20%, against weights plus 2 GiB overhead | 52,429 MiB | | ComfyUI `maximum_vram_for_weights`: 0.88 x total minus 1.2 GiB | 56,443 MiB | | Studio's MPS allocator cap: total minus max(1.5 GiB, 10%) | 58,982 MiB | On MPS, ComfyUI runs in `VRAMState.SHARED`. It never refuses a load; that ceiling only chooses fp8 storage over bf16. The bf16 Qwen-Image load at 57,074 MiB falls between this refusal and the allocator cap. That is the case an explicit "Load anyway" is for, and the per-load override keeps the allocator cap (see below). This PR does not loosen the default reserve without a measurement on a Mac. ### The bug that was fixed The pre-download verdict is meant to judge capacity, so that a model loaded right now does not make a valid swap look too large. On MPS, `snapshot_device_memory` chooses between the RAM view and Metal's working-set view based on what is free right now. The pre-download path kept that choice and only then replaced the free reading with capacity. The same pick on the same 64 GB Mac was therefore judged against 51 GB when idle, and against 41 GB (85% of the 48 GiB working set) whenever less than the working set was free. `unified_capacity_memory` now re-reads RAM at capacity, the floor the snapshot already guarantees. A load past RAM capacity is still refused. ### Smaller hosted variants When the dense companions fit, the refusal now says how much room a quantized main model has. For the Qwen-Image case: "Its text encoders and VAE need about 18 GB, which leaves room for a main model of up to about 34 GB: use a lower GGUF quant ...". Every `unsloth/Qwen-Image-2512-GGUF` quant up to Q8_0 (21.8 GB) fits that room. The pick is never changed silently. ## Changes ### Backend - `allow_oversized_load` (default false) on `DiffusionLoadRequest`, which is also the `/images/download-plan` body, and on `VideoLoadRequest`. - The loaders scope it with a context variable over the load's worker thread, so it is honoured exactly like the env var for that load only. The plan route hands it to its worker the same way. - The env var keeps working. - The native sd.cpp and MLX engines accept the field for interface parity. - The refusal raises `UnifiedMemoryShortfallError`, a `RuntimeError` subclass, so existing handlers still catch it. - Its stable code `unified-memory-load` is returned as `error_code` on image and video load-progress, and as `incompatible_code` on the download plan. - An override that actually goes past the estimate is logged as a warning naming its source (`allow_oversized_load` or the env var). It is never silent. - The env var also lifts the MPS allocator cap; the per-load flag does not. That cap is process-wide and set once when the device is resolved. Keeping it means an over-commit past RAM minus its reserve fails with an MPS out-of-memory error instead of the OS ending the process. - The refusal text now leads with the in-app remedy: "To try anyway, choose Load anyway, or turn on 'Allow oversized model loads' in Settings > System > Model memory (API callers can send allow_oversized_load; server installs can set UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1)." ### Frontend - A new **Allow oversized model loads** switch in Settings > System > Model memory. - It is off by default and stored locally, following the pattern of the existing "Allow oversized generations" switch. - When on, every image and video load and download plan sends `allow_oversized_load`. - On Images and Video, a load refused with `unified-memory-load` shows a titled toast with a **Load anyway** action. - The action opens a confirmation that restates the risk: the load can fail, use up all memory, swap heavily, stop responding or stop Studio. - Only Confirm retries that pick once with the override. Cancel does nothing, nothing retries on its own, and other refusals are unchanged. ## Testing ### Backend `studio/backend/tests/test_diffusion_unified_load_override.py` has 22 new tests covering: - the issue's numbers, reproduced exactly; - the capacity-view fix; - the default still refusing, now with the code; - the request flag lifting the refusal only within its own scope; - the env var still working; - the override's warning; - context propagation through `asyncio.to_thread`, and no leak into another thread; - the request and response models; - `begin_load` handing the flag to the worker; - `error_code` from the image and video workers. On the merge base, a version of these tests with the new imports removed fails 8 of 12. That includes the capacity-view test: the busy Mac reads "only about 41 GB is usable" on base. The existing guard, MPS budget, ROCm APU reserve, text-encoder release, pre-download guard and device suites: 383 passed, 1 skipped. Wider diffusion, video, route, MCP and engine suites: 2,800+ passed. The failures in those suites also fail on the merge base on this host: - `test_begin_load_rejects_concurrent` - four `test_diffusion_native_quant` cases (bitsandbytes CUDA setup) - `test_a_gated_base_with_a_live_mirror_is_not_refused` (network) - the `test_begin_load_answers_without_waiting_on_the_header_probe` timing check ### Frontend - `tests/unified-memory-load-refusal.test.ts` adds 11 tests. The full unit suite passes: 12,906 passed, 0 failed. - `node scripts/typecheck.mjs --tests` passes. - Strict i18n parity passes across all 14 locales. - ESLint error and warning counts on the two pages match the base. ### Studio UI Studio ran from the branch with the diffusion CUDA memory reader patched to report a 3.5 GiB unified pool. The pick was the curated Qwen-Image entry, with its requests redirected to a 30 MB random-weight Qwen-Image pipeline, so no real weights were downloaded. Results: - **Before:** the refusal toast offers only the env var. - **After:** the toast has Load anyway. Confirming loads the model, and the backend logs `loading past the unified-memory estimate (allow_oversized_load)`. - **Setting on:** the same pick loads with no refusal. <!-- screenshots: compare_refusal_before_after.png, head_03_confirm.png, head_04_after_load_anyway.png, compare_settings_before_after.png --> ## Not covered here - No run on a real Mac. Whether bf16 Qwen-Image (57 GB with overhead) completes on a 64 GB Apple Silicon machine under the allocator cap is not measured. - A per-model version of the setting. - Persistence across Desktop restarts and updates is reasoned from local storage under the app's fixed origin, not exercised in a Desktop build. ## Screenshots Studio run with a simulated 3.5 GiB unified pool, on a tiny Qwen-Image so no large weights were downloaded. The refusal before and after: the toast now has a title and a Load anyway action.  Load anyway opens a confirmation that restates the risk; only Confirm retries the load.  After confirming, the model loads (the backend logs that it is loading past the unified-memory estimate).  Settings > System > Model memory: the new "Allow oversized model loads" switch, off by default. 
For #11792. Not run on a Mac yet, so this does not close the issue on its own (see Not covered).
Problem
On a 48 GB M5 Max, Studio refuses
unsloth/Qwen-Image-2.1-GGUFQ4_K_M ("needs about 24 GB ... only about 17 GB is usable"), and withUNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD=1it loads but swaps. Two things add up:te_prequant_sourcesonly admits a pre-cast encoder where fp8 runs (CUDA). On MPS the load falls back to the dense 17.5 GB encoder next to a 4.2 GB GGUF denoiser: 22.4 GB of weights. On unified memory the load-time check reserves 20% of total RAM for the OS, so 27 GB free leaves about 17.4 GB of budget, and 22.4 GB plus overhead is refused.Change
1. The int8 ConvRot encoder on Apple Silicon (
diffusion_te_prequant.py)F.linearon a per-call dequantised view. It needs no torchao, no fp8 dtype and no CUDA kernel.te_prequant_sourcesnow admits it on an MPS target. The fp8 fallback names are dropped there, since fp8 cannot run on MPS, and the fp8 retry in_te_prequant_pipe_kwargsis gated the same way.For the numbers in the report (48 GB total, 27 GB free), the weights go from 22.4 GB to 14.2 GB, which is under the 17.4 GB budget. A genuinely oversized load, such as the dense bf16 transformer with the same encoder, is still refused.
2. Release the text encoders during denoise on unified memory (new
diffusion_te_release.py)UNSLOTH_DIFFUSION_RELEASE_TEXT_ENCODER=1forces it on and=0forces it off.The load-time check itself is unchanged. The load still materialises every weight at once, so the release cannot lower what the load needs, only what each render holds afterwards.
Results
One B200, Studio's
DiffusionBackendwithunsloth/Qwen-Image-2.1-GGUFQ4_K_M, 1024x1024, 20 steps, guidance 4, speed mode off. The release is forced withUNSLOTH_DIFFUSION_RELEASE_TEXT_ENCODER=1, since this host is discrete VRAM; on a Mac it engages automatically. Three generations per arm: prompt A seed 42, prompt A seed 43 (prompt cache, no encoder run), then prompt B seed 42 (the encoder runs again). Peak is torch's peak allocation for that generation.int8 ConvRot encoder (the default this PR brings to Apple Silicon):
bf16 encoder (
text_encoder_quant=none, today's Apple Silicon default):Testing
tests/test_diffusion_te_release.py(20 tests):QwenImage21Pipeline(hf-internal-testing/tiny-qwenimage21-pipe) rendering identical images with the release on, through the realprogress_bardenoise hook. That test skips only when the installed diffusers has noQwenImage21Pipeline.test_video_h3_te_quant.py::test_the_read_layer_matches_the_diffusers_pipeline, which already fails on main on this host).Not covered
text_encoder_quant=int8on MPS is still refused by the pre-load check, as before. Only the default (auto) pick takes the int8 encoder there.