Repository navigation
Studio: count the hosted text encoder and keep the GGUF denoiser resident when only the encoder does not fit - #11802
Conversation
…er resident when only the encoder does not fit
…, pin at allocator size, stream the transformer if a late encoder refuses
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. |
load_prequant_text_encoder can return None for a cached checkpoint too, and assembly then opens the dense shards on disk, so budget max(pre-cast, scanned dense) whether or not the checkpoint is cached. The prefetch skips covered shards, so the usual case is unchanged, and the resident-denoiser tier only streams encoders, so the 24 GB placement holds even with dense shards cached.
…artly offloaded encoder before falling back WDDM and WSL2 cap page-locked host memory near 1 GiB whatever RAM is free, so pinning a multi-GB encoder or transformer failed part way. On the resident-transformer tier the leaf hooks left by that failure made enable_model_cpu_offload reject the pipeline and the load failed. Those hosts keep the unpinned streaming they had before, and a first-encoder refusal now drops its hooks before whole-module offload takes over.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f08f6369c
ℹ️ 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".
| model_dense_mib = None | ||
| if transformer_resident is not None: | ||
| model_dense_mib = transformer_resident + (companion_mib or 0) | ||
| if companions_from_cache and text_encoder_quant is not None: |
There was a problem hiding this comment.
Reprice pre-cast encoders in override plans
When a pipeline combines a hosted pre-cast encoder with transformer quantization, the dense-quant replans pass candidate.companions_mib and candidate.text_encoders_mib, which estimate_dense_quant() derives from the dense BF16 family table. This guard prevents the new pre-cast correction from running for those overrides, so a configuration such as Qwen-Image-2.1 on a 40 GB card is charged for the 17.5 GB dense encoder rather than the roughly 9 GB artifact; the replan can consequently retain encoder-only group offload and decline or reject an explicit transformer-quant request even though the combined quantized artifacts fit resident. Apply the pre-cast replacement to these override terms as well, or scale them before passing them to _plan_memory().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not a regression: the dense-quant replans price the encoder exactly as main does, and this PR deliberately leaves caller overrides alone (test_plan_memory_leaves_a_callers_companion_override_alone). The over-estimate errs toward more offload, never an OOM; repricing those replans is a separate change.
|
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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/core/inference/diffusion_memory.py
Lines 1136 to 1138 in 4379853
When a Qwen3-VL encoder is leaf-offloaded and an image condition is supplied, the original fast_pos_embed_interpolate() reads the still-offloaded pos_embed.weight.device and creates its interpolation weights on CPU; the embedding hook then onloads the embedding and moves its index argument to CUDA, so the original method attempts to multiply the CUDA embedding output by CPU weights and raises before this wrapper regains control. Moving out after _original() therefore cannot prevent the device mismatch; the interpolation inputs must be created on the compute device (or this embedding must remain resident) before invoking the original calculation.
ℹ️ 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".
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4379853e56
ℹ️ 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 not stream_transformer and installed == 0: | ||
| # Resident encoder here would OOM; fall back to model offload, which rejects partial hooks. | ||
| _remove_group_offload_hooks(module) | ||
| raise | ||
| if not stream_transformer and not transformer_demoted: |
There was a problem hiding this comment.
Clear partial hooks after any encoder setup failure
When the resident-transformer tier has multiple text encoders, a successful first encoder makes installed > 0; if apply_group_offloading then raises after partially installing hooks on a later encoder, this branch skips _remove_group_offload_hooks(module), demotes the transformer, and subsequently calls module.to(onload) with the failed encoder's partial hook registry still attached. This can abort loading or leave an incompletely configured encoder at inference time—the same partial-install condition the installed == 0 path explicitly cleans up. Remove hooks from the currently failing encoder before either fallback path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced on real diffusers pipes (tiny SD3, CUDA): the 2nd or 3rd encoder installs its hooks then raises, the load stays group and two generations are bit-identical to fully resident. The leftover hooks keep that encoder streamed, so the later .to() does not leave it resident or broken. Not a correctness issue.
| except Exception: # noqa: BLE001 - an unsizeable module is priced as nothing to pin | ||
| return 0 |
There was a problem hiding this comment.
Disable pinning when a module cannot be sized
If tensor enumeration or numel()/element_size() fails for a custom or quantized module, returning zero makes _streamed_pin_plan treat that module as free and enable low_cpu_mem_usage=False. The new default pinning path can then pin an arbitrarily large, unsized transformer or encoder despite the host-RAM gate, recreating the host-memory exhaustion this gate is intended to prevent. Propagate an unknown-size result and conservatively leave that component unpinned instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
parameters(), numel() and element_size() do not raise on nn.Module / GGUF parameters, so the zero fallback is unreachable on real loads.
| total, _available = _system_memory_mib() | ||
| available = _available_system_memory_mib() | ||
| if total is None or available is None: | ||
| return None | ||
| reserve = max(_PIN_RESERVE_MIN_MIB, int(int(total) * _PIN_RESERVE_FRACTION)) |
There was a problem hiding this comment.
Base the pin reserve on cgroup capacity
Under an enforcing memory cgroup, _available_system_memory_mib() is capped to the container but total still comes from host-wide physical RAM, so the reserve is calculated from a pool the process cannot use. For example, a 64 GiB container on a 512 GiB host gets a 76.8 GiB reserve and therefore a zero pin budget even when nearly all 64 GiB is available, disabling the new pinned streaming optimization. Cap the total by _cgroup_memory_limit_mib() before applying the 15% reserve, as the device-budget path already does for container capacity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Under a tight cgroup the budget just drops to zero and nothing is pinned, which is the previous unpinned behavior: a missed speedup, not a correctness bug.
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
|
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". |
Size the streamed-tier pin reserve from the container like _pin_host_weights (#11766) and reuse its constants.
|
@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: 54183cf738
ℹ️ 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".
| policy = OFFLOAD_NONE | ||
| reasons.append("weights fit resident with headroom") | ||
| elif _resident_transformer_fits(): | ||
| policy = OFFLOAD_GROUP |
There was a problem hiding this comment.
Preserve resident-denoiser speed optimizations
When this encoder-only streaming tier is selected with the default or max speed mode, the OFFLOAD_GROUP policy is still translated to offload_active=True in DiffusionBackend.load_pipeline. apply_speed_optims() then disables full-graph compilation and diffusion_cuda_graph.graph_eligible() unconditionally refuses CUDA graphs because it assumes denoiser weights have onload hooks; here stream_transformer=False, so only text encoders have hooks and the denoiser's pointers remain stable. This unnecessarily removes denoising optimizations from the tier intended to run every denoise step resident; thread a transformer-offload predicate based on stream_transformer into those speed checks instead of deriving it solely from the policy.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Deliberate in this PR: the tier stays offload_policy group so every existing != none check (fullgraph compile, CUDA graphs, torchao) behaves as before. That is a missed speedup, not a correctness bug; the stacked #11883 threads a resident-transformer predicate into those checks.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…dent when only the encoder does not fit (unslothai#11802) * Studio: price the hosted pre-cast text encoder and keep the transformer resident when only the encoder does not fit * Studio: pin the streamed-encoder tiers when host RAM allows, transformer first * Studio: price only the encoder folders a pre-cast checkpoint replaces, pin at allocator size, stream the transformer if a late encoder refuses * Format * Studio: never price a cached pre-cast encoder below its dense shards load_prequant_text_encoder can return None for a cached checkpoint too, and assembly then opens the dense shards on disk, so budget max(pre-cast, scanned dense) whether or not the checkpoint is cached. The prefetch skips covered shards, so the usual case is unchanged, and the resident-denoiser tier only streams encoders, so the 24 GB placement holds even with dense shards cached. * Studio: do not pin streamed modules on Windows or WSL, and unhook a partly offloaded encoder before falling back WDDM and WSL2 cap page-locked host memory near 1 GiB whatever RAM is free, so pinning a multi-GB encoder or transformer failed part way. On the resident-transformer tier the leaf hooks left by that failure made enable_model_cpu_offload reject the pipeline and the load failed. Those hosts keep the unpinned streaming they had before, and a first-encoder refusal now drops its hooks before whole-module offload takes over. * Studio: trim comments * Studio: do not add a pre-cast encoder on top of a bf16 table-priced pipeline * Format * Studio: price HiDream's hosted fourth text encoder in the memory plan * Studio: price an uncached HiDream fourth encoder from its own size
Why
A Windows user on HF (unsloth/Qwen-Image-2.1-GGUF discussion #4, Desktop v0.1.813-beta) reports that Qwen-Image-2.1 GGUF Q8_0 takes much longer per image in Studio than the same Q8_0 file in ComfyUI. I reproduced it with the same Q8_0 file, the same fp8 text encoder repo Studio pulls (
unsloth/Qwen-Image-2.1-FP8) and the same VAE, on 24, 16 and 12 GiB VRAM caps. On those cards the time goes into memory placement, not into the GGUF kernels:unsloth/Qwen-Image-2.1-FP8. The companion scans only walk the base repo, so a GGUF load budgets 8,938 MiB (DiT + VAE) for 17.9 GiB of weights. On a 16 GB card that gives group offload with the encoder resident, and the first image runs out of memory. On Windows, WDDM spills the overflow into shared system memory instead of raising, which is the "drastically slower" case.low_cpu_mem_usage=Truefor everything, so diffusers re-pins every tensor on every onload. On the 16 GB cap that is 25.1 s against 8.5 s pinned. The encoder-only pass goes from 0.39 s to 2.37 s.Measured and ruled out as causes for this report:
TORCHDYNAMO_DISABLE=1matches what a Windows install without Triton gets.What changes
_plan_memorytakes the resolvedtext_encoder_quant. When the load takes its encoder from a hosted pre-cast checkpoint, it prices that checkpoint in the encoder, companion and model terms (_precast_text_encoder_mib, which uses the same resolver as the injection).text_encoder*folders the checkpoint replaces leave the budget, so FLUX.1 keeps its dense CLIP-L.noneandgroup: the transformer stays resident and only the text encoders stream. It is chosen whenmodel - encoders + headroom + overheadfits the budget.offload_policy == "group", with a newMemoryPlan.stream_transformer = False, so every existing!= nonecheck (compile fullgraph, CUDA graphs, torchao declines) behaves as before._apply_group_offload(stream_transformer=False)hooks only the encoders.UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN=0|1overrides this. A RAM-poor host keeps today's unpinned path, and so do native Windows and WSL2: both cap page-locked memory near 1 GiB whatever RAM is free (NVIDIA lists it as a known WSL limitation), and a pin that fails part way used to fail the resident-transformer load outright. On those hosts the 16 GiB row below is the unpinned figure (the "nothing pinned" spot check), not the pinned one.Results
Qwen-Image-2.1
qwen-image-2.1-Q8_0.gguf, 1024x1024, 25 steps, CFG 1. Timings are the median of 4 renders per cell over 2 interleaved passes. Compile is off to match Windows without Triton. ComfyUI is a current upstream build with a GGUF loader node that reads this file, the template's int8 text encoder and the same VAE.Spot checks, one pass each:
Phase split for the 24 GiB cap (after): TE 0.35 s, denoise 4.17 s, VAE 0.11 s. Peak allocated drops from 15.7 to 14.3 GiB at 24 GiB. At 16 GiB it is 7.0 GiB.
Accuracy. Every image from this PR is either bit-identical to the pre-PR image at the same seed or within run-to-run cuDNN noise: LPIPS (alex) at most 9.5e-5, PSNR at least 58 dB, over 4 prompts per cell.
12 GiB. This PR does not change the 12 GiB tier; it stays whole-module offload. With #11764 and #11766 merged on top it measured 26.4-28.4 s -> 16.7 s in an earlier contended run.
Tests
tests/test_diffusion_memory.py:apply_memory_planthreads the flag;tests/test_diffusion_backend.py:_plan_memory, including the swap of scanned dense shards, the FLUX.1-style partial swap, never pricing below dense shards on disk, and caller overrides left alone;_precast_text_encoder_mibagainst a fake cache, both cached and table-priced.test_plan_memory_hands_the_planner_the_text_encoder_split): that shape now picks the resident-transformer tier.test_diffusion_backend.py,test_diffusion_memory.py,test_diffusion_auto_policy.pyandtest_video_backend.py: 966 passed on CPU.ruff checkandscripts/run_ruff_format.pyare clean.How it was measured
DiffusionBackendon a shared B200. The VRAM cap is simulated by patchingtorch.cuda.mem_get_infoto report the card's total, minus a 1.2 GiB desktop and context share, and hard-capping the allocator withset_per_process_memory_fraction. ComfyUI ran under the same patch.encode_promptandvae.decodewith device syncs. ComfyUI is split per node from its websocket events.Not measured
te_prequant_reposis set, and the new tier applies to any image load whose encoder split is known. Both are covered by unit tests only.