Skip to content

Studio: stream oversized diffusion components on low-VRAM GPUs - #8141

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
oobabooga:fix/studio-diffusion-text-encoder-offload
Aug 9, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
oobabooga:fix/studio-diffusion-text-encoder-offload

Conversation

@oobabooga

@oobabooga oobabooga commented Aug 8, 2026 •

Copy link
Copy Markdown
Member

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

  • Refine placement after pipeline construction and optional text-encoder quantization using actual parameter and buffer storage.
  • Keep existing placement when every component fits the safe GPU budget.
  • When one does not fit, stream transformer blocks and text-encoder layers while keeping the small tiled VAE resident.
  • Bound pinned CPU memory with low_cpu_mem_usage=True, report the effective streaming policy, 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.

VRAM Existing policy and result This PR policy and result Peak GPU, existing to PR
8 GB model, OOM during prompt encoding streaming, two images generated 7,678 to 2,620 MiB
12 GB model, two images generated model, two images generated 7,991 to 7,991 MiB

At 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

  • Resident, transformer-only group, and fitting whole-module placement are unchanged.
  • Text-encoder quantization stays optional. The new fallback changes placement without changing weights.

Testing

  • Focused diffusion memory and backend suites: 228 passed after rebase.
  • Automatic policy, sd.cpp argument, and diffusion route coverage passed.
  • Ruff, Python compilation, and git diff --check passed.

Runtime validation

Loaded the cached FLUX.2 Klein 4B Q4_0 GGUF through the real Studio backend with Diffusers 0.39.0.

  • Auto and Low VRAM generated twice at 6 GB without GPU-memory growth. Auto also succeeded at 8 GB and preserved model offload at 12 GB.
  • FP8 switched placement at its measured fit boundary, and the existing Balanced group tier remained unchanged.
  • Unload and reload succeeded. Model offload and streaming produced identical fixed-seed image hashes.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +705 to +706
if isinstance(component, torch.nn.Module):
component.to(onload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed 37aa029 to this branch: Only switch to streaming offload when streaming can hold the plan.

What it changes

refine_memory_plan_for_components sized the policy against every component in pipe.components, but _apply_streaming_offload only installs hooks on transformer* and text_encoder*. Everything else is moved resident with component.to(onload). Two consequences:

  1. When the component over budget is one streaming cannot hook (a VAE, an image encoder), the plan switched to streaming and then onloaded that component whole. A deterministic OOM, where model offload was at least no worse.
  2. model offload holds one component at a time. streaming holds every unstreamed one at once, and nothing checked that sum.

The commit pulls the streamed-component selection into _streamable_components, shared by the planner and the applier, triggers on the largest streamable component, and declines the switch when the resident set does not fit together. _apply_streaming_offload gets shorter as a result: it reuses that selection instead of rebuilding it, so the two can no longer drift apart. Net +34/-12 in diffusion_memory.py, plus one test.

Neither case is reachable with an image family we ship today. refine bails without pipe.transformer, so SDXL never enters, and across flux.1/.2, qwen-image(-edit), z-image, krea-2, lumina-2, hunyuanimage-2.1, hidream-i1 and ideogram-4 there is no image_encoder and every encoder is named text_encoder*, so the resident set is just the tiled VAE. This is a trap for the next family rather than a live bug, which is why it is a guard and not a rewrite.

Before and after

main this PR before 37aa029 after
Oversized text encoder, small GGUF transformer model, OOM during prompt encoding streaming, generates streaming, generates
Oversized component with no granular hook model streaming, then OOMs onloading it whole model, unchanged from main
Resident set over budget only in aggregate model streaming, then OOMs on the resident set model, unchanged from main
Everything fits model model model

Simulation

10,080 load cells, each run through three versions of diffusion_memory.py side by side (main, this PR at 63332ab, and the tree after the fix), with a fake torch and a fake diffusers.hooks so the whole matrix is hardware independent:

[Linux, Windows, WSL2, macOS] x [NVIDIA, AMD discrete, AMD APU, Intel XPU, CPU] x 15 families x 8 VRAM tiers (6 GB to 183 GB) x 5 memory modes, plus the legacy cpu_offload flag. Impossible cells map to the target diffusion_device.py would really build there: macOS GPU is MPS, WSL2 has no ROCm.

Counting cells whose placement leaves more resident than its own budget:

over-budget cells, pre-existing on main: 2501   (explicit balanced/fast overrides, unchanged here)
pr   : 2746 total, +245 introduced, -0 fixed vs main
fix  : 2501 total,   +0 introduced, -0 fixed vs main

The 245 are exactly the two shapes above. The benefit is kept in full: 1078 cells still resolve to streaming, and the only families where the guard reverts the switch are the two synthetic shapes, never a shipping one.

families the guard still streams: qwen-image-edit, hidream-i1, lumina-2, flux.1-dev,
  krea-2, flux.2-klein Q4_0, flux.2-klein bf16, flux.1-dev Q4, z-image, ideogram-4
families the guard reverts:       synthetic-oversized-vae, synthetic-fat-resident-set

112 targeted assertions on top of that, all passing: none / group / sequential are never refined; U-Net families never refine; unified memory (MPS, AMD APU) and CPU never reach the tier at all; missing, zero and negative budgets, a non-dict components, an empty pipeline, zero-parameter modules and a measurement that raises all leave the plan untouched; tied weights are counted once; refinement is idempotent.

diffusers API skew. apply_group_offloading was exercised at four vintages (0.39 full, a build without low_cpu_mem_usage, the earliest shape with no stream controls, and a hypothetical future one without record_stream). No unsupported keyword is ever passed, streams engage only where pinned host memory can be bounded, and a diffusers too old to expose the hook raises the clear granular-offload error instead of retrying the known-OOM path. This matters because the diffusers>=0.39.0 floor in pyproject.toml is conditional on python_version >= '3.10', so a 3.9 install can still be on anything.

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 set_per_process_memory_fraction so an over-cap allocation raises a genuine OutOfMemoryError:

components: transformer 384 MiB, text_encoder 4962 MiB, vae 4 MiB   (budget 4096 MiB)

whole-module offload:  4962 MiB resident, over budget
streaming:                4 MiB after installing hooks
                         33 MiB peak across encoder, transformer and VAE forwards
second generation:       35 MiB peak, no growth

and the guard case, same card and cap:

components: transformer 128 MiB, text_encoder 128 MiB, vae 4802 MiB
planner keeps `model`; had it switched, the VAE alone lands at 4814 MiB against a 4096 MiB budget

Compatibility

  • Payload shape is unchanged. MemoryPlan.as_public_dict() has the same keys before and after, offload_policy stays a bare lowercase token, and estimates is only ever read by .get(), so the two new keys are additive. An older client sees "streaming" where it used to see "model"; the images page renders it through formatResolvedValue, which uppercases any string, and there is no union type or exhaustive switch on policy names anywhere in the frontend. No frontend file changed, so there is nothing browser specific to verify.
  • engages_offload widening to != OFFLOAD_NONE does not flip its answer for any policy that existed before.
  • The sd.cpp path cannot reach the new policy: _memory_policy only ever returns none / group / model / sequential, and offload_flags degrades an unknown policy to no flags rather than raising. Same for video, which calls apply_memory_plan but never refine_memory_plan_for_components.

Tests

studio/backend/tests, same invocation as Backend CI, run twice on this machine: once at 63332ab and once at 37aa029.

63332ab:  67 failed, 18220 passed, 94 skipped, 64 errors
37aa029:  67 failed, 18221 passed, 94 skipped, 64 errors

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 diffusers.pipelines.ltx2 down with it, plus the missing sqlite-vec and OCR extras. They fail the same way on the unmodified branch, and Backend CI is green on all four Python versions here. The one extra pass is the new test.

Full diffusion suites pass clean locally: test_diffusion_memory.py and test_diffusion_backend.py at 229 passed, and test_diffusion_auto_policy.py plus test_sd_cpp_args.py alongside them at 248.

One thing I left alone

_apply_streaming_offload passes low_cpu_mem_usage=True to the block_level transformer as well as to the leaf_level encoders. The diffusers benchmark that introduced the flag (huggingface/diffusers#11106) measured 9.75s to 38.07s on block_level for 35.30 GB to 31.40 GB of host RAM, against 9.48s to 13.72s and 35.11 GB to 22.80 GB on leaf_level, and the upstream guidance is that the flag is best for leaf_level. Restricting it to the leaf hooks looks like a free win, but streaming only engages on low-VRAM hosts, which are also the hosts least able to absorb pre-pinning a large transformer, so the current setting is defensible and the trade needs measuring on the target hardware rather than on a B200. Worth a follow-up, not worth changing blind.

DEFAULT_GROUP_BLOCKS is already 1, which is what diffusers requires with use_stream on, so that part is exactly right.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +538 to +539
if largest_mib <= int(budget):
return plan

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +509 to +511
transformer = getattr(pipe, "transformer", None)
if not isinstance(components, dict) or not isinstance(transformer, torch.nn.Module):
return plan

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 9, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

Note on the red checks, so they are not read as this PR's.

Repo tests (CPU) and pytest tests/security are a main-branch regression. Bisected:

37aa029 (this PR's head, alone)        73 passed
68e5c3f0 (parent of #8194)              1 failed
b8dac29f (#8194)                        5 failed
origin/main                             5 failed

#8193 moved the publish job alongside the build matrix, which breaks test_build_matrix_hands_off_assets_without_release_credentials, and #8194 moved the VirusTotal scan into its own post-publish job, which breaks the four test_virustotal_scan.py::TestWorkflowOrdering cases. PR CI runs on the merge ref, so every open PR inherits it. #8228 already realigns those tests; I checked out its head and the same selection is 76 passed there. Nothing to do on this branch.

The Chat UI failures are Playwright Locator.click 60s timeouts. Two of the three went green on a re-run; the third is re-running. Unsloth UI CI is red on main and on unrelated dependabot branches too, so it is not specific to this change either.

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-platform

Since 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:

ubuntu-latest    243 passed    83s
macos-14         243 passed    87s
windows-latest   243 passed   266s
studio-playwright            success

test_diffusion_backend.py + test_diffusion_memory.py, CUDA-spoofed, no GPU. macOS matters most here: it is the unified-memory path, where plan_diffusion_memory returns none before refinement is ever reached, so the new tier stays unreachable there.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

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".

@danielhanchen
danielhanchen merged commit a08234d into unslothai:main Aug 9, 2026
44 of 52 checks passed
danielhanchen added a commit that referenced this pull request Aug 9, 2026
…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
danielhanchen added a commit that referenced this pull request Aug 9, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants