Repository navigation
Studio: Load anyway for the unified-memory diffusion refusal, and a capacity fix for its pre-download check - #14379
Conversation
…n refusal The unified-memory load refusal could only be lifted with the server env var UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_LOAD, which a desktop install has no way to set. - Image and video load requests (and the image download plan) take allow_oversized_load, honoured exactly like the env var for that load only. The env var keeps working. A load that goes past the estimate logs a warning. - The refusal is now UnifiedMemoryShortfallError (a RuntimeError) and surfaces a stable code, unified-memory-load, as load-progress error_code and download-plan incompatible_code. - The pre-download capacity verdict on Apple Silicon no longer depends on what is free right now: a 64 GB Mac was judged against 51 GB usable when idle and 41 GB when another model was loaded. - The refusal names the room a quantized main model has beside the dense text encoders and VAE, and points at the new setting before the env var.
…t setting - Settings > System > Model memory gains 'Allow oversized model loads', off by default and stored locally, which sends allow_oversized_load with every image and video load and download plan. - An Images or Video load refused with the unified-memory-load code shows a titled toast with a Load anyway action. The action opens a confirmation that restates the risk; only Confirm retries that pick once with the override. Nothing retries on its own, and other refusals are unchanged.
# Conflicts: # studio/backend/core/inference/diffusion.py # studio/backend/core/inference/video.py
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: 21e3d744b3
ℹ️ 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".
| companions = sum( | ||
| max(0, int(size or 0)) | ||
| for path, size in (declared_files or ()) | ||
| if not str(path).startswith(DENOISER_SUBFOLDERS) |
There was a problem hiding this comment.
Exclude UNet files from the companion-only estimate
For SDXL pipelines, the denoiser weights live under unet/, but DENOISER_SUBFOLDERS only recognizes transformer/ and unconditional_transformer/. Consequently, on a unified-memory host where SDXL is oversized, this helper counts the entire UNet as a companion and the new refusal incorrectly claims that the text encoders and VAE alone consume the full footprint and that a lower denoiser quant cannot help. Classify unet/ as a denoiser for this semantic companion split while preserving the existing resident-factor behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ed15bb0: the companion-only estimate now treats unet/ as the denoiser too, so an oversized SDXL pick no longer reports the UNet as text encoder and VAE weight. The resident factors are unchanged. Added a test that the UNet is excluded, which fails on the previous code.
| offerLoadAnyway(incompatible, () => { | ||
| oversizedLoadOnce.current = true; | ||
| try { | ||
| void loadOrStageRef.current(repoId, opts, retrySource, undefined, familyOverrideRequired, undefined, true); |
There was a problem hiding this comment.
Fence Load-anyway retries against newer picks
When an oversized plan is refused, this toast remains actionable for 20 seconds and its confirmation callback captures the refused model without checking pickSeq or ownership again. If the user selects or loads another model before clicking the old toast action—or before confirming the dialog—the callback starts the stale model and supersedes the newer choice. Capture the originating pick/token and reject the retry once it is no longer current, or invalidate prior Load-anyway prompts when a new pick begins; the video page has the analogous callback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 17e80a1aca. The Load anyway toast and its confirm dialog outlived the refused pick, and the retry reran the captured model without checking for a newer pick or load. On both the Images and Video pages the retries now go through retryWhileCurrent: the plan-refusal retry checks its pickSeq value is still current, and the load-refusal retry checks both pickSeq and loadSeq, so a confirm from an older pick or load does nothing. useLoadAnywayPrompt also exposes dismiss(), which a new pick and the start of a load call to close any open prompt. New unit tests cover a stale confirm (no load), a current confirm (still retries) and the wiring on both pages; both fail on the previous code.
…gins A refused oversized pick left a 20 second Load anyway toast whose confirm retried the captured model unconditionally, so clicking it after picking or loading another model started the stale one and superseded the newer choice. Both retries on the Images and Video pages now re-check the pick sequence (and the load sequence for the load refusal) before retrying, and a new pick or load dismisses any open Load anyway toast and dialog. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
…an unused import, add error_code to the exact load-progress shape
… in the CFG routers, and test fixes (#14420) ## Summary Follow-up fixes for the recently merged Studio diffusion work: two runtime fixes (the VAE OOM ladder under a multi-GPU component split, and bitwise comparison of expanded timesteps in the CFG routers) and five test fixes. Each change is its own commit. ### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802 with #13725) **What was broken.** Under a component split the VAE decodes on a secondary card while the denoiser stays resident on the primary. When that decode ran out of memory, `DecodeSession.free_others` reset the denoiser's CUDA graphs on the primary card and counted that as "released". The ladder then retried the same untiled decode on the secondary card, which ran out of memory again before it reached the tiled rung, and the denoiser lost its captured graphs for nothing. `_release_groups` had the same problem with resident offload groups on the primary card. A failed re-pin was also deferred against the VAE's card instead of the groups' own card. **Fix.** Graph handles are filtered to the VAE's card, using the card the graph was recorded on (or its module's card when nothing has been recorded yet). Resident-group modules are filtered by `_unsloth_resident_device`. This is the same filtering `_hook_torchao_resident` and `_move_components` already do with `_placement(comp, self.device)`. `release_resident_groups` takes an optional `device` filter. It is only passed when the pipeline has resident groups on more than one card, so single-card calls are unchanged. Anything whose card cannot be read is still freed, as before. **Tests** (`test_diffusion_vae_oom.py`, all fail on main): - `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on cuda:1 with graphs on cuda:0 goes straight from the untiled decode to the tiled one, and no graph is reset. - `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the cuda:1 handle is reset. - `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on cuda:0 are left alone and nothing is deferred against them. With groups on both cards, the release is limited to cuda:1. - `test_release_resident_groups_device_filter`: the new filter releases only the matching card's groups, and with no filter every card's groups are released. ### 2. Expanded scalars compare bitwise in the CFG routers (#13725, #13787) **What was broken.** `_bitwise_equal` in `diffusion_multigpu.py` flattens both tensors, calls `contiguous()` and views them as `uint8`. WanPipeline passes `timestep = t.expand(batch)`. For a one-element tensor `contiguous()` is a no-op whatever the stride, so the stride-0 timestep reached `view(torch.uint8)`, which raised, and the comparison returned False for two equal timesteps. #13787 CFG batching uses it through `_record_template`, `_matches` and the branch merge. On Wan it missed three times in a row and turned itself off. CFG-parallel's prediction check uses the same helper. **Fix.** A small `_as_bytes` helper takes a dense copy only when the flattened tensor still has a non-unit stride. `_bitwise_equal` and `_unchanged_since_launch` both use it. Bitwise semantics are unchanged: equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three call sites all go through `_bitwise_equal`, so they are covered by the same fix. **Tests** (both fail on main): - `test_bitwise_equal_on_an_expanded_scalar` (`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a clone and a fresh expand, plus NaN, signed zero and `_unchanged_since_launch`. - `test_wan_expanded_timesteps_serve_the_second_branch` (`test_diffusion_cfg_batch.py`): a Wan-style loop that passes `t.expand(batch)` to each branch. It matches the two-call reference with 4 hits, 0 misses, and batching stays on. On main it gets 0 hits. ### 3. Seeded denoiser cancel test pins the text encoder (#13715) **What was broken.** On a CUDA host, an unset `text_encoder_quant` also plans the hosted FP8 Wan text encoder. The load then fetched two artifacts and `test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event` failed its exact single-fetch assertion. It passed only with the GPU hidden. **Fix.** The test passes `text_encoder_quant = "off"`, so it checks only what it is about: the denoiser fetch carries the load's cancel event. **Test.** Fails on main with a GPU visible and passes after. It passes both ways with the GPU hidden. ### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401) **What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not drop the child-registry list that an earlier uncached render cached. `test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with `ValueError: No context is set`. Production already calls `_invalidate_child_registry_cache` after `enable_cache` in `apply_step_cache`. Only the test helper skipped it. diffusers 0.41 invalidates the list itself. **Fix.** The test's `_render` helper calls `dc._invalidate_child_registry_cache(model)` after `enable_cache`. **Test.** With diffusers 0.39.0 the test failed before and the whole file passes after (7 passed). It also passes on the pinned diffusers. ### 5. Stream encode tests skip when diffusers cannot import the Wan VAE (#14405) **What was broken.** `pytest.importorskip("diffusers")` succeeds on the lazy top-level module. The next line, `from diffusers import AutoencoderKLWan`, can then raise `RuntimeError` (for example with a broken bitsandbytes), which aborted collection of the whole pytest run. **Fix.** Catch `ImportError` and `RuntimeError` on those imports and skip the module, as the other diffusion tests do. **Test.** In an environment with a broken bitsandbytes, collection errored before and the module is skipped after. In the Studio environment all 9 tests still run and pass. ### 6. Multi-GPU planner tests pin the host facts they read (#13725, #13793) **What was broken.** On a host with one GPU, 11 tests in `test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at or above the real `torch.cuda.device_count()` and cards below the primary's capability, so `make_selection(0, [0, 1])` returned None on a one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151) showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on `get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm reports the gfx version (gfx1151 gives (11, 5)), and torchao then refuses fp8 there. **Fix.** Tests only. The autouse fixture pins the card count and the capability check (tests that probe those filters still override them), and the fp8 GPU gate returns False on a HIP torch, matching Studio, which already declines torchao fp8 on ROCm. New test `test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two cards at capability (11, 0), the planner selects both and splits onto card 1, as on CUDA. **Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete cards, one CUDA card without HIP): 11 failed before, 114 passed after on each. Normal CPU host: 133 passed, 1 skipped. ### 7. The ROCm APU pool discount applies only to HIP device snapshots (#14379) **What was broken.** `_rocm_linux_apu_os_room_outside_pool` (`diffusion_memory.py`) gave any unified-memory reading the smaller Linux ROCm APU reserve on a ROCm build, without checking the snapshot's device. On a ROCm host, a mocked Apple (`mps`) snapshot in `test_diffusion_unified_load_override.py` got that reserve, so two refusal tests failed. A real ROCm build never produces an `mps` reading, so the user impact is close to zero. **Fix.** The discount now requires a `cuda` device snapshot (`cuda` or `cuda:N`). `test_flux3_prompt_upsampler.py` also pins `torch.__version__` in the tests that stand in for a CUDA build (Studio reads `+rocm` there too) and pins the card count in its warm fixture, which read the real host. **Tests.** The new `mps` / `cpu` reserve test fails without the fix and passes with it. Prompt upsampler: 164 passed on a spoofed APU, two discrete ROCm cards, two CUDA cards and plain CPU. ## Tests Base is origin/main and head is this branch. Same host and same Studio venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared, not counts. - CPU, GPU hidden: test_diffusion_vae_oom.py, test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py, test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py, test_diffusion_int8_gemm.py, test_video_stream_residency.py, test_diffusion_offload_prefetch.py, test_diffusion_small_host_prefetch.py, test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py, test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed. Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing IDs on either side. - One GPU visible: test_video_prequant.py. Base: 1 failed (`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`), 85 passed. Head: 86 passed. - CPU, GPU hidden: test_diffusion_cfg_batch.py, test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py, test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2 new tests). No failures on either side. - test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed before, 7 passed after. Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base and head ran on the two T4s of one kernel, each on its own CPU slice: | Run | s/step | CFG batch | |---|---|---| | base, CFG batching off | 5.96 | not armed | | base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off | | head, CFG batching off | 5.58 | not armed | | head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain (batched pair 5.42 s vs plain pair 5.39 s) | - The 43% slowdown on base is gone. On this streamed T4 placement a batched pair is no faster than two plain calls, so the batcher's own timing gate turns it off, as designed. - The batching-off latents are identical on base and head (`829b889b587d13f6`), so the plain path is unchanged. The two batched steps are not bit-exact, as documented for CFG batching. ## Not verified - CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs two CUDA cards in one process and was skipped. - No real two-GPU decode that runs out of memory. The split case is covered by CPU tests that use real `torch.device("cuda", N)` indices with fake graph handles and resident modules. - diffusers 0.40.0 was not run. Its source lacks the same invalidation as 0.39.0.
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-Imagepipeline (Qwen-Image-2512has the same sizes) on a 64 GiB unified pool:What is not over-counted
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
maximum_vram_for_weights: 0.88 x total minus 1.2 GiBOn 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_memorychooses 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_memorynow 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-GGUFquant up to Q8_0 (21.8 GB) fits that room. The pick is never changed silently.Changes
Backend
allow_oversized_load(default false) onDiffusionLoadRequest, which is also the/images/download-planbody, and onVideoLoadRequest.UnifiedMemoryShortfallError, aRuntimeErrorsubclass, so existing handlers still catch it.unified-memory-loadis returned aserror_codeon image and video load-progress, and asincompatible_codeon the download plan.allow_oversized_loador the env var). It is never silent.Frontend
allow_oversized_load.unified-memory-loadshows a titled toast with a Load anyway action.Testing
Backend
studio/backend/tests/test_diffusion_unified_load_override.pyhas 22 new tests covering:asyncio.to_thread, and no leak into another thread;begin_loadhanding the flag to the worker;error_codefrom 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_concurrenttest_diffusion_native_quantcases (bitsandbytes CUDA setup)test_a_gated_base_with_a_live_mirror_is_not_refused(network)test_begin_load_answers_without_waiting_on_the_header_probetiming checkFrontend
tests/unified-memory-load-refusal.test.tsadds 11 tests. The full unit suite passes: 12,906 passed, 0 failed.node scripts/typecheck.mjs --testspasses.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:
loading past the unified-memory estimate (allow_oversized_load).Not covered here
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.