Skip to content

Studio diffusion: VAE OOM under a component split, expanded timesteps in the CFG routers, and test fixes - #14420

Merged
danielhanchen merged 8 commits into
mainfrom
studio-diffusion-verify-fixes
Oct 21, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-diffusion-verify-fixes

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

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.

Under a component split the VAE decodes on a secondary card while the
denoiser's CUDA graphs and resident offload groups stay on the primary.
Step (a) dropped those graphs and released those groups, counted that as
freed, and retried the same untiled decode on the secondary card, which
ran out of memory again before the tiled rung. A failed re-pin was also
deferred against the VAE's card instead of the groups' own.

Graph handles and resident-group modules are now filtered to the VAE's
card, like the torchao and component moves already are, and
release_resident_groups takes an optional device filter.
On a CUDA host an unset text_encoder_quant also plans the hosted FP8 Wan
text encoder, so the load fetched two artifacts and the exact single-fetch
assertion failed. The test is about the denoiser fetch carrying the load's
cancel event: pin text_encoder_quant off so it checks only that.
On diffusers 0.39 and 0.40 enable_cache does not drop the child-registry
list an earlier uncached render cached, so the cached render failed with
"No context is set". Production already calls
_invalidate_child_registry_cache after enable_cache; the test helper now
does the same.
pytest.importorskip("diffusers") succeeds on the lazy top-level module,
then importing AutoencoderKLWan can raise RuntimeError (a broken
bitsandbytes), which aborted collection of the whole run. Catch ImportError
and RuntimeError and skip the module, as the other diffusion tests do.
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 _bitwise_equal returned
False for two equal timesteps. CFG batching then missed three times in a
row and turned itself off for Wan, and CFG-parallel predictions never
matched.

The byte view now goes through _as_bytes, which takes a dense copy when
the flattened tensor still has a non-unit stride. Bitwise semantics are
unchanged: equal NaN bits match, -0.0 and 0.0 do not.
@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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 ⚠️ Failed 2026-10-21T02:40:39.926596Z
We couldn’t complete this review. Comment @codex review to try again.
3fa2292 New commits
🔒 Security Review ⚠️ Failed 2026-10-21T01:04:58.791022Z
We couldn’t complete this review. Comment @codex security review to try again.
c29e265 PR opened
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: c29e2659dc

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

make_selection drops ordinals torch cannot address and cards below the
primary's capability, both read from the real host, so on any one-GPU
host (a ROCm APU or a single CUDA card) every fake [0, 1] selection
collapsed to None. Pin both in the autouse fixture, add a two discrete
ROCm card case, and skip the sm_89 fp8 compile test on HIP torch, where
the capability is a gfx version and Studio declines torchao fp8.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1875e56c2f

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

_rocm_linux_apu_os_room_outside_pool gave any unified-memory snapshot
the halved OS reserve once torch was a ROCm build, so an mps or cpu
snapshot read on a ROCm host (the unified load override tests on the
Strix Halo runner) was budgeted as if it were the GTT pool. Check the
snapshot's device first.

The prompt upsampler tests that name a CUDA torch now also pin
__version__, which a ROCm wheel tags with +rocm, and the warm fixture
pins one card so a multi-GPU host does not decline with placement.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 90a1df2879

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

[skip ci]
@danielhanchen
danielhanchen merged commit bfaed19 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-verify-fixes branch October 21, 2026 03:55
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…(fused FLUX RoPE, CFG batching, Blackwell native attention, BF16 small DiTs) (#14566)

## Summary

An audit of every Studio image and video optimization switch (all 144
`UNSLOTH_DIFFUSION_*` / `UNSLOTH_VIDEO_*`
names, the other optimization env vars the diffusion and video modules
read, and the non-env defaults such as the
speed tier, attention backend, step caches and CFG batching) against two
rules: an optimization should be on by
default when it costs no accuracy, and where ComfyUI picks a setting by
default, Studio follows it.

Almost everything already passes. Most switches are kill switches for
optimizations that are already on, and the
rest are on through measured auto gates. Five defaults change here, plus
one follow-up to the bf16 rule, one commit each, so any of them can be
dropped
on its own:

1. **Fused FLUX RoPE now runs on NVIDIA CUDA too** (Linux, WSL
included). Bit-identical, 18.7% faster per eager
FLUX.2-klein-4B step on a B200. ComfyUI runs FLUX RoPE through
comfy-kitchen's fused `apply_rope` by default.
2. **Small DiTs keep bf16 by default while they fit** (FLUX.2-klein 4B,
Z-Image, FLUX.3-klein). FP8 / INT8 on
these sizes measured up to LPIPS 0.129 (klein-4B) and 0.191
(Z-Image-Turbo) against bf16. INT8 is still picked
when bf16 would offload. The rule is scoped by resolved base repo:
FLUX.2-klein 9B and base 9B (an 18.2 GB bf16
transformer, not measured here) keep the quantized default, mirrors
included.
3. **The automatic static step skip is now only on `speed_mode=max`.**
It is lossy (gated at LPIPS <= 0.05 on
`default`, <= 0.10 on `max`, #12652), and ComfyUI skips no steps by
default. Unset and `default` speed no longer
   skip steps, including the deferred "from the third image" path.
4. **CFG batching now also runs for a resident denoiser**, as ComfyUI
does by default (`calc_cond_batch`), behind
the existing per-shape timing gate (on only where one batched step,
timed end to end with its prediction,
merge, snapshot and verification, is at least 8% faster than two plain
calls). An explicit `speed_mode=off`
keeps one branch per call (`UNSLOTH_DIFFUSION_CFG_BATCH=force`
overrides). The trial now
runs once per shape on step 1 with its outputs discarded, so a render
never mixes paths and the same seed twice
gives the same image. On a compiled denoiser the doubled shape compiles
only inside a shape's first render: 0
   graph breaks and 0 recompiles on follow-up prompts.
5. **On Blackwell, `auto` attention keeps native SDPA where torch
already dispatches cuDNN.** Same kernel, bitwise
identical, without the cuDNN pin's per-call wrapper (0.4% to 22% per
eager SDPA call, equal compiled). ComfyUI also
   defaults to native.

6. **Small DiTs kept bf16 compile from render 1.** With speed unset, the
INT8 default for these models was compiled
from render 1. Keeping them bf16 (change 2) moved them onto the deferred
profile, which compiles on the third
image, a follow-up prompt. They now compile from render 1, as the INT8
load did, so follow-up prompts compile
nothing. The eager reference renders 1-2 are given up for these loads
only. An explicit speed is honoured, and
   every other dense load keeps the deferred profile.

Two switches stay off on purpose: the NVFP4 runtime
(`UNSLOTH_NVFP4_DIFFUSION`, waiting on the hosted NVFP4 repos)
and background compile (`UNSLOTH_DIFFUSION_BG_COMPILE`, which breaks
same-seed repeatability).

## 1. Fused FLUX RoPE on NVIDIA CUDA

| Switch | Before | After | Accuracy evidence | Measured gain |
|---|---|---|---|---|
| `UNSLOTH_DIFFUSION_FUSED_ROPE` | `auto` = ROCm only | `auto` = ROCm,
or NVIDIA CUDA on Linux | Bit-identical by construction (same fp32 math,
FMA contraction off, one rounding). On a B200: FLUX.2-klein-4B 1024x1024
renders have the same pixel sha256 with and without it (2 seeds). The
tiny FLUX.1 pipe through the real `STAGE_LOAD` registry is identical, as
is the tiny FLUX.2 transformer, eager and under CUDA graph replay |
FLUX.2-klein-4B eager bf16 denoiser step, 1024x1024, B200: see the table
below |

FLUX.2-klein-4B, bf16, eager, one denoiser step at 1024x1024 (4096 image
tokens), real weights, B200. Arms are
interleaved in one process (stock, fused, stock) over 6 rounds of 5
forwards each. The A/A row is the spread between
the two stock arms.

| Arm | median ms / step | min - max |
|---|---|---|
| stock RoPE (arm A) | 49.74 | 49.43 - 49.84 |
| stock RoPE (arm B, A/A) | 49.87 | 49.47 - 50.06 |
| fused RoPE (new default) | 40.51 | 40.09 - 40.69 |

A/A spread 0.26%; fused is 18.7% faster per eager step (exclusive B200
lease, torch 2.13.0+cu130, diffusers
0.41.0.dev0). 400 fused RoPE calls per two 4-step renders, and both
renders have the same pixel sha256 as stock.

The step speedup applies wherever a FLUX block runs eager:
- the first two renders of an unset dense load, before the deferred
`default` profile compiles on the third;
- GGUF FLUX on the default tier, where only the dequant chain is
compiled and the block stays eager;
- loads that cannot compile.

Compiled blocks are unchanged: the wrapper checks
`torch.compiler.is_compiling()` first and takes stock RoPE there.

Scope and gates:
- Applies only to bf16 / fp16 CUDA tensors with no grad, the layouts the
kernel checks. Anything else, including a
kernel error, takes the stock function. The first failed launch (a JIT,
driver or PTX error) turns the fused path
off for the rest of the load, so a failing kernel is not retried on
every call.
- Windows and macOS keep stock RoPE. A Triton JIT failure on Windows
would be retried on every call, and that path
  is unmeasured.
- ROCm behaviour is unchanged: the ROCm branch is evaluated first,
exactly as before.
- fp16 FLUX.2 on NVIDIA keeps its own patch
(`UNSLOTH_DIFFUSION_FLUX2_FUSED_ROPE`, installed first). The new auto
  path never stacks on top of it.
- Fused AdaLN stays opt-in everywhere. It is not bit-identical (LPIPS
0.004) and showed no speedup.
- Kill switch: `UNSLOTH_DIFFUSION_FUSED_ROPE=0` restores stock diffusers
RoPE.

### Every placement, RoPE commit alone: speed, peak memory, follow-up
prompts

All of these go through Studio's real backend (`load_pipeline` +
`generate`), one process per arm. Old = a worktree
at the merge base (77e6eaf), new = this branch. Each process runs 5
prompts at one resolution:
- different prompt text and lengths (7 to 32 words);
- seeds 11 / 22 / 33 / 44 / 55;
- guidance 4.0 on prompts 1-3 and 2.5 on prompts 4-5 (video: 5.0 then
3.0).

Models: FLUX.2-klein-base-4B, a CFG model, at 1024x1024 with 8 steps,
and Wan2.1-T2V-1.3B at 832x480, 17 frames,
8 steps. Counters per prompt:
- torch._dynamo graph breaks;
- new compiled graphs (recompiles);
- Studio's CUDA graph capture counter
(`diffusion_cuda_graph.capture_generation`);
- fused RoPE kernel calls.

| Model / placement | Fused RoPE calls | Pixels old vs new | Peak alloc
MiB (old / new) | Peak reserved MiB (old / new) | Prompts 2+ graph
breaks / new graphs / CUDA graph captures (old = new) |
|---|---|---|---|---|---|
| klein-base, unset speed, auto quant (hosted int8, compiled from prompt
1) | 0 | identical 5/5 | 12523 / 12523 | 13490 / 13490 | 0 / 0 / 0 |
| klein-base dense, unset speed (eager renders 1-2, deferred compile on
render 3), resident | 1600 | identical 5/5 | 16142 / 16142 | 17128 and
17048 (two old runs) / 17048 | 4 / 2 / 1, all on prompt 3 |
| klein-base dense, `speed_mode=default`, resident | 0 (compiled) |
identical 5/5 in 2 of 2 A/A pairs | 16110 / 16110 | 16788 / 16788 | 0 /
0 / 0 |
| klein-base dense, `memory_mode=balanced` (group offload, streamed) |
950 | identical 5/5 | 10122 / 10122 | 11308 / 11308 | 10 / 2 / 1, all on
prompt 3 |
| klein-base dense, `memory_mode=low_vram` (model offload) | 1600 |
identical on the eager prompts 1-2 | 8054 / 8054 | 8682 / 8702 | 4 / 2 /
3 (prompt 3, plus 1 capture each on prompts 4 and 5) |
| Wan2.1-1.3B, unset speed (default tier), resident | not installed
(video) | same path | 17689 / 17689 | 18484 / 18484 | 0 / 0 / 0 |
| Wan2.1-1.3B, `memory_mode=low_vram` | not installed | same path |
11125 / 11125 | 11208 / 11208 | 0 / 0 / 0 |

Reading the table:
- **Peak VRAM:** allocated peaks are identical old vs new in every
placement. The fused kernel writes one output
tensor where stock RoPE builds fp32 intermediates, so it cannot raise
the peak. Reserved peaks are within the
allocator's own run-to-run spread: two old runs of the same config
differ by 80 MiB, and the one +20 MiB new
  cell is on prompts 4-5, where the kernel does not run.
- **Host RAM:** steady RSS during rendering is within +-50 MiB, in both
directions, across arms. Max RSS during
load varies by up to 0.9 GiB between old and new even on the video arms,
where old and new run the same code, so
  that column is noise.
- **Follow-up prompts:** the flip adds 0 graph breaks, 0 recompiles and
0 CUDA graph captures in every placement.
The counts on prompts 2+ are identical old vs new and come from existing
defaults; see "Existing defaults that
  recompile or re-capture" below.
- **Pixel spread on compiled prompts:** the compiled prompts 3-5 of the
low_vram pair differ, and so did one old
  `default` run. That is run-to-run spread of the compiled tier itself:
  - the old `default` arm differed from a second old `default` process;
  - the new and old A/A pairs were identical 4/4;
- the RoPE kernel never runs inside compiled code (0 calls on those
prompts).
- **s/step:** the host was saturated during these runs (load average 800
to 1200, NVML timeouts), so the
end-to-end s/step from these shared-card runs are not usable as a speed
result. They are kept in
`outputs/defaults_e2e_shared`. The speed claim rests on the
exclusive-card transformer-step A/B above. The
  exclusive end-to-end matrix ticket never got a card and was cancelled.

Placements not run, and why the RoPE flip cannot change them:
- **MPS, CPU, sd.cpp, Windows:** the gate requires a CUDA tensor and
NVIDIA CUDA torch on Linux, and the sd.cpp
  engine router is not touched.
- **ROCm:** the ROCm branch is unchanged and evaluated first.
- **Multi-GPU:** the kernel launches under
`torch.cuda.device(x.device)`, so a replica or companion on another card
  gets the same kernel on its own device. This was not run on two cards.
- **Small-card routing:** 4 GB / 8 GB and small-host routing are planner
decisions that read no RoPE state, so they
are unchanged. On a real 8 GB card the planner picks the group / model
offload placements measured above; here
  those placements were forced with `memory_mode`.

## 2. Small DiTs keep bf16 by default while they fit

What each default picks for a small model (FLUX.2-klein-4B,
Z-Image-Turbo, FLUX.3-klein) when the user sets nothing:

| Default | Before | After |
|---|---|---|
| Unset transformer precision, bf16 fits the card | INT8 (hosted ConvRot
or on the fly), FP8 only if INT8 fails its probe | bf16 |
| Unset precision, bf16 would offload (small card, `low_vram`) | INT8 |
INT8 (unchanged: the model cannot fit otherwise) |
| Small-host route (fp16-only GPU, small host RAM) | int8 storage only
when the dense load does not fit host RAM | unchanged |
| Ada FP8 unit-scale GEMM (`UNSLOTH_DIFFUSION_FP8_UNIT_SCALE`) | only
changes how FP8 runs once FP8 is chosen; never chooses it | unchanged |
| Speed tiers (`off` / `eager` / `default` / `max`) | never choose a
quant; a quantised DiT forces `default` | unchanged |
| MPS / ROCm native int8 | explicit request only | unchanged |
| Text encoder | FLUX.2-klein and Z-Image keep bf16; FLUX.3-klein auto
int8 ConvRot (BFL's ComfyUI templates; LPIPS 0.017-0.023 mean) |
unchanged, listed for review |

GPU check through Studio's backend, 5 prompts per process, B200, unset
precision:

| Model | Old: scheme / peak alloc MiB | New: scheme / peak alloc MiB |
New pixels | Prompts 2+ (new) |
|---|---|---|---|---|
| FLUX.2-klein-base-4B, 1024^2, 8 steps | int8 / 12523 | bf16 / 16142 |
equal to the dense bf16 reference (the same sha256 as the
`transformer_quant=none` arms) | the deferred-profile compile on prompt
3, as for any dense load |
| Z-Image-Turbo, 1024^2, 8 steps | int8 / 15218 | bf16 / 21880 | bf16 |
compile on prompt 4 when guidance turns CFG on, and one more graph on
prompt 5. Old does the same (3 + 1 new graphs) |
| FLUX.2-klein-base-4B, `memory_mode=low_vram` | int8 | int8 / 6115 |
int8 | 0 / 0 / 0 |

This rule conflicts with the "never slower, never more VRAM"
requirement. Keeping bf16 costs +3.6 GiB (klein-4B)
and +6.5 GiB (Z-Image-Turbo) of peak VRAM against the old INT8 default,
and gives up INT8's GEMM speed. It only
applies where bf16 already fits, so no load starts to offload or fail.
On the compiled `default` tier,
FLUX.2-klein-base-4B at 1024x1024 renders in 1.41 s vs 1.08 s with INT8
(shared card, indicative). An unset load also
now takes the deferred profile (eager renders 1-2, compile on the third
image; see "Existing defaults" below). It is
its own commit so it can be dropped on its own.


### 2b. Small DiTs kept bf16 compile from render 1

The coordinator's decision on the bf16-vs-no-recompile conflict: a load
that auto kept bf16 by the small-DiT rule
resolves `speed_mode=default` from render 1. Only an unset speed on a
compile-eligible host does this, and the deferred
profile stays for everything else. B200, Studio backend in process,
unset speed and precision, 4 prompts, and prompt 4
repeats prompt 1's seed:

| Model | Branch before this commit (deferred) | This commit |
|---|---|---|
| FLUX.2-klein-base-4B, 1024 | prompts 1-3 eager; prompt 4 compiles (2
graphs, 1 capture) | prompt 1 compiles (2 graphs, 1 capture); prompts
2-4 add 0 graphs, 0 captures; prompt 4 == prompt 1 |
| Z-Image-Turbo, 1024 | prompts 1-3 eager; prompt 4 compiles (2 graphs,
1 capture) | prompt 1 compiles (2 graphs, 1 capture); prompts 2-4 add 0
graphs, 0 captures (new text lengths take the CUDA graph's eager
fallback, no re-capture); prompt 4 == prompt 1 |

The accepted cost of the accuracy rule, against the old INT8 default on
a B200:
- **Speed:** FLUX.2-klein-base-4B on the compiled tier renders at
1024x1024 in 1.41 s bf16 vs 1.08 s INT8.
- **Memory:** peak VRAM is +3.6 GiB (klein-4B) and +6.5 GiB
(Z-Image-Turbo).

Both apply only where bf16 fits on the card, and INT8 is still picked
when bf16 would offload. Test:

`test_diffusion_pipeline_prequant.py::test_a_small_dit_kept_bf16_compiles_from_render_1`
covers three cases:
- the small-DiT rule resolves `default` and does not defer (this case
fails without the commit);
- an explicit `off` is honoured;
- another bf16-kept family still defers.

## 3. Automatic static step skip: only on `speed_mode=max`

The automatic static step skip (#12652) skips a fixed set of denoiser
steps for profile-listed upstream repos at 20+
default steps. It was gated at mean LPIPS <= 0.05 on `default` and <=
0.10 on `max`, and also engaged with the
deferred profile from the third image of an unset load. That is a lossy
default, and ComfyUI skips no steps unless
a caching node is added.

| Speed | Before | After |
|---|---|---|
| unset (including the deferred profile from the third image) | skip on
(LPIPS <= 0.05 class) | no skip |
| `default` | skip on (LPIPS <= 0.05 class) | no skip |
| `max` | skip on (LPIPS <= 0.10 class) | unchanged |
| an explicit `transformer_cache=static` request, and the
`UNSLOTH_STATIC_SKIP_*` knobs | honoured | unchanged |

`UNSLOTH_DIFFUSION_AUTO_STEP_SKIP=0` still turns the `max` auto skip
off. Video follows the same rule (the tests cover
Wan2.2-TI2V-5B). The diff is `AUTO_STATIC_SKIP_TIERS = (max,)` in
`diffusion_cache.py`. 9 tests fail
on the merge base and pass here, including
`test_deferred_default_tier_never_auto_skips` and
`test_default_speed_never_auto_skips_on_wan_5b`.

## 4. CFG batching for a resident denoiser

A guided step calls the denoiser twice (cond, then uncond). ComfyUI
batches both into one call by default whenever
memory allows, resident or not. Studio batched only a streamed
(offloaded) denoiser. The router now also arms for a
resident denoiser of the listed stateless classes (FLUX.1, FLUX.2,
Qwen-Image, Wan). The existing per-shape timing
gate is kept: batching stays on only where one doubled call is at least
8% faster than two plain calls. Where it
loses (for example FLUX.2-klein at 1024x1024, -1.8% on an exclusive
B200), the shape stays plain.

Three fixes go with it:

- **The trial no longer mixes paths inside a render.** It used to time
live steps, so render 1 ran some steps plain
and later ones batched, while render 2 read the verdict and took a
different path. Now steps 1-2 of every render
run plain, and step 2's own pair is timed. If needed, the trial runs
once per shape on step 2's arguments: two
plain pairs interleaved with two batched steps, outputs discarded,
fastest of each compared. A batched sample
times everything the live path does: predicting the second branch,
merging, snapshotting, the doubled call, the
  split and the second-call verification. Steps 3+ of every
  render of a shape take the verdict's path.
- **A slow card pays nothing.** A resident pair of 0.25 s or more is
compute-bound: one doubled call cannot win 8%
there, so the shape stays plain with no extra calls. On Kaggle T4s the
ungated trial added 19 s to the first
FLUX.2-klein-4B render, 17 s on klein-9B and 44 s on Wan2.1, all to
conclude "no gain". B200 winners measure
0.03-0.06 s per pair. Offloaded denoisers are never gated, because they
save an upload per step.
- **One slow sample cannot decide the verdict.** The old gate compared
one plain sample with the faster of two
  batched ones.
- **Compiled denoisers add nothing after warm-up.** A doubled batch is a
new input shape, so it compiles a second
graph per compiled block. A B200 audit of main found this happening,
along with graph breaks traced inside the
  router. The rules are now:
- a resident compiled denoiser stays plain (two calls upload nothing, so
batching would only add a compile);
- an offloaded compiled denoiser batches from its trial render on, so
the batch-2 graph compiles inside the same
    first-render warm-up;
- a shape judged before a later compile (the deferred profile, or
#14528's compile below the offload hooks)
    stays plain after it;
- a doubled call that still compiles a graph on a follow-up render ends
batching for the load after that render;
- a router reached while Dynamo traces passes straight through, so none
of its own code enters a graph.
  This is checked at install and at the start of every render.
- **Model offload stays declined**, as before. diffusers rebuilds the
model-offload hooks around the denoiser between
renders, which takes the router out of the forward slot after render 1.
On Wan2.1-1.3B `low_vram` a first version
  of this change batched render 1 only.
- Rebased onto main, which now has #14420's stride-safe byte compare for
Wan's `t.expand(batch)` timestep. Before
  that, every batched Wan step counted as a miss.

Determinism and accuracy. Each probe below is one process and one load
on a B200, bf16, resident, at the same prompt
and seed. It renders with the router (twice), then with the router
uninstalled, then with a re-armed router (a
fresh trial):

| Model, size | Trial verdict | Router render 1 == render 2 | Re-armed
== router | Batched vs two calls |
|---|---|---|---|---|
| FLUX.2-klein-base-4B, 512x512 | batched (0.046 vs 0.063 s per pair) |
identical | identical | bitwise equal |
| FLUX.2-klein-base-4B, 1024x1024 | varies by run (0.084 vs 0.157, and
0.084 vs 0.084 off) | identical | identical | bitwise equal (also forced
on) |
| Wan2.1-T2V-1.3B, 832x480, 17 frames, eager | off (0.120 vs 0.123) |
identical | identical | plain path, bitwise equal |
| Wan2.1-T2V-1.3B, forced to batch | batched, 14/14 hits, 0 misses |
identical | identical | LPIPS 0.019 mean / 0.023 max |

Before the stride fix, the forced Wan probe missed 3 of 3 batched steps,
and render 1 differed from render 2 for the
same seed (LPIPS 0.016 eager, 0.028 on `default`).

Speed and memory, exclusive B200, CFG batching on vs off
(`UNSLOTH_DIFFUSION_CFG_BATCH=0`), arms interleaved off / on
/ on / off, one process each, 20 steps, median wall of prompts 2-5:

| Model, size | Trial verdict (on arms) | s per render off (A/A) | s per
render on | on vs off | Peak alloc MiB off / on |
|---|---|---|---|---|---|
| FLUX.2-klein-base-4B 512x512, eager | batched | 0.726 / 0.739 | 0.701
/ 0.621 | -9.8% | 13924 / 13983 |
| FLUX.2-klein-base-4B 1024x1024, eager | plain (no gain) | 1.625 /
1.625 | 1.629 / 1.639 | +0.6% | 14984 / 14984 |
| Wan2.1-T2V-1.3B 832x480x33, `default` | plain (no gain) | 3.538 /
3.488 | 3.399 / 3.442 | -2.6% | 17769 / 17769 |

The first run of this A/B showed the plain-verdict shapes 2.5-3.5%
slower with the router than with it off. A shape
that stays plain still recorded a prediction template on every
second-branch call. That compares small tensors
bytewise, a host sync per step. An off shape now skips it. The table
above is the re-run, and the plain-verdict rows
are within the A/A spread (+0.6% and -2.6%). The batched row is 9.8%
faster for 59 MiB more peak allocation.

Peak allocated VRAM with batching on, from the all-defaults matrix:
Wan2.1-1.3B on `default` 17723 vs 17689 MiB
(+34 MiB). FLUX.2-klein-base-4B at 1024 is unchanged within 2 MiB,
because the peak there is set outside the denoiser
call. The doubled call is attempted only when the card has room for
twice the activations a plain call allocated. An
out-of-memory turns the shape plain for that render. On a compiled tier
the doubled shape is one more graph on the
first prompt (Wan `default`: 2 graphs on prompt 1 instead of 1), and
nothing on prompts 2+. CUDA-graph tiers displace
the router, so the klein unset profile from the third image runs as
before.

Compiled and streamed placements. These use the audit's harness
(`verify_b200_arm.py`, VRAM capped to simulate a
small card), with batching on vs off on the rebased branch, B200. There
are 4 prompts, and prompt 4 repeats prompt 1's
seed:

| Case | Batching | Extra graphs (prompt 1 / prompts 2-4) | Graph breaks
| Same seed repeats | s/step on vs off | Peak alloc MiB on / off | LPIPS
on vs off |
|---|---|---|---|---|---|---|---|
| Wan2.1-1.3B `default` (compiled), streamed, 8 GiB cap | batched, 116
hits, 0 misses | +1 / 0 | 0 / 0 | identical | 0.083 / 0.110 | 2393 /
2393 | 0.022-0.062 mean, 0.069 max |
| Wan2.1-1.3B `default` (compiled), resident | declined (compiled and
resident) | 0 / 0 | 0 / 0 | identical | 0.069 / 0.070 | 17689 / 17689 |
0 (bitwise) |
| FLUX.2-klein-base-4B eager, streamed, 5 GiB cap | batched, 76 hits | 0
/ 0 | 0 / 0 | identical | 0.149 / 0.288 | 2810 / 2389 | 0 (bitwise) |

The compiled streamed Wan row is main's existing behavior: main already
batches offloaded denoisers, and the tree
before this fix gives the same pixels and graph counts. Its LPIPS
against two calls (up to 0.069 at 30 steps) is the
doubled batch's bf16 numerics. Before this fix, the resident compiled
Wan row compiled the batch-2 graph on prompt
1 for a trial that then found no gain.

### Multi-GPU: Kaggle T4x2 (two real T4s)

One whole kernel per notebook, both cards visible, old (main 3649767)
and new arms run one after another in the
same kernel. Four prompts, and prompt 4 repeats prompt 1's seed. T4 has
no bf16, so the dense models run fp16, and
the attention change does not apply (SM75). Placements come from
Studio's own multi-GPU planner. Times are wall
seconds per render on Kaggle's T4s.

| Model, placement (old = new) | Arms | Pixels old vs new | Peak MiB per
card (cuda:0 / cuda:1) old ; new | s per render, render 1 / renders 2-4
mean | CFG batching (new) | Prompts 2+ graphs / breaks / captures |
|---|---|---|---|---|---|---|
| FLUX.2-klein-base-4B, 1024, unset: layer split over both cards, text
encoder on cuda:1 | old x2, new x2 (final branch) | identical, 4/4 per
arm | 7448 / 9141 ; 7448 / 9141 | old 39.7, 41.8 / 36.0, 36.7 ; new
42.5, 41.8 / 36.6, 36.7 | off: compute-bound (4.3 s pair), no extra
calls | 0 / 0 / 0 |
| same, branch before the gate | old x2, new x2 | identical | 7448 /
9141 ; 7449 / 9701 on render 1 | old 39.7, 41.1 ; new 59.9, 58.8 on
render 1 | trial ran, no gain | 0 / 0 / 0 |
| same, both cards selected explicitly | old, new (before the gate) |
identical | 7682 / 8907 ; 7683 / 9467 on render 1 | old 41.5 ; new 60.0
on render 1, then equal | CFG-parallel declined (layer split); trial
ran, no gain | 0 / 0 / 0 |
| FLUX.2-klein-base-9B, unset: denoiser on cuda:1, text encoder streamed
| old, new (before the gate) | identical | 2978 / 9220 ; 2979 / 9976 on
render 1 | old 119.1 / 78.5 ; new 136.5 / 78.5 | trial ran, no gain (9.2
s pair; gated now) | 0 / 0 / 0 |
| Wan2.1-T2V-1.3B, 832x480x17, unset (automatic placement: one card,
group offload) | old x2, new (before the gate) | identical | 9799 / 0 ;
9799 / 0 | old 622, 601 / 535, 546 ; new 667 / 543 | trial ran, no gain
(21.4 s pair; gated now) | 0 / 0 / 0 |
| Wan2.1-T2V-1.3B, both cards selected: CFG-parallel armed | old, new
(final branch) | identical | 9799 / 6169 ; 9799 / 6169 | old 424 / 358 ;
new 399 / 344 | not armed (CFG-parallel holds the forward slot) | 0 / 0
/ 0 |

Reading it:
- **Placement:** no multi-GPU placement changes. On T4x2, main's auto
already keeps the klein-base-4B / 9B denoisers
dense ("dense transformer kept unquantized", fp16), so the small-DiT
bf16 rule changes nothing there. The 9B
  checkpoint's denoiser is 8352 MiB at fp16 and sits whole on cuda:1.
- **CFG-parallel:** it never arms on a layer-split denoiser. Where it
does arm, CFG batching steps aside.
- **The gate:** the gated branch's klein-4B rows match old within the
A/A spread (old's two first renders differ by
5%), with identical peaks. The klein-9B and automatic Wan rows ran
before the gate. Their plain pairs (9.2 s and
21.4 s) are far above 0.25 s, so the gated branch runs them exactly as
old.
- **Pre-existing:** with both cards selected, Wan's CFG-parallel arms
but its replica is never built (0 parallel steps,
old and new alike). Selecting both cards still roughly halves Wan's
s/step (11 vs 22 s) through component
  placement. Neither is changed here.

## 5. Blackwell: native SDPA when torch already dispatches cuDNN

With a speed tier active, `auto` attention pinned diffusers'
`_native_cudnn` backend on NVIDIA SM80+. The code comment
said about 1.18x. Re-timed on a B200 (torch 2.13.0+cu130), one process
with interleaved arms on an exclusive card:

| Shape (bf16) | Kernel native picks | Native vs pinned output | Eager
SDPA ms native / pinned | Compiled SDPA ms native / pinned | Native A/A
spread |
|---|---|---|---|---|---|
| FLUX.2-klein-4B 1024x1024 (1, 24, 4608, 128) | cuDNN sm100 flash fprop
| bitwise equal | 0.201 / 0.213 | 0.254 / 0.250 | 0.95% |
| FLUX.2-klein-4B 512x512 (1, 24, 1536, 128) | cuDNN sm100 | bitwise
equal | 0.054 / 0.066 | 0.117 / 0.116 | 1.3% |
| FLUX.2-klein-4B 1024, CFG batch 2 | cuDNN sm100 | bitwise equal |
0.393 / 0.426 | 0.459 / 0.463 | 3.3% |
| Wan2.1-1.3B 832x480x17 (1, 12, 7800, 128) | cuDNN sm100 | bitwise
equal | 0.327 / 0.328 | 0.392 / 0.391 | 7.2% |
| Wan2.1-1.3B 832x480x33 (1, 12, 14040, 128) | cuDNN sm100 | bitwise
equal | 0.927 / 0.946 | 1.024 / 0.983 | 2.8% |
| Qwen-Image 1024 (1, 24, 4352, 128) | cuDNN sm100 | bitwise equal |
0.194 / 0.206 | 0.253 / 0.258 | 2.0% |

Native already runs the same cuDNN kernel. The pin adds only its
per-call `sdpa_kernel` wrapper: 0.4% to 22% slower
eager, and within +-4% compiled (mixed sign, inside the A/A spread). End
to end on the compiled `default` tier,
FLUX.2-klein-base-4B 1024x1024 at 20 steps, 3 interleaved processes per
arm: native 1.277 s vs pinned 1.287 s
pooled median per render (native A/A spread 3%), so equal. A side
effect: the `sdpa_kernel` context was the source of
the Dynamo graph breaks ("custom metaclass with `__getattribute__`" on
`torch.nn.attention._SDPBackend`) on every
compiled image and video tier. With native SDPA on Blackwell they are
gone: 0 graph breaks on every prompt of every
arm in the matrix below, against 2 to 4 on prompt 1 before.

At head_dim 256 native picks FLASH on the same card, so the rule asks
torch at load time
(`torch._fused_sdp_choice` at each DiT head dim and the run dtype) and
leaves native only when the answer is cuDNN for
every head dim. The probe shape does not hide a different real-call
choice: on a B200 (torch 2.14.1, cuDNN 9.24),
a sweep of `torch._fused_sdp_choice` over bf16 / fp16, head dims 64 /
128 / 256, 1-40 heads, self and cross
attention (query 1 to 32760 tokens, key 77 to 32760), with no mask, bool
and float masks and causal, found no call
where the cuDNN pin could run and native picked another kernel. Where
native picks Flash or Efficient (head_dim 256,
a single-token query), the pinned cuDNN backend cannot run at all. The
cuDNN pin stays for:
- pre-Blackwell cards (SM80 / SM89 / SM90), which were not re-timed
here;
- a head dim where native would not run cuDNN (256 here), or an unknown
one;
- fp32;
- a probe that cannot run;
- an explicit `attention_backend=cudnn`;
- `UNSLOTH_DIFFUSION_BLACKWELL_NATIVE_ATTN=0`.

The auto pick is a `str` subclass equal to `"_native_cudnn"`, so the
MiniMax-H3 arch override and the preinstall step
see the same value as before.

## All five on together: old (merge base) vs new

This matrix ran before the branch was rebased onto main 3649767: old
is 77e6eaf and new is the five commits on
top of it. The compiled and streamed CFG table in change 4 ran on the
rebased branch.

Studio's backend in process, one process per arm, B200 (shared card), 5
prompts with different text and lengths,
seeds 11-55, and a guidance change on prompts 4-5. "Unset" means no
speed or precision given. `free8` holds all but
8 GiB of the card before the load (a small-card placement). Times are
wall seconds on a host with load average near
1000, so they are indicative only. The exclusive tables above carry the
speed claims.

| Config | Old: speed / quant / attention / placement | New: speed /
quant / attention / placement | Median s, prompts 2-5, old / new | Peak
alloc MiB old / new | Prompts 2+ breaks / graphs / captures, old ; new |
CFG batching (new) | LPIPS old vs new, mean / max |
|---|---|---|---|---|---|---|---|
| FLUX.2-klein-base-4B 1024, unset | default / int8 / cuDNN / resident |
off / bf16 / native / resident | 1.42 / 11.17 (includes the third-image
compile; prompt 5: 1.58 / 1.06) | 11498 / 16018 | 0/0/0 ; 0/2/1 |
batched 14 steps | 0.0468 / 0.0723 |
| FLUX.2-klein-base-4B 512, unset | default / int8 / cuDNN / resident |
off / bf16 / native / resident | 0.43 / 11.28 (includes the third-image
compile; prompt 5: 0.38 / 0.69) | 10436 / 14189 | 0/0/0 ; 0/2/1 |
batched 14 steps | 0.0418 / 0.1037 |
| FLUX.2-klein-base-4B 1024, `speed_mode=default` | default / int8 /
cuDNN / resident | default / bf16 / native / resident | 1.08 / 1.41 |
11498 / 15117 | 0/0/0 ; 0/0/0 | - | 0.0460 / 0.0751 |
| FLUX.2-klein-base-4B 1024, unset, 8 GiB free | default / int8 / cuDNN
/ group offload | default / int8 / native / streaming | 2.32 / 2.45 |
2365 / 2397 | 0/0/0 ; 0/0/0 | - | 0.0001 / 0.0001 |
| FLUX.2-klein-base-4B 1024, `low_vram` | default / int8 / cuDNN / model
offload | default / int8 / native / model offload | 49.20 / 39.59 | 6115
/ 6147 | 0/0/4 ; 0/0/4 | - | 0.0002 / 0.0003 |
| Z-Image-Turbo 1024, unset | default / int8 / cuDNN / resident | off /
bf16 / native / resident | 9.84 / 13.15 (both recompile on prompts 4-5)
| 15218 / 21880 | 4/4/1 ; 0/6/1 | - | 0.0500 / 0.1282 |
| Wan2.1-T2V-1.3B 832x480x17, unset (`default`) | default / bf16 / cuDNN
/ resident | default / bf16 / native / resident | 3.93 / 4.36 | 17689 /
17723 | 0/0/0 ; 0/0/0 | batched 35 steps | 0.0211 / 0.0593 |
| Wan2.1-T2V-1.3B, `low_vram` | default / int8 / cuDNN / model offload |
default / int8 / native / model offload | 65.51 / 20.14 | 11125 / 11125
| 0/0/0 ; 0/0/0 | - | 0.0000 / 0.0000 |

Reading it:
- **Graph breaks:** 0 on every prompt of every new arm. Old arms had 2-4
on prompt 1, and Z-Image 3 more on prompt 4.
- **Prompts 2+ recompiles and captures:** this matrix predates change
2b.
- 0 / 0 in every new arm except two. The unset FLUX.2-klein and Z-Image
loads are now dense bf16 (change 2), so
they take the existing deferred profile: eager renders 1-2, then compile
on the third image (2 graphs and 1
capture for klein; 6 graphs for Z-Image, which old INT8 also recompiled,
4 graphs). The old INT8 default was
forced to the compiled tier from prompt 1, so klein had 0 on prompts 2+
before. This is the one place where
two requirements conflict: small models stay bf16, and prompts 2+ never
compile.
- `low_vram` (model offload) re-captures one CUDA graph every render,
old and new alike.
- **Accuracy vs old:**
- klein and Z-Image differ from old by the INT8 -> bf16 change (LPIPS
0.04-0.05 mean), with the new renders the
    bf16 reference.
- Wan `default` differed by CFG batching (0.021 mean / 0.059 max) in
this run. This matrix ran before the
compiled-denoiser rule; a resident compiled Wan now declines batching
and matches old bit for bit (table in
    change 4).
- The offloaded and `low_vram` arms run the same precision as old, and
stay within 0.007.
- **Peak VRAM:** unchanged within 34 MiB wherever the precision is
unchanged. +3.6 GiB (klein) and +6.5 GiB
  (Z-Image) where bf16 replaced INT8 (change 2).
- **Speed:** klein on the compiled `default` tier is 1.41 s vs 1.08 s
per render, bf16 vs old INT8 (change 2). The
  same cost shows on the unset path once its profile has compiled.

## Existing defaults that recompile or re-capture on follow-up prompts

1. **Unset dense image speed: the deferred profile compiles on the third
image.** By design, so renders 1-2 are the
bit-identical eager reference. The compile lands on prompts 3-4 (2 new
graphs and 1 CUDA graph capture for
FLUX.2-klein). Small DiTs kept bf16 by change 2 no longer take this
path: they compile from render 1 (change 2b).
   Other dense loads (FLUX.1, FLUX.2-dev, Qwen-Image, ...) keep it.

Before this PR, the graph breaks here came from the `sdpa_kernel`
context ("custom metaclass with
`__getattribute__`" on `torch.nn.attention._SDPBackend`). On Blackwell
they are gone with change 5; on other
   cards they remain.
2. **`memory_mode=low_vram` (model offload) on the compiled image tier
re-captures one CUDA graph every render**
(1 capture on each of prompts 2-5, old and new). Model offload
re-uploads the denoiser each render.
3. **Z-Image recompiles when guidance turns CFG on and on the next
prompt length.** Old INT8 default: 3 graphs and
1 capture on prompt 4 and 1 graph on prompt 5. New bf16 default: the
deferred compile on prompt 4 (5 graphs and 1
   capture) and 1 graph on prompt 5.
4. **The compiled image tiers are not pixel-reproducible across
processes.** With the same seeds, one old `default`
process differed from two others. Eager FLUX.2-klein 512x512 also
differed across processes (LPIPS 0.0001)
while staying bit-identical within a process. Same-seed repeats inside
one process are identical on every path
   measured here.

## What stays off, and why

- **Decided off:**
- the NVFP4 runtime (`UNSLOTH_NVFP4_DIFFUSION`), until the hosted NVFP4
repos are public;
- `UNSLOTH_DIFFUSION_BG_COMPILE=1`. Render 1 runs eager and render 2
compiled, so the same seed no longer repeats.
- **Lossy, or a tolerance class instead of exact:**
  - fused AdaLN (LPIPS 0.004, no speed);
  - int8 MiniMax-H3 VAE;
- explicit static-skip knobs, and the auto static skip below `max`
(change 3);
  - NVFP4 protect steps (must be measured per model);
- torchao's own inductor config (renders differ between processes, and
TF32 is process-wide).
- **No gain:**
- per-block CUDA graphs on streamed or model-offloaded denoisers
(copy-bound, extra VRAM);
  - the NVFP4 zero buffer (strictly slower);
  - NVENC export (larger files, slower than libx264 on many-core hosts);
- the on-disk conditioning cache (the in-memory prompt cache is already
on);
- cuDNN attention on eager renders 1-2: 6.4% slower than native on a
B200 at 1024x1024 (53.1 vs 49.9 ms per
    step).
- **Platform, unverifiable here:**
  - MLX engine;
  - MPS fp16 compute for Z-Image;
  - sd.cpp on MPS;
  - sd.cpp text encoder on Metal (ggml-metal can abort an LLM encoder);
  - W8A8 on the native-quant path on ROCm and the Windows torchao stub.

## Tests

Each new test fails on the merge base and passes here:

- **RoPE:** `tests/test_diffusion_rocm_fused.py` covers:
  - NVIDIA Linux auto (RoPE only, bf16 and fp16);
  - Windows / macOS / no-GPU torch stay stock;
  - the kill switch;
  - fp16 FLUX.2 not stacking;
- a GPU test that runs a tiny FLUX.2 transformer and checks the fused
kernel ran and matches stock bit for bit.

The parity snapshot pins the new host gate off, as it does the other
host gates.
- **Small DiTs:**
-
`test_diffusion_pipeline_prequant.py::test_the_bf16_rule_names_only_the_measured_families`
covers the five kept
    models, plus FLUX.1-dev, FLUX.2-dev and Qwen-Image as not kept;
- the family freeze fixture is regenerated (its diff is exactly the four
new rows).
- **Static skip:** `test_diffusion_step_skip_defaults.py` and
`test_video_static_skip.py`, 9 failing on base, 103
  passing here.
- **CFG batching:** `test_diffusion_cfg_batch.py`, 35 tests (including
#14420's; one runs only with a GPU). The new ones
  are:
- a resident denoiser is armed by default, and model offload is
declined;
- with a fake device timer, render 1 (which runs the trial) and render 2
are bit-identical. The call pattern
shows the trial only inside step 1, and the result equals the plain-only
or batched-only path;
- compiled denoisers are seen in every form (`_compiled_call_impl`,
Studio's compile markers, a compiled forward
    below a group-offload hook);
- a resident compiled denoiser stays plain, including when the compile
lands after install;
  - an offloaded shape judged before a compile stays plain after it;
  - an offloaded compiled denoiser batches from its trial render;
- a doubled call that compiles on a follow-up render ends batching after
that render;
- a router traced by Dynamo (`fullgraph=True`) passes straight through;
- a compute-bound resident pair skips the trial (no extra calls), a fast
one runs it, and an offloaded one is
    never gated;
  - one slow plain sample does not flip the verdict;
- a shape that stays plain records no prediction (no per-step host
sync).
- on CUDA latents (GPU only), step 2's pair is timed and batching
engages from step 3 only when the doubled
call paid, with the same image; CPU latents have no device timer, so the
trial judges untimed.
- a doubled call that wins alone but whose snapshot and verification
overhead makes the whole step slower stays
    plain;
- an explicit `speed_mode=off` declines batching resident and offloaded
(unset, `default` and `max` still arm;
`force` overrides), and both the image and video loaders pass the
requested speed.
- **Review follow-ups:** `test_diffusion_rocm_fused.py` checks that a
failing RoPE launch runs once per load, then
stock (bit-identical output), and that the next load re-arms it.
`test_diffusion_pipeline_prequant.py` checks that
the small-DiT rule covers the 4B klein ids and skips the four 9B ids
(vendor and mirror), and that a load hands
  the decider its resolved base.
- **Attention:** `test_diffusion_attention_blackwell.py`, 11 tests, all
erroring on base. They cover:
  - the auto pick still reads as `_native_cudnn`;
  - Blackwell plus a cuDNN dispatch leaves native;
  - an explicit cudnn request is pinned;
- the pin stays for Hopper, head_dim 256, fp32, the kill switch, an
unknown head dim and no target;
  - mixed head dims need cuDNN at every one;
  - an unaskable probe keeps the pin.
- **Suites, no GPU visible:**
- the 7 test files this PR touches give 297 passed, 13 skipped, 1 failed
with no GPU, and 310 passed, 1 failed
with a GPU. The failure is `test_teardown_survives_a_later_eager_layer`,
which fails the same way on the merge
base with the same file set (`test_diffusion_pipeline_prequant.py`
running first leaves process-global patch
    state) and passes when its file runs alone;
- after merging origin/main 94135ef into the branch, the 25 touched
test files (the 22 below plus
`test_diffusion_multigpu.py`, `test_diffusion_block_graph.py` and
`test_diffusion_attention_install.py`) gave
2207 passed, 87 skipped and 2 failed.
`test_an_imported_old_kernels_is_not_papered_over` fails on that main
too, and `test_teardown_survives_a_later_eager_layer` is the known
order-dependent failure;
- the 17 test files that touch CFG batching or attention selection give
1718 passed, 6 skipped;
- one run showed a failure in
`test_diffusion_backend.py::test_unload_cancels_pipeline_construction`
that moved
between parameters across runs and passed in the next full run and in
isolation. It waits on 2-5 s thread
    timeouts, on a host with load near 1000;
- after the rebase onto main, the same files plus
`test_diffusion_multigpu.py` and `test_diffusion_block_graph.py`
gave 2201 passed, 87 skipped and 2 failed. The two failures
(`test_teardown_survives_a_later_eager_layer` and

`test_diffusion_attention_install.py::test_an_imported_old_kernels_is_not_papered_over`)
also fail on main /
    the merge base;
- before the rebase, the 22 test files the five commits touch (RoPE,
parity, prequant, family freeze, step skip, video static skip,
CFG batching, attention, diffusion and video backend, MiniMax-H3) gave
2031 passed, 74 skipped, 1 failed. The
failure is
`test_diffusion_rocm_fused.py::test_teardown_survives_a_later_eager_layer`.
It fails the same way on
the merge base with the same file set (order-dependent process-global
patch state), and passes when its file
    runs alone;
- the RoPE commit's full diffusion / video / sd.cpp run had the same 5
pre-existing failures on base and head.
- **GPU (B200, through the GPU queue):**
  - the RoPE, prequant and parity GPU tests;
  - the in-process CFG probes above;
  - the exclusive SDPA kernel probe;
  - the all-defaults matrix.

## Not verified

- **RoPE launch failure:** the one-failure latch is tested with a
launcher that raises, not a real JIT failure on an
  unsupported card or driver.
- **Pre-Blackwell attention:** no Hopper, Ada or Ampere card was
re-timed. Change 5 is gated to SM100+, so those keep
  the cuDNN pin unchanged.
- **CFG batching off Blackwell:** not measured on smaller cards (L4, T4,
consumer RTX). The per-shape trial decides
  there, and its result is not measured.
- **Speed:** the end-to-end matrix ran on a shared card with host load
near 1000, so its times are indicative only.
The exclusive tables (RoPE step, SDPA kernel, CFG on / off) carry the
speed claims.
- **Platforms:** multi-GPU ran only on Kaggle T4x2 (two T4s, fp16,
SM75), not on two bf16 or Blackwell cards. No
ROCm, MPS, CPU, Windows or WSL run. ROCm and MPS paths are unchanged by
construction:
the RoPE ROCm branch is evaluated first, and the attention change needs
NVIDIA SM100+.
- **Small cards:** no real 4 GB / 8 GB card. Small-card placements were
simulated with `--leave-free-gib 8` (a
ballast tensor) and `memory_mode=low_vram`. In the `free8` pair the
planner picked group offload for old and
streaming for new, both INT8. Pixels match (LPIPS 0.0001) and peak
allocation is within 32 MiB. Free memory moves
on a shared card, so this placement difference is not attributed to the
change.
- **Studio server:** no render went through the HTTP server, only
through the backend in process.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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