Repository navigation
Studio diffusion: turn on the measured-safe optimizations by default (fused FLUX RoPE, CFG batching, Blackwell native attention, BF16 small DiTs) - #14566
Conversation
UNSLOTH_DIFFUSION_FUSED_ROPE auto now also engages the bit-identical Triton RoPE kernel for FLUX.1 / FLUX.2 bf16 and fp16 loads on NVIDIA CUDA under Linux, as ComfyUI does by default through comfy-kitchen. It was ROCm only. Compiled blocks keep stock RoPE, Windows and macOS keep stock, fused AdaLN stays opt-in, and UNSLOTH_DIFFUSION_FUSED_ROPE=0 restores the old path.
An unset transformer precision on FLUX.2-klein, Z-Image and FLUX.3-klein loads now keeps the released bf16 denoiser when it fits the card, as Lumina-2 and HiDream already do. INT8 / FP8 change image detail on these sizes (FP8 vs bf16 LPIPS 0.065 mean on FLUX.2-klein-4B and 0.103 on Z-Image-Turbo). INT8 is still picked when bf16 would offload, and an explicit precision is honoured.
The automatic static step skip (#12652) is lossy (mean LPIPS up to 0.05 on the default interval, 0.10 on max) and ComfyUI never skips steps by default. Auto now engages it only on the opt-in max tier. The default tier, an unset speed and the deferred profile on the third image render every step. An explicit static request and UNSLOTH_DIFFUSION_AUTO_STEP_SKIP=0 behave as before.
…e per shape ComfyUI batches the cond and uncond branches of a guided step by default whether or not the model is resident. Studio only batched a streamed (offloaded) denoiser. Arm the router for resident denoisers of the listed stateless classes as well, keeping the per-shape timing gate: batching stays on only where one doubled call beats two plain calls by 8%. The timing gate used to time live steps, so a render could run some steps plain and later steps batched, and render 1 (timed) took a different path from render 2 (verdict). Now steps 1-2 of every render run plain; step 2's own pair is timed, and a resident pair of 0.25 s or more is compute-bound and stays plain with nothing extra run (on a T4 the trial alone added ~17 s to the first FLUX.2-klein render). Otherwise the trial runs once per shape on step 2's arguments: two plain pairs interleaved with two doubled calls, outputs discarded, fastest of each compared. Steps 3+ of every render of a shape take the verdict's path, so the same seed twice in one process gives the same image. A shape that stays plain records no prediction (that compared small tensors bytewise, a host sync per step). Compiled denoisers: a doubled batch is a new input shape and compiles a second graph per compiled block, so that is allowed only inside a shape's trial render. A resident compiled denoiser stays plain (nothing to save); an offloaded compiled one batches from its trial render on; a shape judged before a later compile (the deferred profile, a compile moved below an offload hook) stays plain after it. A doubled call that compiles a graph on a follow-up render ends batching for the load after that render, and a router reached while Dynamo traces passes straight through. Model offload stays declined: diffusers rebuilds its hooks around the denoiser between renders, which takes the router out of the forward slot after render 1. Measured on a B200, same seed: FLUX.2-klein-base-4B resident batched renders are bitwise equal to plain at 512 and 1024 px (exclusive card: 9.8% faster at 512 px, +59 MiB peak; no gain and plain at 1024 px). Compiled streamed Wan2.1-T2V-1.3B (8 GiB cap, the case an audit flagged): one extra graph on prompt 1 only, 0 graph breaks, nothing on prompts 2-4, same seed repeats bit-identically, 0.083 vs 0.110 s/step. Resident compiled Wan: declined, identical to off with no extra graph. UNSLOTH_DIFFUSION_CFG_BATCH=0 keeps two calls.
…it already runs cuDNN On a B200 with torch 2.13, native SDPA dispatches the same cuDNN sm100 kernel the auto pin selects, bitwise identical, at every Studio DiT shape measured (FLUX.2-klein 512 / 1024 px, batch 1 and 2, Wan2.1-1.3B 17 and 33 frames, Qwen-Image 1024). The pin only adds its per-call sdpa_kernel wrapper. On an exclusive card, per SDPA call it is 0.4 to 22% slower eager and within +-4% compiled (mixed sign, A/A up to 7%); FLUX.2-klein-4B compiled default-tier renders measure equal (1.277 s native vs 1.287 s pinned, pooled over 3 interleaved processes each). ComfyUI also defaults to native. So on SM100+ the auto pick leaves native when torch's own dispatch choice is cuDNN for every DiT head dim at the run dtype. At head_dim 256 native picks FLASH on the same card, so that, unknown head dims, fp32, pre-Blackwell cards and an unaskable probe keep the cuDNN pin, as does an explicit cudnn request. The auto pick is a str subclass equal to "_native_cudnn", so callers that compare it (the H3 arch override, preinstall) are unchanged. UNSLOTH_DIFFUSION_BLACKWELL_NATIVE_ATTN=0 keeps the pin.
With speed unset, the INT8 default for FLUX.2-klein, Z-Image and FLUX.3-klein was forced onto the compiled tier from render 1, so follow-up prompts compiled nothing. Keeping those loads bf16 (the accuracy rule) moved them onto the deferred profile, which compiles on the third image: a follow-up prompt. A load that auto kept bf16 by the small-DiT rule now resolves speed_mode=default from render 1, as the INT8 load did; 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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
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. |
|
@codex review |
3 similar comments
|
@codex review |
|
@codex review |
|
@codex review |
…A variant The fake FLUX.2 loop runs on CPU tensors, so the trial has no device timer and plain_pair_s stays None even when a GPU is visible. Assert that, and add a CUDA-only test that times the step 2 pair and checks batching engages from step 3 only when the doubled call paid, with the same image. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ea1168e5a4
ℹ️ 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".
| q = torch.zeros(1, 2, 256, int(head_dim), device = device, dtype = dtype) | ||
| return int(torch._fused_sdp_choice(q, q, q)) |
There was a problem hiding this comment.
Probe the native backend using real attention geometry
The probe uses only unmasked self-attention with B=1, two heads, and 256 tokens, but SDPA dispatch also depends on query/key lengths, head count, masks, and causality. On a Blackwell pipeline where this synthetic call selects cuDNN but a real long, cross-attention, or masked DiT call selects Flash/Efficient, _native_dispatches_cudnn returns true and apply_attention_backend removes the cuDNN pin, potentially changing seeded outputs and reintroducing the large performance regression this pin was intended to prevent. Keep the pin unless the actual call geometry is verified, or guard dispatch at call time.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
We swept torch._fused_sdp_choice on a B200 (torch 2.14.1+cu130, cuDNN 9.24) over the geometries real DiT calls use: bf16 and fp16, head dims 64/128/256, 1 to 40 heads, batch 1-2, self attention up to 32760 tokens, cross attention (4096 x 512, 4096 x 77, 333 x 1000, single-token queries), with no mask, bool and float masks, and causal. In each case we also ran the call under sdpa_kernel([CUDNN_ATTENTION]). There were 0 cases where the cuDNN pin could run and native picked another backend. Native picked Flash or Efficient only where cuDNN itself cannot run (head_dim 256 and single-token queries), and there the pinned _native_cudnn backend would raise instead of falling back. Torch's SM100 priority puts cuDNN first, so geometry only matters through cuDNN eligibility, and that is the same check the pin depends on. Removing the pin therefore cannot move a call off cuDNN onto Flash/Efficient. The per-head-dim load-time probe already keeps the pin wherever native would not choose cuDNN (head_dim 256).
| if _AUTO_ON.get(env, False) and _is_rocm(): | ||
| return True | ||
| return _AUTO_ON_NVIDIA.get(env, False) and _is_nvidia_linux() |
There was a problem hiding this comment.
Disable fused RoPE after the first failed NVIDIA launch
Auto now installs this Triton path on every Linux NVIDIA CUDA build based only on whether Triton imports, without checking that the current GPU/toolchain can JIT and launch the kernel. If compilation or launch fails—for example on an unsupported architecture or driver/PTX combination—the wrapper catches the exception but leaves the patch armed, so every RoPE invocation retries the same failing JIT before falling back to stock; a render can therefore incur repeated compilation failures instead of a one-time fallback. Cache the failure and disable the fused path for the remainder of the load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. The first failed fused RoPE launch now turns the fused path off for the rest of the load, so later calls go straight to stock RoPE (bit-identical output). The next load turns it back on. A new test checks for exactly one launch attempt across repeated calls and the re-arm after reload.
| b_args, b_kwargs = merge_branches(first, second, batch) | ||
| graphs = _graph_count() | ||
| # interleaved, fastest of each: one slow sample cannot decide the verdict | ||
| for _ in range(_BATCHED_SAMPLES): | ||
| t0 = time.perf_counter() |
There was a problem hiding this comment.
Time CFG batching's preparation and verification overhead
The trial constructs the merged batch before starting its timer and never measures the production path's _predict, merge_branches, _snapshot, or second-call _matches work. The latter clones and byte-compares every predicted tensor and can force device synchronization, so for the newly enabled resident path—especially small or low-resolution forwards—a measured 8% kernel win can still make the complete batched step slower than two plain calls. Time the same end-to-end operations that _batched and _take perform before enabling the optimization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Each batched trial sample now times what _batched and _take actually run: predicting the second branch from the template, merge_branches, _snapshot, the doubled forward, the split, and _matches against the real second call, then a device sync. A new test checks that a doubled call which wins on its own but loses once snapshot and verification are counted keeps the shape plain.
| name = "flux.2-klein", | ||
| label = "FLUX.2 Klein", | ||
| profile = FamilyProfile( | ||
| auto_bf16_when_resident = SMALL_DIT_BF16_WHEN_RESIDENT, |
There was a problem hiding this comment.
Exclude the 9B Klein variants from the small-DiT BF16 rule
This profile is shared by the 4B and 9B FLUX.2 Klein variants, so _auto_keeps_bf16_reason also applies the new “small denoiser” policy to FLUX.2-klein-9B and FLUX.2-klein-base-9B. On a GPU large enough to hold their roughly 18.2 GB transformer plus the 8B encoder, an automatic load now keeps the unmeasured 9B model in BF16 and immediately compiles it instead of selecting the previous quantized default; the stated measurements and the <= ~6B rationale cover only the 4B variant. Scope this rule by resolved base repo rather than the family-wide name.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. The rule is now scoped by resolved base repo. FLUX.2-klein-9B and FLUX.2-klein-base-9B (18.2 GB bf16 transformer), including their unsloth mirrors, skip the small-DiT bf16 rule and keep the previous quantized auto default. The 4B variants, Z-Image and FLUX.3-klein are unchanged. Tests cover the vendor and mirror ids and that the load passes its base to the decider.
| if offload_policy == "model": | ||
| # diffusers rebuilds model-offload hooks between renders, evicting the router: later renders would differ. | ||
| return "model offload re-hooks the denoiser every render" | ||
| return None |
There was a problem hiding this comment.
Keep CFG batching off for Speed=off resident loads
Removing the resident-denoiser decline enables CFG batching without consulting speed_mode, including when the request explicitly selects speed_mode="off" (and for ordinary unset-speed resident loads). The API and loader treat that tier as a bit-identical contract, but this module explicitly documents that a doubled batch can choose different GEMM/attention tiles and cites nonzero LPIPS for Wan; users can therefore request the reference path and still receive numerically different images unless they know to set a separate environment variable. Pass the effective speed tier into this gate and decline automatic batching on off, while still allowing an explicit CFG_BATCH=force override.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. The loaders now pass the requested speed tier into the CFG batching gate. An explicit speed_mode=off keeps one branch per call for resident and offloaded denoisers alike, so the reference path stays exact, and UNSLOTH_DIFFUSION_CFG_BATCH=force still opts in explicitly. An unset speed keeps the default-on behaviour behind the per-shape timing gate.
…napshots and verification
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… the load (#14583) ## Problem Follow-up to #14566, which made the fused FLUX RoPE in `diffusion_rocm_fused.py` turn itself off for the rest of the load after its first failed launch. Two sibling wrappers still retried a failing launch on every call, so a broken JIT / driver / PTX path paid the failed launch once per RoPE or AdaLN call for the whole render: - the fp16-only FLUX.2 RoPE wrapper in `diffusion_flux2_rope.py` - the opt-in fused AdaLN modulation (`UNSLOTH_DIFFUSION_FUSED_ADALN=1`) in `diffusion_rocm_fused.py` ## Fix Same latch as the fused FLUX RoPE: - The first launch exception sets a per-path flag; every later call skips the kernel and runs the stock path (the same stock code the exception fallback already used, so output is bit-identical). - One warning is logged when the latch trips. The fused FLUX RoPE latch now logs the same way. - `uninstall()` and the next load's install clear the flag, so a new load tries the kernel again. - AdaLN eligibility checks moved into `_adaln_eligible` (no behaviour change) so the latch is testable without a GPU. ## Tests - `test_a_failed_launch_disables_the_fused_path_for_the_load` (`test_diffusion_flux2_rope.py`) and `test_a_failed_adaln_launch_disables_the_fused_path_for_the_load` (`test_diffusion_rocm_fused.py`): a raising launcher, four calls, exactly one launch attempt, stock output after the failure, re-armed after reload. Both fail on main and pass here. - On a real CUDA GPU with a raising AdaLN launcher: main makes 4 launch attempts in 4 calls, this branch makes 1; output equals stock in both. - The related diffusion suites pass on GPU (161 passed). ## Not verified - No real ROCm / gfx1151 or T4 run with a kernel that actually fails to JIT; the failure is simulated with a raising launcher.
…no device timer (CPU, MPS) (#14652) ## Summary #14566 turned CFG batching on for resident denoisers, behind the per-shape timing gate: a shape batches only where one doubled call was measured at least 8% faster than two plain calls. That gate needs a CUDA device timer. When the latents are not on CUDA (a CPU load, or MPS on Apple Silicon), `CfgBatchRouter._trial` skipped the measurement and judged the shape as batchable anyway. So every guided render on CPU or MPS batched both guidance branches without being measured, and its output changed compared with before #14566. Before #14566 this branch was only reachable by offloaded denoisers, which are always on CUDA in practice. The resident path made it reachable on CPU and MPS. ## What it does - `diffusion_cfg_batch.py`: when the trial cannot time the doubled call and the denoiser is resident, the shape is turned off with the reason `no device timer on <device> to price the doubled call`. `UNSLOTH_DIFFUSION_CFG_BATCH=force` still batches. Offloaded denoisers, and anything on CUDA (ROCm included), behave as before. - New test `test_a_resident_denoiser_off_cuda_stays_plain_unless_forced`: a resident CPU denoiser renders twice with only plain calls, matches two plain calls exactly, and reports the reason. Under `force` it still batches. The test fails on main and passes with this change. ## Evidence Found on a Kaggle CPU kernel (no GPU) while checking today's merged diffusion PRs against their merge base (9f303b3). This is the tiny Wan pipeline through Studio's real `VideoBackend`, guidance 5, 2 prompts, same seeds: | tree | CFG batched steps (prompt 1 / 2) | shape off reason | frame hash prompt 1 | prompt 2 | |---|---|---|---|---| | merge base 9f303b3 | not armed | - | 8c598ead | de66c6a0 | | main 2749eee | 2 / 4 | none (batched without a measurement) | a48be48b | b6eb8278 | | this branch | 0 / 0 | no device timer on cpu | 8c598ead | de66c6a0 | The same thing showed up on Kaggle's CPU kernel: main batched 2 / 4 steps and its frames differed from the merge base. On CUDA nothing changes: on a Kaggle T4 the gate already measures and keeps batching off for compute-bound FLUX.2-klein-base-4B pairs (`compute-bound: a plain pair takes 2.40 s`). ## Tests - `pytest studio/backend/tests/test_diffusion_cfg_batch.py`: 35 passed, 1 skipped (the CUDA timer test, run on a CPU host).
…cesses so a seed keeps one path (#14849) ## Problem Single-card CFG batching (#13787, defaults from #14566, #14652, #14734) decides per request shape whether both guidance branches run as one doubled call. Batched is a tolerance mode (about LPIPS 0.01-0.02 versus plain on some models, since the doubled batch can pick other kernels), so the same seed and prompt only give the same image if every render takes the same path. Three ways that choice could change: 1. **Between processes.** The verdict lived only on the router (`CfgBatchRouter.shapes`, keyed on the argument tensor shapes, per load). Every new process or reload re-ran the 2-sample trial (`min(batched) > 0.92 * min(plain)`, plus the single-sample `_RESIDENT_MAX_PAIR_S` gate). A shape near the 0.92 line landed on either side depending on timing noise. 2. **Between renders in one process.** A shape turned off by memory pressure (`_OFF_TRANSIENT`: no room before the trial, or an OOM on a doubled call) had `judged` reset in `end_render`, so the next render re-timed it and could latch "measured no gain" for the rest of the load. 3. **Within one render.** `_batched` returned plain for a single step when free memory read below 2x the activation peak and batched again on the next step, so a fluctuating free-memory reading mixed paths step by step. Probe with a controlled timer (per-call lognormal noise, 40 fresh loads per cell; P = plain pair, B = doubled call): | doubled / plain pair | noise sigma | main | this PR | |---|---|---|---| | 0.92 | 0 (A/A) | 40/40 batched | 40/40 batched | | 0.90 | 0.05 | 29 batched, 11 plain | 40/40 one path | | 0.92 | 0.02 | 22 batched, 18 plain | 40/40 one path | | 0.94 | 0.05 | 20 batched, 20 plain | 40/40 one path | One transient OOM on render 2, ratio 0.91, sigma 0.03: render 1 and render 4 took different paths in 2/40 loads on main, 0/40 here. Free memory moving around the line each step on main: `PPPBPBBB`, `PPBBPPBP`. ## Fix - The timing verdict is latched on the shape (`_Shape.verdict`). A transient memory off still makes that render plain, but the next render batches again from step 3 without a new trial. - Verdicts are stored in `diffusion_cfg_batch_verdicts.json` next to the learned peaks. The key covers the load (denoiser class, config, layer classes, weight dtypes, offload policy, speed tier), the card name, compiled or eager, the request shape, and the runtime stamp (torch, diffusers, kernel packages). First writer wins under the same file lock as the learned peaks, so a later process takes the stored path with no trial. Only measured timing verdicts are stored. Nothing is stored off CUDA or for a load that cannot be identified. `UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0` keeps the verdict per load, and `UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE` sets the path. - If a doubled call has no room mid-render, the shape stays plain for the rest of that render. It no longer skips single steps. - OOM safety is unchanged: no room or an OOM still falls back to plain for that render. A shape whose first doubled call comes from a stored verdict counts that render as its warm-up, so the compiled-graph rules match the trial path. Nothing changes under Dynamo tracing (the router still passes straight through) and there is no new per-step work. The store is read once per shape per load. ## Tests - New in `studio/backend/tests/test_diffusion_cfg_batch.py`: a borderline shape keeps one path across fresh loads (both verdicts), memory pressure never re-times a judged shape, no room mid-render keeps the rest of that render plain, and the store is keyed on the card and skipped off CUDA. All 5 fail on main and pass here. - `test_diffusion_cfg_batch.py`, `_cfg_batch_sync`, `_cfg_parallel_tier`, `_zimage_cfg_split`, `_speed`, `test_diffusion_backend.py`, `test_video_backend.py` with `-n 8`: 1465 passed here; on main 1460 passed and the 5 new tests failed. - Real CUDA (B200, tiny random FLUX.2-klein, resident bf16, CFG 4, 6 steps, 256x256): process 1 ran the trial and stored `batch`. Process 2 skipped the trial (`[1, 1, 1, 1, 2, 2, 2, 2]`) and gave the same image hash as process 1. ## Not covered - No real-model LPIPS run: the probe shows the path choice, and the image difference between paths is the tolerance already measured in #13787. - A stored verdict is not re-measured after a driver change, or after other changes that leave the key the same. Deleting the file or setting `UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0` resets it. - If memory really runs short partway through a render, that render still switches to plain from that step on. This is the intended OOM fallback. - `activation_mib` is only known when a plain call raises the process's peak counter, so whether the memory gate applies still depends on process history. Unchanged here. - `test_diffusion_backend.py::test_begin_load_rejects_concurrent` hit its 30 s thread timeout on a loaded host. It fails the same way on main and is unrelated. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…% per eager step, fp32 error unchanged) (unslothai#16760) ## Summary The fused FLUX AdaLN kernel (`UNSLOTH_DIFFUSION_FUSED_ADALN`, one pass of LayerNorm + `* (1 + scale) + shift`) is now on by default on NVIDIA CUDA under Linux, the same scope the fused FLUX RoPE got in unslothai#14566. - It was opt-in everywhere because it gave no speed on gfx1151, and that is still true there: ROCm stays opt-in. - On NVIDIA it is faster (numbers below). Its output differs from stock only by rounding order: it rounds once where stock rounds three times, and its error against an fp32 reference is the same as stock's. - The bit-exact `speed_mode=off` tier keeps the stock AdaLN. The RoPE kernel is bit-identical, so it still installs there. Unset, `eager`, `default` and `max` get the fused AdaLN. - Unchanged: it never runs inside a compiled graph (`torch.compiler.is_compiling()` returns stock). So it only acts on eager FLUX blocks: GGUF FLUX on the default tier (dequant compiled, blocks eager), the `eager` tier, the first renders of an unset load, and loads that cannot compile. - `UNSLOTH_DIFFUSION_FUSED_ADALN=0` turns it off. Windows and macOS keep stock, as with the RoPE kernel. ## Evidence (A100-SXM4-40GB, Colab, torch 2.14.1, diffusers 0.42.1) The setup is a FLUX.1-shaped `FluxTransformer2DModel` at real width: 24 heads x 128, joint dim 4096, 2 double + 4 single blocks, 4096 image + 512 text tokens (1024x1024), random weights. It runs eager with the fused RoPE on in both arms, which is what main does today. Each arm was timed for 5 interleaved rounds of 10 forwards, with the arm order rotated, and stock was timed twice for A/A. | dtype | stock ms (min-max) | fused AdaLN ms (min-max) | speedup | A/A spread | fused AdaLN calls per forward | |---|---|---|---|---|---| | bf16 | 40.01 (39.58-40.13) | 39.04 (38.78-39.15) | 2.48% | 0.10% | 9 of 9 | | fp16 | 41.49 (41.23-41.53) | 40.52 (40.33-40.73) | 2.38% | 0.02% | 9 of 9 | The fused and stock ranges do not overlap. The per-block share of AdaLN is the same in the full 19 + 38 block model, so the per-step gain on an eager FLUX.1 step should be about the same. Accuracy, measured on the same weights and inputs against an fp32 run of the stock model (relative L2 of the transformer output): | dtype | stock vs fp32 | fused vs fp32 | fused vs stock | |---|---|---|---| | bf16 | 0.013836 | 0.013845 | 0.0078 | | fp16 | 0.001805 | 0.001801 | 0.0011 | The fused output is exactly as far from fp32 as stock is. The fused-vs-stock gap is about half of bf16's own rounding error, which is the scale of a different rounding order. The only real-weights pixel number is from FLUX.2-klein on gfx1151 (unslothai#12701): LPIPS 0.004 between the two. There it covers only the final `AdaLayerNormContinuous`, because FLUX.2 blocks use their own modulation. ## Tests - New or updated in `test_diffusion_rocm_fused.py`: - auto engages RoPE and AdaLN on NVIDIA Linux (bf16, fp16). - `adaln=False` keeps the stock AdaLN but still installs RoPE. - The AdaLN kill switch works on NVIDIA. - FLUX.2 fp16 keeps its own RoPE patch. - The patch registry passes `adaln=False` only for `speed_mode=off`, and `adaln=True` for unset, `eager` and `default`. - Base vs head, with each arm importing its own tree, over `test_diffusion_autoopt*`, `test_diffusion_eager*`, `test_diffusion_speed.py`, `test_diffusion_rocm*` and `test_diffusion_flux2*`: - head: 327 passed, 0 failed. - base with the head tests: 321 passed, 6 failed. - The 6 base failures are exactly the new default tests. ## Not covered here - Timing is from an A100 only. L4, H100 and Blackwell were not timed. The kernel is memory-bound, so it should gain at least as much on cards with lower bandwidth, but that is not measured. - No pixel LPIPS with real FLUX.1 weights in this PR (FLUX.1 is where every block uses these classes). The accuracy evidence is the fp32-reference comparison above.
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:
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_ropeby default.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.
The automatic static step skip is now only on
speed_mode=max. It is lossy (gated at LPIPS <= 0.05 ondefault, <= 0.10 onmax, Studio: per-model automatic step skip at each model's measured step count (1.44 to 1.81x, MiniMax-H3 on max) #12652), and ComfyUI skips no steps by default. Unset anddefaultspeed no longerskip steps, including the deferred "from the third image" path.
CFG batching now also runs for a resident denoiser, as ComfyUI does by default (
calc_cond_batch), behindthe 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=offkeeps one branch per call (
UNSLOTH_DIFFUSION_CFG_BATCH=forceoverrides). The trial nowruns 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.
On Blackwell,
autoattention keeps native SDPA where torch already dispatches cuDNN. Same kernel, bitwiseidentical, without the cuDNN pin's per-call wrapper (0.4% to 22% per eager SDPA call, equal compiled). ComfyUI also
defaults to native.
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
UNSLOTH_DIFFUSION_FUSED_ROPEauto= ROCm onlyauto= ROCm, or NVIDIA CUDA on LinuxSTAGE_LOADregistry is identical, as is the tiny FLUX.2 transformer, eager and under CUDA graph replayFLUX.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.
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:
defaultprofile compiles on the third;Compiled blocks are unchanged: the wrapper checks
torch.compiler.is_compiling()first and takes stock RoPE there.Scope and gates:
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.
is unmeasured.
UNSLOTH_DIFFUSION_FLUX2_FUSED_ROPE, installed first). The new autopath never stacks on top of it.
UNSLOTH_DIFFUSION_FUSED_ROPE=0restores 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 worktreeat the merge base (77e6eaf), new = this branch. Each process runs 5 prompts at one resolution:
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:
diffusion_cuda_graph.capture_generation);speed_mode=default, residentmemory_mode=balanced(group offload, streamed)memory_mode=low_vram(model offload)memory_mode=low_vramReading the table:
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.
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.
The counts on prompts 2+ are identical old vs new and come from existing defaults; see "Existing defaults that
recompile or re-capture" below.
defaultrun. That is run-to-run spread of the compiled tier itself:defaultarm differed from a second olddefaultprocess;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. Theexclusive end-to-end matrix ticket never got a card and was cancelled.
Placements not run, and why the RoPE flip cannot change them:
engine router is not touched.
torch.cuda.device(x.device), so a replica or companion on another cardgets the same kernel on its own device. This was not run on two cards.
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:
low_vram)UNSLOTH_DIFFUSION_FP8_UNIT_SCALE)off/eager/default/max)defaultGPU check through Studio's backend, 5 prompts per process, B200, unset precision:
transformer_quant=nonearms)memory_mode=low_vramThis 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
defaulttier,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=defaultfrom render 1. Only an unset speed on a compile-eligible host does this, and the deferredprofile stays for everything else. B200, Studio backend in process, unset speed and precision, 4 prompts, and prompt 4
repeats prompt 1's seed:
The accepted cost of the accuracy rule, against the old INT8 default on a B200:
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_1covers three cases:defaultand does not defer (this case fails without the commit);offis honoured;3. Automatic static step skip: only on
speed_mode=maxThe 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
defaultand <= 0.10 onmax, and also engaged with thedeferred 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.
defaultmaxtransformer_cache=staticrequest, and theUNSLOTH_STATIC_SKIP_*knobsUNSLOTH_DIFFUSION_AUTO_STEP_SKIP=0still turns themaxauto skip off. Video follows the same rule (the tests coverWan2.2-TI2V-5B). The diff is
AUTO_STATIC_SKIP_TIERS = (max,)indiffusion_cache.py. 9 tests failon the merge base and pass here, including
test_deferred_default_tier_never_auto_skipsandtest_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:
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.
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.
batched ones.
graph per compiled block. A B200 audit of main found this happening, along with graph breaks traced inside the
router. The rules are now:
first-render warm-up;
stays plain after it;
This is checked at install and at the start of every render.
renders, which takes the router out of the forward slot after render 1. On Wan2.1-1.3B
low_vrama first versionof this change batched render 1 only.
t.expand(batch)timestep. Beforethat, 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):
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:
defaultThe 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
default17723 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 displacethe 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 asmall card), with batching on vs off on the rebased branch, B200. There are 4 prompts, and prompt 4 repeats prompt 1's
seed:
default(compiled), streamed, 8 GiB capdefault(compiled), residentThe 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.
Reading it:
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.
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.
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,
autoattention pinned diffusers'_native_cudnnbackend on NVIDIA SM80+. The code commentsaid about 1.18x. Re-timed on a B200 (torch 2.13.0+cu130), one process with interleaved arms on an exclusive card:
Native already runs the same cuDNN kernel. The pin adds only its per-call
sdpa_kernelwrapper: 0.4% to 22% slowereager, and within +-4% compiled (mixed sign, inside the A/A spread). End to end on the compiled
defaulttier,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_kernelcontext was the source ofthe Dynamo graph breaks ("custom metaclass with
__getattribute__" ontorch.nn.attention._SDPBackend) on everycompiled 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_choiceat each DiT head dim and the run dtype) and leaves native only when the answer is cuDNN forevery 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_choiceover bf16 / fp16, head dims 64 / 128 / 256, 1-40 heads, self and crossattention (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:
attention_backend=cudnn;UNSLOTH_DIFFUSION_BLACKWELL_NATIVE_ATTN=0.The auto pick is a
strsubclass equal to"_native_cudnn", so the MiniMax-H3 arch override and the preinstall stepsee 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.
free8holds all but8 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.
speed_mode=defaultlow_vramdefault)low_vramReading it:
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.bf16 reference.
defaultdiffered by CFG batching (0.021 mean / 0.059 max) in this run. This matrix ran before thecompiled-denoiser rule; a resident compiled Wan now declines batching and matches old bit for bit (table in
change 4).
low_vramarms run the same precision as old, and stay within 0.007.(Z-Image) where bf16 replaced INT8 (change 2).
defaulttier is 1.41 s vs 1.08 s per render, bf16 vs old INT8 (change 2). Thesame cost shows on the unset path once its profile has compiled.
Existing defaults that recompile or re-capture on follow-up prompts
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_kernelcontext ("custom metaclass with__getattribute__" ontorch.nn.attention._SDPBackend). On Blackwell they are gone with change 5; on othercards they remain.
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.
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.
The compiled image tiers are not pixel-reproducible across processes. With the same seeds, one old
defaultprocess 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
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.max(change 3);step).
Tests
Each new test fails on the merge base and passes here:
RoPE:
tests/test_diffusion_rocm_fused.pycovers: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_familiescovers the five keptmodels, plus FLUX.1-dev, FLUX.2-dev and Qwen-Image as not kept;
Static skip:
test_diffusion_step_skip_defaults.pyandtest_video_static_skip.py, 9 failing on base, 103passing here.
CFG batching:
test_diffusion_cfg_batch.py, 35 tests (including Studio diffusion: VAE OOM under a component split, expanded timesteps in the CFG routers, and test fixes #14420's; one runs only with a GPU). The new onesare:
shows the trial only inside step 1, and the result equals the plain-only or batched-only path;
_compiled_call_impl, Studio's compile markers, a compiled forwardbelow a group-offload hook);
fullgraph=True) passes straight through;never gated;
call paid, with the same image; CPU latents have no device timer, so the trial judges untimed.
plain;
speed_mode=offdeclines batching resident and offloaded (unset,defaultandmaxstill arm;forceoverrides), and both the image and video loaders pass the requested speed.Review follow-ups:
test_diffusion_rocm_fused.pychecks that a failing RoPE launch runs once per load, thenstock (bit-identical output), and that the next load re-arms it.
test_diffusion_pipeline_prequant.pychecks thatthe 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:_native_cudnn;Suites, no GPU visible:
with a GPU. The failure is
test_teardown_survives_a_later_eager_layer, which fails the same way on the mergebase with the same file set (
test_diffusion_pipeline_prequant.pyrunning first leaves process-global patchstate) and passes when its file runs alone;
test_diffusion_multigpu.py,test_diffusion_block_graph.pyandtest_diffusion_attention_install.py) gave2207 passed, 87 skipped and 2 failed.
test_an_imported_old_kernels_is_not_papered_overfails on that maintoo, and
test_teardown_survives_a_later_eager_layeris the known order-dependent failure;test_diffusion_backend.py::test_unload_cancels_pipeline_constructionthat movedbetween 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;
test_diffusion_multigpu.pyandtest_diffusion_block_graph.pygave 2201 passed, 87 skipped and 2 failed. The two failures (
test_teardown_survives_a_later_eager_layerandtest_diffusion_attention_install.py::test_an_imported_old_kernels_is_not_papered_over) also fail on main /the merge base;
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 onthe merge base with the same file set (order-dependent process-global patch state), and passes when its file
runs alone;
GPU (B200, through the GPU queue):
Not verified
unsupported card or driver.
the cuDNN pin unchanged.
there, and its result is not measured.
The exclusive tables (RoPE step, SDPA kernel, CFG on / off) carry the speed claims.
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+.
--leave-free-gib 8(aballast tensor) and
memory_mode=low_vram. In thefree8pair the planner picked group offload for old andstreaming 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.