Skip to content

Studio diffusion: keep the denoiser resident ahead of the text encoders - #15099

Merged
danielhanchen merged 3 commits into
mainfrom
studio-diffusion-planner-monotonic
Oct 24, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-diffusion-planner-monotonic

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

The flat memory planner could keep less of the denoiser on the card when it had more VRAM to work with. For an int8 FLUX.1 load, once the free budget reached about 19.9 GiB, the plan switched to keeping the text encoders resident. Their bytes then came out of the denoiser's room, so one 256 MiB step past that point the resident denoiser dropped from 11420 MiB to 5370 MiB. That is a slower placement, because the denoiser runs every step while the text encoders run once per prompt.

Root cause (diffusion_memory.py)

  1. The flat ladder (elif _group_fits():) ranks "transformer streams, encoders resident" above "encoders streamed", so the plan flips to resident encoders as soon as their floor fits.
  2. refine_plan_from_loaded_weights then subtracts the resident encoder bytes from the denoiser's room (room -= encoders).
  3. The "pin the whole denoiser" and "wide partial" paths only run when the encoders are streamed.

ComfyUI orders it the other way. It loads the text encoder, runs it, and then load_models_gpu for the sampler calls free_memory, which unloads the encoder before the denoiser's partial-load budget is sized, so the denoiser gets priority.

Fix

refine_plan_from_loaded_weights is now a thin wrapper around the old body (renamed _refine_plan_from_loaded_weights).

  • It only acts on an auto group plan with the encoders resident, the transformer streamed, and a known encoder size.
  • In that case it also prices the same plan with the encoders streamed. It takes that version only when it keeps strictly more of the denoiser resident.
  • When it switches, the plan gets a reason line and the estimate denoiser_first_resident_te_dit_mib.
  • The flat plan and the loader decisions are unchanged. Explicit memory modes are untouched.

CPU sweep

  • Coverage: FLUX.1, FLUX.2-klein, FLUX.2, Qwen-Image, Qwen-Image-2.1, Z-Image and Wan; bf16 / fp16 / int8 / fp8 / fp8-stored; speed off / default / max; with and without calibrated activation and a learned peak; 24 / 32 / 48 / 80 / 96 GiB cards; budgets 4 to 80 GiB in 256 MiB steps. That is 323,730 plans.
inversions (resident denoiser shrinks as the budget grows) encoder-residency inversions
main 631 436
this PR 195 0
  • Changed plans: 12,438, across 219 cases. Every one is at or above that case's first inversion budget, and every one keeps strictly more of the denoiser resident (smallest gain 3186 MiB). Every plan below the inversion is byte-identical to main.
  • Int8 FLUX.1 cases: a 24 GiB card at 90% free, 32 GiB at 70%, 48 GiB at 50% and 80 GiB at 30% all keep 11420 MiB resident now, with the encoders streamed.
  • Not fixed here: the 195 remaining inversions are a different pattern, mostly FLUX.2-klein and Z-Image fp8-stored around 12.5 GiB, where whole-module offload gives way to group streaming. Changing that would move plans tuned on small cards, so it is left for a separate change.

GPU check

Qwen/Qwen-Image, int8, B200 capped to 28 GiB free.

  • Sweep on the real loaded pipeline:
    • Main drops from 15117 to 596 MiB resident between 28160 and 28416 MiB free.
    • This PR has no inversion; the 22 plans that changed (28416 to 33792 MiB) are all strictly better.
  • Load at 28 GiB:
    • Main keeps 852 MiB of the denoiser resident.
    • This PR keeps 15629 MiB resident with the encoders streamed. It renders, with peak 21.5 GiB allocated and 24.4 GiB reserved, under the cap.
  • Speed: on an exclusive card, run A/B/A/B, the per-step time was lower for this PR in both pairs (main vs this PR: 0.64 vs 0.36 s and 1.23 vs 1.04 s). The drift between pairs was larger than the gap, so this is directional only.

Tests

  • New tests/test_diffusion_placement_monotonic.py (116 tests): a budget sweep that asserts monotonicity per family, the four int8 FLUX.1 card cases, encoders staying resident when they cost the denoiser nothing, and explicit modes left untouched. 43 of them fail on main.
  • test_whole_transformer_tier_needs_streamed_encoders asserted the old behaviour. It is renamed ..._streams_resident_encoders and now asserts 6922 MiB resident with the encoders streamed.
  • Placement / memory / measured-placement / auto-placement suites pass.

Not covered

  • No int8 FLUX.1 render on GPU: the cached FLUX.1 checkpoint here has no transformer weights.
  • The sweep's component sizes for families other than FLUX.1 int8 are estimates; the GPU sweep used real loaded sizes.
  • No ROCm, Windows or multi-GPU run.

Once the flat plan's companion floor fits, it keeps the text encoders
resident and refine_plan_from_loaded_weights takes their bytes out of the
denoiser's room. Just past that budget fewer denoiser MiB stayed resident
than one 256 MiB step below it (int8 FLUX.1: 11420 -> 5370 MiB at about
19.9 GiB of budget; Qwen-Image measured on a B200 at 28 GiB free: 852 MiB
instead of 15629 MiB).

The refinement now also prices the same group plan with the encoders
streamed and takes it whenever it keeps more of the denoiser resident, as
ComfyUI frees the text encoder for the sampler. The denoiser runs every
step, the encoders once per prompt. Plans where the encoders cost the
denoiser nothing, and every plan below the inversion budget, are unchanged.
@danielhanchen danielhanchen self-assigned this Oct 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T07:35:45.036940Z 84845fa Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 84845fa41e

ℹ️ 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 35ec100 into main Oct 24, 2026
25 of 41 checks passed
@danielhanchen
danielhanchen deleted the studio-diffusion-planner-monotonic branch October 24, 2026 08:39
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 24, 2026
…the streamed floor (unslothai#15129)

Follow-up to unslothai#15099. A budget sweep of the flat planner still showed 195
places where more free VRAM picked a slower placement. All of them sit
at the same step, about 12288 to 12544 MiB free, where the
streamed-encoder group floor (10400 MiB) starts to fit:

- **Below the floor**, the only tier is whole-module offload (`model`),
which runs the whole denoiser on the card while it is called.
- **Above it**, the plan becomes `group` with the transformer streamed,
keeping 0, 4704 or 5216 MiB of the denoiser resident and streaming the
rest every step.

The real FLUX.2-klein-4B bf16 pipe shows the same flip: `model` up to
12288 MiB free, then `group` with nothing resident from 12544.

| model / precision | inversions |
|---|---|
| FLUX.2-klein bf16 | 60 |
| FLUX.2-klein fp16 | 60 |
| FLUX.2-klein fp8-stored | 15 |
| Z-Image fp8-stored | 60 |

ComfyUI loads as much of the denoiser as fits beside its inference
reserve for each sampling call (`load_models_gpu`, `partially_load`), so
at 12.25 GiB the whole klein denoiser would be resident there, which
matches the `model` plan.

### Changes

- `prefer_whole_module_offload(pipe, refined)` in `diffusion_memory.py`,
called in `diffusion.py` right after `refine_plan_from_loaded_weights`.
- **When it applies:** in auto mode, the plan is a streamed group plan,
the denoiser is plain bf16 (not torchao, packed or fp8-stored), every
component would have fit under the streamed floor (so whole-module
offload still holds the denoiser whole), and the refined plan does not
already pin the whole denoiser.
- **What it does:** keeps whole-module offload and adds a reason line
plus the `whole_module_kept_below_floor_mib` estimate. Everything else,
including every plan below the floor, is unchanged.
- **Out of scope:** fp16, packed, fp8-stored and torchao denoisers keep
the current ladder (see below).

### Results

FLUX.2-klein-4B bf16 (real weights), 1024x1024, 4 steps, exclusive B200
with the free-memory cap probe, 3 interleaved process repeats x 2
renders.

| arm | plan | render, median (min to max) | s/step | peak alloc |
|---|---|---|---|---|
| 12.00 GiB free | model | 0.345 s (0.337 to 0.377) | 0.028 | 7.83 GiB |
| 12.25 GiB free, main | group, nothing resident | 0.595 s (0.594 to
0.600) | 0.170 | 3.04 GiB |
| 12.25 GiB free, this PR | model | 0.336 s (0.335 to 0.341) | 0.029 |
7.83 GiB |
| 12.25 GiB free, learned peak, main | group, 5471 of 7393 MiB resident
| 0.727 s (0.724 to 0.757) | 0.170 | |
| 13.5 GiB free, learned peak, main | group, 6751 MiB resident | 0.624 s
(0.621 to 0.629) | 0.145 | |

- The two `model` arms at 12.00 vs 12.25 GiB differ by about 3% (A/A).
Whole-module offload is 1.77x faster than streaming at the same budget,
and 1.7 to 1.9x faster even with most of the denoiser pinned resident.
- Peak allocation stays within the budget.

**CPU sweep:** the planner budget sweep from unslothai#15099.
- Plans below each case's first inversion are byte-identical to main.
- 810 plans changed, all in the 60 bf16 cases and all at or above the
inversion.
- The bf16 inversions go to 0. The other 135 are now reported as
hardware-dependent rather than fixed.

### Why bf16 only

The fp16 evidence pointed the other way. On a Kaggle T4 (fp16, stock
diffusers, not Studio), a 4-step render took 23.2 s with whole-module
offload and 9.3 s streaming (one run each, no A/A). Stock diffusers
copies the weights back to the CPU after every call and Studio does not,
so this probably overstates the gap, but it is not enough to move
small-card fp16 plans. Z-Image Turbo fp8 on the real torchao path is
already monotonic (0.415 / 0.382 / 0.342 / 0.341 s at 10.75 / 11.0 /
13.25 / 13.5 GiB).

### Tests

- New cases in `tests/test_diffusion_placement_monotonic.py`:
  - the bf16 inversion budgets switch to whole-module offload;
- fp16 / packed / fp8-stored / torchao denoisers, explicit modes and
fully pinned plans are left alone;
  - plans below the floor are unchanged.
- Placement / memory / measured-placement / auto-placement suites: 487
passed.

### Not covered

- No run on a real 12-16 GB bf16 consumer card. The B200 has PCIe 5 and
fast compute, so the size of the gain on slower cards is not measured.
- Studio's own path on a T4, so fp16 is left unchanged.
- Z-Image and klein fp8-stored timing on a real pipe.
- Qwen-Image-2.1 int8 (torchao turns `model` into streaming at load).
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.

1 participant