Skip to content

Studio FLUX.3: build attention Q / K in one bit-exact kernel - #17637

Merged
danielhanchen merged 4 commits into
mainfrom
t4-klein-norm-attn
Nov 13, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
t4-klein-norm-attn

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Studio FLUX.3: build attention Q / K in one bit-exact kernel

What was slow

Flux3AttnProcessor (diffusers transformer_flux3.py) prepares Q and K like this:

query = attn.norm_q(query.float())
key = attn.norm_k(key.float())
query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
query, key = query.to(value.dtype), key.to(value.dtype)

Each tensor goes through an upcast copy, a float32 RMSNorm, the RoPE (one kernel with the existing fused RoPE, several without it) and a downcast. On Turing (T4, fp16 only, eager blocks) the float32 RMSNorm (vectorized_layer_norm_kernel<float, float, true>, the true is torch's RMSNorm flag) was the largest norm kernel in a FLUX.3 klein INT8 render: 939 ms per profiled render, plus 666 ms of RoPE and the casts around them.

What changes

core/inference/diffusion_flux3_qk_rope.py adds one Triton kernel that reads the fp16 / bf16 projection once and writes the attention input once. All math stays in float32 and in the stock order:

  • RMSNorm reproduces torch's CUDA row kernel order (4 elements per thread in order, then the warp fold, rsqrt(sum / D + eps), w * (rstd * x)). An fp16 / bf16 value squared is exact in float32, so the order alone fixes the sum.
  • RoPE is diffusers' interleaved x * cos + rot * sin, with each product and the sum rounded to float32 and FMA contraction off. Then one rounding to the activation dtype.

The stock processor is swapped for a subclass that calls the shared helper. The strided cuDNN processor and the FLUX.x ConvRot fused block path call the same helper and accept the subclass. Diffusers' Flux3AttnProcessor.__call__ digest is checked first, as the strided processor already does.

Gates

  • The kernel is used per (card, activation dtype, norm weight dtype, head dim, eps) only after a probe matches the stock chain bit for bit. The probe covers row scales from 1e-3 to 1e3, DC offsets, outliers and strided head-split views. The kernel also has to beat the stock chain by more than 2% on a timed probe.
  • The first real call of each key is also compared against the stock chain once. A mismatch turns the key off for the process.
  • Compiling frames, grad, CUDA graph capture before the probe ran, odd layouts, patched or hooked norms, and a failed launch all run the stock lines.
  • Kill switch: UNSLOTH_DIFFUSION_FLUX3_QK_NORM_ROPE=0 (also UNSLOTH_DIFFUSION_PATCH_FLUX3_QK_ROPE=0).

Compiled blocks (A100 / L4 / Blackwell default tiers) keep stock math inside the graph. Only eager renders change: Turing, a first render before a deferred compile, LoRA, and speed off. Output is bit-identical either way.

Numbers

Kernel, klein joint block shape (S = 4608, 24 heads, head dim 128), Q + K together:

card weight dtype stock chain fused bit-exact
T4 (fp16) float32 10.67 ms 1.06 ms yes (all rows)
T4 (fp16) float16 12.28 ms 0.60 ms yes
L4 (bf16 / fp16) float32 9.17 ms 0.59 ms yes
L4 (bf16 / fp16) float16 11.39 ms 0.58 ms yes

On-device probe verdicts were exact and faster for fp16 and bf16 activations, with float32 and same-dtype weights, on both T4 and L4.

End to end, FLUX.3 klein INT8, 1024x1024, 16 steps, Colab T4, same VM, base = merge base, base run three times:

arm s/img (median of 3 images) peak VRAM LPIPS vs base, same seeds
base r1 / r2 / r3 41.42 / 42.11 / 42.19 (median 42.11, spread 0.77) 12.11 GiB A/A: 0.0, pixel-identical
head r1 / r2 40.73 / 40.70 12.06 GiB 0.0, pixel-identical (every image)

Head is 1.4 s/img faster than the base median (-3.3%). That is outside the base spread, and both head runs beat the fastest base run. LPIPS against the dense fp16 reference is the same on both arms (mean 0.0279, max 0.0745), because the images are identical.

Profiled render, denoise window: GPU busy time 40.13 s -> 38.36 s, 38323 -> 34674 kernels. Per render, the float32 RMSNorm (1236 ms), RoPE (667 ms) and the cast copies around them (about 0.8 s) became one _f3_qk_norm_rope kernel at 512 ms. Attention (fmha 14.4 s) and the int8 GEMMs are unchanged.

Tests

tests/test_diffusion_flux3_qk_rope.py (CPU):

  • the probe's reference is the stock chain, bit for bit;
  • the swapped processor equals the stock processor bit for bit;
  • a whole tiny FLUX.3 transformer forward is unchanged;
  • every gate is checked: unproven, slower or unprobed card, kill switch, compiling frame, missing RoPE, patched or hooked norm, failed launch (never retried), first-real-call mismatch;
  • install, idempotence, uninstall, a changed diffusers processor, and registry membership.

The autoopt registry tests and the parity fixture gain the new flux3_qk_rope spec, which stays off on the CPU stub pipes.

The attention prologue upcast Q and K to float32, ran torch's float32 RMSNorm,
a two-pass RoPE and a downcast: five kernels per tensor. On Turing (eager
blocks, fp16) the float32 RMSNorm alone was the largest norm kernel of a
klein render. One Triton kernel now reads the fp16 / bf16 projection once and
writes the attention input once, all math in float32 in the stock order.

Engaged per card / dtype / head dim only after a probe matched the stock chain
bit for bit and beat it on time, and after the first real call matched too.
Compiling frames, grad, odd layouts and a failed launch run the stock lines.
Off with UNSLOTH_DIFFUSION_FLUX3_QK_NORM_ROPE=0.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: 🔄 Running

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-11-13T11:20:36.485787Z 2d8e4c2 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

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

ℹ️ 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 +45 to +46
def enabled() -> bool:
return (os.environ.get(QK_NORM_ROPE_ENV) or "1").strip().lower() not in (

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 Honor the registry kill switch in the shared helper

When UNSLOTH_DIFFUSION_PATCH_FLUX3_QK_ROPE=0 is set, the registry skips the processor swap, but this check still enables the fused kernel because it reads only UNSLOTH_DIFFUSION_FLUX3_QK_NORM_ROPE. Both the strided cuDNN processor in diffusion_flux3_attn.py and the ConvRot path in diffusion_flux_convrot_fused.py now call qk_norm_rope independently of that swap, so those configurations continue probing and launching the optimization despite its registry kill switch. Check both switches in the shared runtime gate so disabling the patch actually restores the stock Q/K chain on every integration path.

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.

Fixed in 7891167: the shared gate now honours both UNSLOTH_DIFFUSION_FLUX3_QK_NORM_ROPE and UNSLOTH_DIFFUSION_PATCH_FLUX3_QK_ROPE, so either switch restores the stock Q / K chain on the swapped processor, the strided cuDNN processor and the ConvRot path. test_kill_switch now covers both switches.

… K helper

The strided cuDNN and ConvRot paths call qk_norm_rope without the processor
swap, so UNSLOTH_DIFFUSION_PATCH_FLUX3_QK_ROPE=0 left them on the fused kernel.
The helper's gate now honours both switches.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 789116787f

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

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. Breezy!

Reviewed commit: 2d8e4c213e

ℹ️ 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 de68009 into main Nov 13, 2026
@danielhanchen
danielhanchen deleted the t4-klein-norm-attn branch November 13, 2026 13:13
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 17, 2026
… q/k RoPE int64 offsets, Gemma-4 band route int32 guard (unslothai#18141)

Three fixes from a re-check of recent kernel PRs.

1. **Cold probes ask about capture on the operand's card (unslothai#17795,
unslothai#17593, unslothai#17637).** The cold `verdict()` of the MiniMax-H3 row-mod kernel
(`video_minimax_h3_rowmod.py`), the H3 q/k norm
(`video_minimax_h3_qknorm.py`) and the FLUX.3 q/k RoPE
(`diffusion_flux3_qk_rope.py`) read
`torch.cuda.is_current_stream_capturing()` on the current card before
switching to the operand's card. With another card current, the timing /
equality probe could start inside a CUDA graph capture on the operand's
card, then cache a failure or raise. The query now runs under
`torch.cuda.device(x.device)`, with the probe.
2. **MOSS-Image fused q/k norm + RoPE: int64 row offsets (unslothai#17099).** The
kernel multiplied the token index by the fused-QKV row stride in int32,
which wraps past 2**31 (a 9216-wide row past about 233k tokens). The row
index is now int64 before any stride product; output bits are unchanged.
3. **Block compile: the Gemma-4 sliding band route checks the interval
kernel's int32 limit (unslothai#17817, unslothai#17860).** The long-band route in
`unsloth/models/_block_compile.py` called `large_head_attention`
directly and skipped the int32 span check the large-head router applies
on its own path (`_shapes_qualify`), so a long enough sliding layer
reached the int32-addressed kernel. The band route now keeps masked SDPA
past that limit.

### GPU results, base (main 62d66cb) vs this branch

Capture probes, Kaggle 2x T4 (sm75), torch 2.11.0+cu130: cuda:0 current,
a `torch.cuda.graph` capture active on cuda:1, operand on cuda:1, cold
call, probe runs counted.

| probe | base | this branch |
|---|---|---|
| H3 row-mod `verdict` | probe ran inside the capture and cached
`{exact: False, use: False}`; the next eager call still returns the
cached failure | returns None, no probe, nothing cached; the next eager
call computes `{exact: True, use: True}` |
| H3 q/k norm `verdict` | probe ran inside the capture and the call
raised `Cannot copy between CPU and CUDA tensors during CUDA graph
capture` | returns None, no probe; the next eager call computes the real
verdict |
| FLUX.3 q/k RoPE `verdict` | probe ran inside the capture and cached a
RuntimeError failure for cuda:1 for the process | returns None, nothing
cached; the next eager call runs the real check |

The captured graph itself replayed correctly in both arms; the defect is
the probe running inside the capture and the cached failure or raise.

MOSS and band route, L4 (sm89), Colab, torch 2.12.1+cu130, Triton 3.7.1:

| fix | check | base | this branch |
|---|---|---|---|
| MOSS int64 offsets | fused kernel engaged (4 launches per arm);
1x4096x24, 2x1029x24, 1x16384x24, 1x37x4 | q / k / v hashes | identical
to base; v equal to eager, q / k within 0.03125 of eager in both arms |
| band route guard | S600 / w512 / hd256, S2048 / w512 / hd128, S4096 /
w1024 / hd256 (kernel route), S256 / w512 (causal SDPA) | routes and
output hashes | same routes, identical hashes; max error vs fp32 about
0.008 |

### Tests

- `studio/backend/tests/test_diffusion_capture_probe_device.py` and
`test_h3_row_mod.py::test_cold_verdict_asks_about_capture_on_the_operand_card`:
on the T4 pair base 3 failed / 14 passed, this branch 17 passed
(two-card tests included).
- `studio/backend/tests/test_diffusion_moss_qk_rope_offsets.py` lowers
the kernel to TTIR and rejects i32 row-stride products: fails on main;
on the L4 base 1 failed / 8 passed, this branch 9 passed, and the
existing MOSS fused GPU tests pass in both arms.
-
`tests/test_block_compile.py::test_gemma4_long_band_past_int32_keeps_the_plain_route`:
fails on main; on the L4 base 1 failed / 83 passed, this branch 84
passed (4 skips, the same version gates in both arms).
- CPU (torch 2.14.1) on this branch: 13 passed / 5 skipped in the probe
and MOSS files, 74 passed / 14 skipped in `test_block_compile.py`.

### Not covered

- The overflow sizes themselves (over 233k MOSS tokens, a band span past
2**31) cannot be allocated; the TTIR and CPU route tests are the
evidence there.
- A full MOSS-Image render with real weights; the op and its unit tests
ran.
- On fp16 / sm75 the FLUX.3 q/k RoPE check reports a real bit mismatch,
so its fused path stays off on T4 regardless of this change; the capture
fix is shown by the probe count, not by the fused path engaging there.
- sm80 and sm120 cards; the capture probes ran on T4 only, MOSS and the
band route on L4 only.
- The GPU runs used main 62d66cb; the branch was then rebased onto
main 142c398 and only the CPU tests were rerun there.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant