Repository navigation
Studio: fused RoPE for FLUX on ROCm (FLUX.2-klein 8% faster per image, pixel-identical) - #12701
Conversation
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.
…identical); fused RoPE stays auto
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. |
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. |
|
All three red checks here ( |
…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.
…ip tests without torch
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if out is None: | ||
| COUNTS["adaln_stock"] += 1 | ||
| out = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
…% 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.
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_embupcasts q and k to float32, builds the rotated copy withstack, 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/AdaLayerNormContinuousrunlayer_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 fromload_pipelinenext to the FLUX.2 RoPE patch and removed in_uninstall_fused_dit_patches:apply_rotary_emboftransformer_fluxandtransformer_flux2points at a wrapper that launches the existingdiffusion_flux2_ropeTriton kernel for bf16 and fp16. Float32 math with FMA contraction off, one rounding, so the output is bit-identical to stock.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), soautoleaves it off and only=1turns it on.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;1opts 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-matrixfreqs_cislayout 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.
fusedis this PR's default on ROCm. The other Studio arms set the switches.COMFY_KITCHEN_DISABLE_HIP=1Kernel 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.
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.autostays off on CUDA, and on ROCm engages RoPE only; AdaLN needs=1.0disables,1forces 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.diffusion.py, and the reimplemented diffusers lines are still present.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
video_wan_fused.py) is fp16 CUDA only; Qwen-Image uses the complexapply_rotary_emb_qwen.norm2modulation inFluxTransformerBlock.forwardstays stock.test_diffusion_arch_patches.py::test_install_idempotent_and_reversiblefails on this host independently of this change (it imports neither changed file; patch count against diffusers 0.41.0.dev0).