Skip to content

Studio diffusion: compile group-offloaded blocks below their hooks on the deferred profile and for planned-offload video - #14528

Merged
danielhanchen merged 4 commits into
mainfrom
studio-diffusion-group-offload-compile
Oct 21, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-diffusion-group-offload-compile

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Under group offload (memory_mode=balanced, block streaming through diffusers' group offload hooks), some denoisers compiled straight through the hooks. Studio wraps GroupOffloadingHook.pre_forward / post_forward in torch.compiler.disable, so every compiled block split into three pieces: two real graph breaks per block class, and each block ran as two resumed frames. compile_below_offload_hooks exists to stop exactly this: it compiles the block's own forward below the hook, so the hook stays eager outside the compiled region. It was not engaging in two cases.

  1. Image, deferred profile (FLUX.2-klein, Z-Image). With speed_mode unset and no transformer quant, renders 1-2 run eager and the compile lands on render 3. That same deferred step installs the per-arch block forward fusions (diffusion_arch_patches: Flux2TransformerBlock.forward, Flux2SingleTransformerBlock.forward, ZImageTransformerBlock.forward, ...), but only after group offload had already hooked every block at load. So each hook still held the class's definition-time forward. compile_below_offload_hooks only accepted the live class forward (_is_original_forward), found nothing to move and moved 0 blocks. The blocks then compiled through the hooks. A side effect: under the hooks the fused forwards never ran either. Qwen-Image was not affected because its patch targets _modulate, not forward.
  2. Video, planned group offload (Wan). video.py only moved the compile below the hooks when a layer split fell back to a hooked placement (not speed_offload). When the offload was planned, the denoiser compiled through the hooks every time. The image backend already moves the compile whenever the denoiser landed hooked.

Changes

  • diffusion_block_graph.py: new _own_forward(fn, module) helper. It matches a hook's captured forward when that forward is either the live class forward or the class's own definition-time forward (same __qualname__ / __module__ as a class in the MRO), and returns the live forward bound to the module. Foreign bound methods are still refused. compile_below_offload_hooks now compiles that live forward and uses it as the compile guard's eager fallback, so the patched forward runs below the hook, as in the immediate profile. install_block_graphs uses the same lookup, and its restore puts back the hook's original forward.
  • video.py: move the compile below the hooks whenever _video_denoiser_hooked(pipe), matching the image backend.

Results (B200, Studio's real path through load_pipeline + generate, 5 prompts, 1024x1024 / Wan 832x480x17, 8 steps, balanced)

family real hook graph breaks (compile render) dynamo frames unique graphs recompiles prompts 2+ output
FLUX.2-klein-base-4B (deferred, render 3) 2 -> 0 4 -> 2 2 -> 2 0 -> 0 within eager floor
Z-Image-Turbo (deferred, render 3) 2 -> 0 4 -> 2 2 -> 2 0 -> 0 within eager floor
Wan2.1-T2V-1.3B (render 1) 2 -> 0 4 -> 2 2 -> 2 0 -> 0 bit-identical, all 5 prompts
Qwen-Image (tiny, deferred) 0 -> 0 (already engaged) 1 -> 1 0 -> 0 unchanged

The remaining unimplemented counter entries (Custom metaclass SDPBackend read in diffusers' attention dispatch) do not split the graph and are unchanged by this PR.

Accuracy, pixel PSNR vs the eager (speed_mode=off) render of the same prompt and seed, on the compiled renders 3 / 4 / 5:

  • FLUX.2-klein: base 44.6 / 37.4 / 49.7 dB, head 44.3 / 36.4 / 47.3 dB
  • Z-Image-Turbo: base 38.3 / 30.8 / 46.3 dB, head 36.1 / 30.6 / 47.0 dB

Head now also runs the per-arch addcmul fusions under the hooks, as the immediate profile already did, so the two are not expected to be bit-identical to base. Renders 1-2 (eager) are bit-identical.

Speed and memory, exclusive B200, 20 steps, 1024x1024, two runs per arm (base, head, base2, head2). Wall s/step per prompt includes text encode and VAE:

compile render (p3) steady p5 peak alloc p3-5
FLUX.2-klein base / base2 3.23 / 3.53 0.323 / 0.317 8586 / 8205 MiB, both runs
FLUX.2-klein head / head2 2.13 / 1.54 0.349 / 0.318 8586 / 8205 MiB, both runs
Z-Image base / base2 0.86 / 0.98 0.265 / 0.257 9083 to 10183 MiB (varies run to run)
Z-Image head / head2 0.81 / 0.76 0.257 / 0.252 9083 to 10215 MiB (varies run to run)
Wan2.1-1.3B 832x480x33 base / base2 (compile render is p1) 1.31 / 1.30 0.205 / 0.212 15205 MiB
Wan2.1-1.3B 832x480x33 head / head2 (compile render is p1) 0.84 / 0.85 0.207 / 0.213 15205 MiB, outputs bit-identical to base

The compile render gets cheaper: one frame per block class to trace instead of two resumed frames. FLUX.2-klein's p3 drops by about half. Steady-state s/step does not move outside the A/A spread, so this is a correctness and compile-time fix, not a per-step speedup. Peak VRAM is unchanged. Compiled outputs are deterministic: base and base2 match, and head and head2 match, bit for bit.

Tests

  • New: test_compile_below_the_hook_engages_after_a_class_patch_lands_on_the_hooked_forward, test_block_graphs_find_the_compute_below_a_hook_that_predates_a_class_patch, test_own_forward_refuses_a_foreign_bound_method (test_diffusion_block_graph.py), plus the planned-offload cases of test_a_layer_split_fallback_moves_the_compile_below_the_offload_hooks (test_video_backend.py). All fail on main and pass here.
  • Related suites, base vs head: test_diffusion_block_graph.py, test_diffusion_offload_step_graphs.py, test_h3_stream_compile_and_top_group.py, test_diffusion_layer_split.py and test_diffusion_arch_patches.py pass on both (130 passed). test_video_backend.py, test_diffusion_backend.py, test_diffusion_speed.py, test_diffusion_multigpu.py and 6 more have the same 7 failures on main and here, and those failures are not related to this PR.

Not covered

  • Real-weight Qwen-Image (tiny model only; it already engaged on main).
  • Wan 2.2 MoE, HunyuanVideo-1.5 and LTX under planned offload also take the compile-below path now but were not run.
  • MiniMax-H3 keeps its own copy of the original-forward check and is unchanged.

…hooks on the deferred profile and for planned-offload video

The deferred profile installs the per-arch block forward fusions on render 3, after group offload hooked every block
at load, so each hook still held the definition-time forward. compile_below_offload_hooks only matched the live class
forward, moved nothing, and the blocks compiled through the hooks: a real graph split at each torch.compiler.disable'd
pre / post forward (FLUX.2-klein, Z-Image). Match the hook's captured class forward too and compile the live (patched)
forward below the hook, as the immediate profile does. The block graph layer uses the same lookup.

The video backend only moved the compile below the hooks when a layer split fell back to a hooked placement; a
planned group offload (Wan balanced) compiled through the hooks. Move it whenever the denoiser landed hooked, as the
image backend does.
@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 ✅ Completed 2026-10-21T16:45:11.541616Z e0517ed Manual request
🔒 Security Review ⚠️ Failed 2026-10-21T15:38:32.517187Z
We couldn’t complete this review. Comment @codex security review to try again.
ad7c18c 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: ad7c18c474

ℹ️ 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 1638 to 1639
fn = guard.wrap(fn, live, transformer)
guard.restores.append(lambda ref = target, f = original: setattr(ref, "forward", f))

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 Keep the patched forward after compile fallback

When an offload hook predates a class-level forward patch and the lazy compile raises a handled compile-time error, _CompileGuard.fail executes this restore and resets the hook reference to the definition-time original, not the patched live forward supplied as the eager fallback. The failing invocation retries through live, but later blocks in the same denoiser call—and all later calls—silently revert to the old implementation, producing a mixed numerical path and disabling the per-architecture patch precisely on the fallback path. Restore live (or retain a permanent eager wrapper around it) in this case.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed: the guard's restore put back the definition-time forward the hook captured, so after a handled compile failure the later blocks dropped the class patch. Fixed in e597b92: the restore now installs the live forward (the same one the guard uses as its eager fallback), so a compile failure keeps the per-arch patch running eager below the hook. test_a_compile_failure_below_the_hook_keeps_the_class_patch failed before and passes now.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: e597b9253d

ℹ️ 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 +9492 to 9496
if _video_denoiser_hooked(pipe):
# Below the offload hooks (as the image backend), whether the speed layer planned the offload or a split
# fell back to a hooked placement: compiled through them, each block splits at the hook's
# torch.compiler.disable'd pre / post forward.
compile_pipe_below_offload_hooks(pipe, logger)

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 Preserve LTX's STG adapter below offload hooks

For a planned-offload LTX-2/LTX-2.5 load, this newly calls compile_pipe_below_offload_hooks after the family hook has installed install_stg_compile_adapter on every block's _compiled_call_impl (video_ltx2.py:1123-1163). The mover discards that callable and recompiles the live class forward, preserving only the unrelated restride wrapper (diffusion_block_graph.py:1635-1646), so STG once again passes a 0-D all_perturbed tensor into a data-dependent branch. This reintroduces graph breaks and loses the adapter's special recompile-limit fallback; preserve or reapply the STG adapter when moving these blocks.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed: moving the compile below the hooks replaced the block's _compiled_call_impl and with it LTX-2's STG adapter, so the 0-d all_perturbed tensor reached the data-dependent branch again. Fixed in 93f79c0: the adapter now carries a rewrap hook, and compile_below_offload_hooks re-applies any such family adapter around the moved compile (alongside the existing restride wrapper), keeping both the bool conversion and the recompile-limit fallback. test_compile_below_the_hook_reapplies_a_family_adapter failed before and passes now; the LTX-2 / LTX-2.5 test files show the same 11 pre-existing failures before and after.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 93f79c0c5c

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: e0517ed3d4

ℹ️ 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 3649767 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-group-offload-compile branch October 21, 2026 17:12
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