Repository navigation
Studio: stream oversized diffusion components on low-VRAM GPUs - #8141
danielhanchen merged 3 commits into
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 63332ab602
ℹ️ 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 isinstance(component, torch.nn.Module): | ||
| component.to(onload) |
There was a problem hiding this comment.
Do not resident-load oversized unstreamed components
When refinement is triggered by an oversized component other than a transformer or text encoder (for example, a VAE or image encoder), that component is absent from streamed and is moved wholesale to the accelerator here. Because refine_memory_plan_for_components() compares every pipeline component against the device budget, this path can select streaming precisely because that component cannot fit, then deterministically OOM during .to(onload) instead of retaining the previously viable model-offload policy; either stream every component that exceeded the budget or only refine when all unstreamed components are proven to fit.
Useful? React with 👍 / 👎.
… PR unslothai#8141 refine_memory_plan_for_components sized the policy against every component, but _apply_streaming_offload only streams transformers and text encoders and moves everything else resident. An oversized VAE or image encoder therefore selected streaming and was then onloaded whole, and whole-module offload holds one component at a time while streaming holds every unstreamed one at once. Share the streamed-component selection between the two so the planner sizes against what actually streams, and keep whole-module offload when the resident set does not fit together.
|
Pushed What it changes
The commit pulls the streamed-component selection into Neither case is reachable with an image family we ship today. Before and after
Simulation10,080 load cells, each run through three versions of
Counting cells whose placement leaves more resident than its own budget: The 245 are exactly the two shapes above. The benefit is kept in full: 1078 cells still resolve to 112 targeted assertions on top of that, all passing: diffusers API skew. Real hardware. Because the fakes only prove the policy, the streaming path was also run against real torch 2.9.1 and real diffusers 0.39.0 in a clean venv, on an 8 GB budget emulated with and the guard case, same card and cap: Compatibility
Tests
The failure and error sets are byte identical between the two revisions, 131 entries each, and all of them are local environment breakage rather than code: a torchao build that cannot import against this torch, which takes Full diffusion suites pass clean locally: One thing I left alone
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 37aa029abb
ℹ️ 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 largest_mib <= int(budget): | ||
| return plan |
There was a problem hiding this comment.
Include runtime headroom when deciding a component fits
When a text encoder's weights fit just below safe_device_budget_mib but its weights plus prompt-encoding activations do not, this returns the original model-offload plan, which still onloads the entire encoder and can OOM during its forward. The plan already exposes runtime_headroom_mib (and base_overhead_mib), so the fit comparison needs to reserve that working memory rather than comparing weights alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one.
runtime_headroom_mib is estimate_image_runtime_mib, the latent and VAE-decode budget for the generation itself, 8192 MiB at the 1024x1024 default. It is not the text encoder's prompt-encoding activation, which runs on 77 to 512 tokens and costs tens of MiB. Reserving the first against a per-component weight check compares the wrong two quantities.
On the cards this tier exists for it is also larger than the entire budget:
6 GB card: safe budget 4096 MiB, headroom 8192, base overhead 2048 -> budget - headroom - overhead = -6144
8 GB card: safe budget 6144 MiB, headroom 8192, base overhead 2048 -> -4096
12 GB card: safe budget 10240 MiB, headroom 8192, base overhead 2048 -> 0
So largest + runtime_headroom + base_overhead <= budget could never be satisfied there by a component of any size, including a zero-byte one, and refinement would fire on every low_vram load on a 6, 8 or 12 GB card. Measured cost of that on a real forward: leaf-level streaming is 9.0x slower than resident, so it would be a 9x slowdown applied to loads whole-module offload handles fine today.
The kernel is real, a component sitting at 99 percent of budget has no room for its own forward, but closing it needs a per-component activation estimate, which the plan does not carry. The image-generation headroom is not a stand-in for it, and the behaviour at that boundary is unchanged from main either way.
| transformer = getattr(pipe, "transformer", None) | ||
| if not isinstance(components, dict) or not isinstance(transformer, torch.nn.Module): | ||
| return plan |
There was a problem hiding this comment.
Recognize the supported U-Net denoiser during refinement
When loading the supported SDXL family on a GPU where a CLIP component exceeds the device budget, this guard always returns the model-offload plan because SDXL exposes its denoiser as pipe.unet, not pipe.transformer. The oversized encoder is therefore still onloaded whole and can OOM; include the family's U-Net denoiser in the streamable-component selection instead of requiring a transformer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured this rather than reasoning about it.
Group offloading does accept a real UNet2DConditionModel, so the request is implementable. It just does not pay. block_level is what the denoiser path uses, and down_blocks / up_blocks are 3 entries each, so one block is a large fraction of the model. On an SDXL-topology U-Net at fp16, 4897 MiB of weights, 4 denoise steps, real diffusers 0.39.0:
arm peak MiB 4 steps vs resident
resident 5083 0.162 s 1.00x
block_level 4695 1.410 s 0.92x memory, 8.7x slower
leaf_level 145 1.461 s 0.03x memory, 9.0x slower
Adding unet to the streamable set as asked is the block_level row: an 8 percent memory saving for an 8.7x slowdown. That does not rescue a card whole-module offload already cannot fit, it just makes the same failure slower.
leaf_level would genuinely work, but picking a different granularity for one family is a separate design decision that needs its own SDXL testing, not a late addition to a PR about transformer families. Worth noting too that SDXL's own encoders are CLIP-L at 246 MiB and CLIP-G at 1.4 GiB, so the oversized component on that family is the U-Net itself rather than a CLIP tower.
For contrast, the case this PR does target goes from 4962 MiB resident to a 33 MiB peak.
|
@codex review |
|
Note on the red checks, so they are not read as this PR's.
The Everything else on the head is green, 41 checks including the Backend CI studio matrix on Python 3.10, 3.11, 3.12 and 3.13. Cross-platformSince this is a studio backend change, I ran the diffusion suites on the real OS triple rather than relying on the code being pure Python:
|
|
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". |
…fusal (#8257) Four tests are red on a clean checkout of main. #8165 made a declined EXPLICIT precision refuse the load instead of falling back silently, and made the text-encoder pass return a TEQuantOutcome the loader reads .mode off. Two later squash merges carried branches cut before it: #8162 added the saved-recipe precision contracts, and #8141 added a placement test whose stub returns a bare None. Neither combination was ever run. Fixed on the test side. quantize_text_encoders is annotated -> TEQuantOutcome and every one of its seven returns constructs one, so the None at diffusion.py:3113 only exists because a test monkeypatches the function; and the route only calls assert_precision_available on the diffusers engine, which is DiffusionBackend, which defines it. Neither AttributeError is reachable in a real run, so there is no product guard to add. - opt into UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK where the contract is about what the recipe records once a fallback is allowed, as the routes, backend and video suites already do - assert the decline reason #8165 records instead of the old wording naming what loaded instead. The substantive pair is untouched: off, from explicit - give _EngagedBackend the assert_precision_available gate the route now calls, and return a TEQuantOutcome from the stubbed text-encoder pass
…fusal (#8257) Four tests are red on a clean checkout of main. #8165 made a declined EXPLICIT precision refuse the load instead of falling back silently, and made the text-encoder pass return a TEQuantOutcome the loader reads .mode off. Two later squash merges carried branches cut before it: #8162 added the saved-recipe precision contracts, and #8141 added a placement test whose stub returns a bare None. Neither combination was ever run. Fixed on the test side. quantize_text_encoders is annotated -> TEQuantOutcome and every one of its seven returns constructs one, so the None at diffusion.py:3113 only exists because a test monkeypatches the function; and the route only calls assert_precision_available on the diffusers engine, which is DiffusionBackend, which defines it. Neither AttributeError is reachable in a real run, so there is no product guard to add. - opt into UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK where the contract is about what the recipe records once a fallback is allowed, as the routes, backend and video suites already do - assert the decline reason #8165 records instead of the old wording naming what loaded instead. The substantive pair is untouched: off, from explicit - give _EngagedBackend the assert_precision_available gate the route now calls, and return a TEQuantOutcome from the stubbed text-encoder pass
Summary
Studio's Low VRAM image path can still OOM during prompt encoding because model CPU offload moves one complete component onto the GPU. The dense Qwen3 encoder used by FLUX.2 Klein must therefore fit in full even when the GGUF transformer is small.
This PR measures the loaded components and uses granular Diffusers offload only when one cannot fit. On an 8 GB class GPU, the reported load goes from OOM to a completed image at a 2,620 MiB peak.
What changed
low_cpu_mem_usage=True, report the effectivestreamingpolicy, and fail clearly instead of retrying a whole-component onload already known to OOM.Measurements
FLUX.2 Klein 4B Q4_0 with its dense 7,673 MiB Qwen3 text encoder, 1024x1024, four steps, speed and transformer quantization off.
model, OOM during prompt encodingstreaming, two images generatedmodel, two images generatedmodel, two images generatedAt 8 GB, granular streaming cuts the attempted generation peak by 5,058 MiB, or 66 percent, and completes in 5.13s on the first run and 4.12s on the second. At 12 GB, where the encoder fits, placement and peak allocation are unchanged.
Behavior boundaries
Testing
git diff --checkpassed.Runtime validation
Loaded the cached FLUX.2 Klein 4B Q4_0 GGUF through the real Studio backend with Diffusers 0.39.0.