Skip to content

Studio: fused RoPE for FLUX on ROCm (FLUX.2-klein 8% faster per image, pixel-identical) - #12701

Merged
danielhanchen merged 10 commits into
mainfrom
studio/amd-diffusion-fused-rope
Oct 5, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
studio/amd-diffusion-fused-rope

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On a Ryzen AI Max (gfx1151, ROCm), Studio's FLUX.1-schnell denoiser step is slower than ComfyUI's on the same torch build: 4.34 s against 3.81 s per step at 1024x1024 (14%). Qwen-Image-2.1 is about 8% behind and Wan 2.2 TI2V-5B about 7%.

ComfyUI runs FLUX's RoPE and AdaLN modulation through comfy-kitchen (ck.apply_rope, ck.apply_rope1, ck.adaln), and on ROCm comfy-kitchen registers its HIP backend ahead of the others, so each of those ops is one kernel there. Studio runs diffusers' stock code:

  • apply_rotary_emb upcasts q and k to float32, builds the rotated copy with stack, then does two products and an add: about six full passes over a 4608 x 24 x 128 tensor, twice per block, 57 blocks per step.
  • AdaLayerNormZero / AdaLayerNormZeroSingle / AdaLayerNormContinuous run layer_norm, 1 + scale, a product and an add, each re-reading the activation.

On a bandwidth-bound APU each extra pass costs real time. The eager addcmul patches only run in an active speed tier, which ROCm loads do not enter by default.

Change

New diffusion_rocm_fused.py, installed from load_pipeline next to the FLUX.2 RoPE patch and removed in _uninstall_fused_dit_patches:

  • RoPE: the module global apply_rotary_emb of transformer_flux and transformer_flux2 points at a wrapper that launches the existing diffusion_flux2_rope Triton kernel for bf16 and fp16. Float32 math with FMA contraction off, one rounding, so the output is bit-identical to stock.
  • AdaLN (opt-in): the three AdaLN classes can get a forward that runs LayerNorm and the modulation in one Triton kernel. LayerNorm statistics are float32; the normalised value, 1 + scale, the product and the sum are each rounded to the activation dtype, as in stock. The only difference to stock is the order of the row reduction. On gfx1151 it bought no speed on top of the RoPE kernel and is not bit-identical (see Results), so auto leaves it off and only =1 turns it on.
  • Scope: FLUX.1 and FLUX.2 denoisers, CUDA-device tensors in bf16 / fp16, no grad, not while compiling (a compiled block keeps stock code). Any call that does not fit (fp32, CPU, a different layout, an affine or fp32 norm, a kernel error) takes the stock math. A diffusers release that changes the reimplemented lines keeps the stock class.
  • Switches:
    • UNSLOTH_DIFFUSION_FUSED_ROPE=auto|0|1: auto (the default) = ROCm only, so CUDA loads are unchanged.
    • UNSLOTH_DIFFUSION_FUSED_ADALN=auto|0|1: auto = off on every device; 1 opts in.

No new dependency. comfy-kitchen (Apache-2.0) was considered: its PyPI wheels do ship a prebuilt HIP extension for gfx103x, gfx110x, gfx115x and gfx120x, but that is a 59 MB wheel (132 MB HIP library linked against libamdhip64.so.7) plus a backend registry and custom ops for two elementwise kernels, and its RoPE takes ComfyUI's rotation-matrix freqs_cis layout instead of diffusers' (cos, sin). Studio already had a bit-identical Triton RoPE kernel, and Triton ships with ROCm torch.

Results

Strix Halo CI runner, Radeon 8060S (gfx1151), Linux, torch 2.11.0+rocm7.13.0, AOTriton SDPA. FLUX.2-klein-4B, 1024x1024, 4 steps, same prompts and seeds, all cells in one job on one runner. fused is this PR's default on ROCm. The other Studio arms set the switches.

arm s/image s/step vs unfused pixels vs unfused
Studio, unfused (stock diffusers) 8.76 1.872 1.00 reference
Studio, fused RoPE (this PR's default) 8.09 1.731 0.92 identical (PSNR 99 on both prompts)
Studio, fused RoPE + fused AdaLN 8.04 / 8.07 / 8.09 (3 runs) 1.706 / 1.725 / 1.717 0.92 PSNR 34.0 / 45.5 dB, LPIPS 0.004
ComfyUI, same torch, defaults (kitchen HIP kernels on) 10.67 / 10.69 / 10.67 (3 runs) 1.90 to 1.95
ComfyUI, COMFY_KITCHEN_DISABLE_HIP=1 10.99 2.06
  • Speed: the RoPE kernel takes 8% off the render and is pixel-identical to stock. AdaLN adds nothing measurable on top, and the three repeated renders differ by less than 1%. That is why AdaLN is opt-in.
  • Against ComfyUI: Studio's klein render (8.09 s) is about 24% faster than ComfyUI's (10.67 s) on the same torch.
  • What kitchen buys ComfyUI: turning off comfy-kitchen's HIP kernels costs ComfyUI about 6% per step (1.90-1.95 to 2.06 s).
  • FLUX.1: not measured. In the same job, the FLUX.1-schnell Studio cells were refused at load because another tenant held about 31 GiB of this runner's memory pool before the job started. That is a host fault, not a result, and it is being rerun.

Kernel microbench, NVIDIA B200 with both switches forced on, FLUX.1 1024x1024 shapes, bf16, median of 5 timing windows, 3 runs. This is a sanity check only: the card was shared and busy, so absolute times are inflated, and it says nothing about gfx1151.

op, per call stock fused
RoPE, 1 x 4608 x 24 x 128 754 to 1086 us 45 to 55 us
AdaLayerNormZeroSingle, 4608 x 3072 330 to 610 us 107 to 159 us

Tests

tests/test_diffusion_rocm_fused.py. Run with the FLUX.2 RoPE tests on a B200 with the switches forced on: 50 passed on torch 2.14.1 / diffusers 0.41.0.dev0 and on torch 2.11.0 / diffusers 0.41.0.dev0. After merging current main, the file plus the FLUX.2 RoPE and speed suites: 209 passed. On main the file fails at import.

  • Switch logic: auto stays off on CUDA, and on ROCm engages RoPE only; AdaLN needs =1. 0 disables, 1 forces on, and the two switches are independent, fp32 / CPU / non-FLUX loads stay stock, no Triton stays stock, reinstall does not stack wrappers, uninstall restores the exact diffusers objects.
  • Load and teardown wiring in diffusion.py, and the reimplemented diffusers lines are still present.
  • GPU: RoPE equals stock bit for bit (bf16 and fp16, FLUX.1 shape and an odd shape). AdaLN stays within the propagated rounding bound of stock, with under 1% of elements differing. A tiny FluxTransformer2DModel (2 double, 2 single blocks) runs the fused paths the expected number of times (8 RoPE, 7 AdaLN calls) and matches stock output.

Not covered

  • FLUX.1 and FLUX.2-dev were not measured on gfx1151 (FLUX.1 was blocked by a co-tenant in this run). Only FLUX.2-klein-4B has runner numbers.
  • No A/A repeats of the unfused and RoPE-only arms: one run each against three repeats of the fused arm.
  • Wan 2.2 and Qwen-Image are not covered. Wan's fused block (video_wan_fused.py) is fp16 CUDA only; Qwen-Image uses the complex apply_rotary_emb_qwen.
  • FLUX.1's inline norm2 modulation in FluxTransformerBlock.forward stays stock.
  • Torch 2.6 was not run: the available torch 2.6 environment fails to import diffusers (torchao mismatch) for the existing FLUX.2 RoPE tests too.
  • test_diffusion_arch_patches.py::test_install_idempotent_and_reversible fails on this host independently of this change (it imports neither changed file; patch count against diffusers 0.41.0.dev0).

FLUX.1 / FLUX.2 denoisers on ROCm now run diffusers' apply_rotary_emb as one
Triton kernel (the existing FLUX.2 fp16 kernel, bit-identical to stock) and
AdaLayerNormZero / AdaLayerNormZeroSingle / AdaLayerNormContinuous as one
LayerNorm plus modulation kernel that keeps the stock rounding chain.

Switches UNSLOTH_DIFFUSION_FUSED_ROPE and UNSLOTH_DIFFUSION_FUSED_ADALN
(auto|0|1, auto = ROCm only, so CUDA loads are unchanged). Inference only,
skipped while compiling, per-call fallback to the forward live at install.
@chatgpt-codex-connector

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 🔄 Running since 2026-10-04T22:38:44.817105Z a442e61 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

chatgpt-codex-connector Bot commented Oct 4, 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-05T09:36:51.144152Z 7bd0b88 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

All three red checks here (Source lint, workflow-trigger lint and Repo tests (CPU, rest)) are the same risky-loader gate, and come from this PR rather than main: the new studio/backend/core/inference/diffusion_rocm_fused.py:191 calls importlib.import_module and has no entry in scripts/risky_loaders_baseline.json. If the module name there is fixed (not user input), run python scripts/lint_risky_loaders.py --update and replace the generated "REVIEW ME" reason with why it is safe. #12703 is stacked on this branch and shows the same failure, so it should clear once this lands.

…eline

install_rope() only calls importlib.import_module on a module name that is
already a key of _ROPE_FNS, which is built from the fixed _MODULES tuple of
the two diffusers Flux transformer modules. No model, request or download
can choose the imported name, so the call site is safe to record.
test_diffusion_backend.py can leave Studio's compile-safe eager patch live on
diffusers' AdaLN classes. When it runs first in the same session, every
teardown here saw that forward instead of stock and failed (1 failed, 14
errors off-GPU). Remove the eager patch before capturing the stock forwards
and before each test, so the suite passes in either file order on CPU and GPU.
@danielhanchen danielhanchen self-assigned this Oct 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 5, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

ℹ️ 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 +332 to +334
if out is None:
COUNTS["adaln_stock"] += 1
out = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]

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 Avoid mutating counters while Dynamo traces AdaLN

When UNSLOTH_DIFFUSION_FUSED_ADALN=1 is combined with the default/max compiled speed profile (including the deferred third-generation profile), _fused_modulate() deliberately returns None while Dynamo is tracing, but this branch then mutates the global COUNTS dictionary. That Python side effect causes a graph break, and resident uncached loads request fullgraph=True in diffusion.py, so compilation can fail instead of using the intended stock compiled math. Suppress counter updates while compiling in all three fused AdaLN forwards.

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.

Not reproducible: with UNSLOTH_DIFFUSION_FUSED_ADALN=1, torch.compile(fullgraph=True) of AdaLayerNormZero, AdaLayerNormZeroSingle and AdaLayerNormContinuous all compile without a break on torch 2.13; Dynamo records the global dict increment as a replayed side effect, not a graph break.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 7bd0b888f8

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 5, 2026
@danielhanchen
danielhanchen merged commit ec1d67b into main Oct 5, 2026
@danielhanchen
danielhanchen deleted the studio/amd-diffusion-fused-rope branch October 5, 2026 11:42
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Nov 5, 2026
…% 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.
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