Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Hanec1d67b57871
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.json
index 40a6ae362e5..e8e985fdf5a 100644
--- a/scripts/risky_loaders_baseline.json
+++ b/scripts/risky_loaders_baseline.json
@@ -138,6 +138,14 @@
"count": 1,
"reason": "Module name comes from a fixed table or constant in this file, not from a model, request or download."
},
+ {
+ "file": "studio/backend/core/inference/diffusion_rocm_fused.py",
+ "rule": "dynamic-import",
+ "sink": "import_module",
+ "digest": "59e72c01edb14c86",
+ "count": 1,
+ "reason": "install_rope only imports a name already in _ROPE_FNS, which is built from the fixed _MODULES tuple of two diffusers Flux transformer modules."
+ },
{
"file": "studio/backend/core/inference/diffusion_torchao_patches.py",
"rule": "dynamic-import",
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index d7555c68f8e..635f669e552 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -1906,6 +1906,11 @@ def _uninstall_fused_dit_patches() -> None:
uninstall_flux2_rope()
except Exception: # noqa: BLE001 - teardown is best effort
pass
+ try:
+ from .diffusion_rocm_fused import uninstall as uninstall_rocm_fused
+ uninstall_rocm_fused()
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
def _clear_exception_frames(exc: BaseException) -> None:
@@ -7033,6 +7038,10 @@ class DiffusionBackend:
from .diffusion_flux2_rope import install_for_pipe as install_flux2_rope
install_flux2_rope(pipe, dtype, device, logger)
+ # ROCm (auto) FLUX.1 / FLUX.2: one-kernel RoPE (bit-identical) and AdaLN modulation.
+ from .diffusion_rocm_fused import install_for_pipe as install_rocm_fused
+
+ install_rocm_fused(pipe, dtype, device, logger)
# fp16-only cards: a guarded family stays float16; patch its overflow sites.
from .diffusion_fp16_guard import family_fp16_guard, install_fp16_guard
@@ -7490,6 +7499,7 @@ class DiffusionBackend:
if eager_patched:
uninstall_patches()
uninstall_arch_patches()
+ _uninstall_fused_dit_patches()
state = pipe = transformer = None
pipe_kwargs.clear()
clear_gpu_cache()
@@ -10246,6 +10256,8 @@ class DiffusionBackend:
uninstall_patches()
uninstall_arch_patches()
+ # Again: the deferred profile layers the eager patch over the fused AdaLN.
+ _uninstall_fused_dit_patches()
# Deliberately NOT unload_lora_weights(): the whole pipe is dropped below, freeing any adapters with it. Drop
# the workflow pipes so they do not pin the freed pipeline modules past unload.
self._aux_pipes.clear()
diff --git a/studio/backend/core/inference/diffusion_rocm_fused.py b/studio/backend/core/inference/diffusion_rocm_fused.py
new file mode 100644
index 00000000000..f959e9c7987
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_rocm_fused.py
@@ -0,0 +1,486 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Fused RoPE and AdaLN modulation Triton kernels for the FLUX DiT on ROCm (bf16 / fp16).
+
+RoPE reuses ``diffusion_flux2_rope``'s kernel (bit-identical to stock). AdaLN keeps stock's rounding chain; only the
+row-reduction order differs. Inference only, never while compiling; any ineligible call runs the forward live at
+install. ``UNSLOTH_DIFFUSION_FUSED_ROPE=auto|0|1`` (auto = ROCm only), ``UNSLOTH_DIFFUSION_FUSED_ADALN=auto|0|1``
+(auto = off: no gfx1151 speedup and not bit-identical).
+"""
+
+from __future__ import annotations
+
+import functools
+import os
+import sys
+import threading
+from typing import Any, Callable, Optional
+
+FUSED_ROPE_ENV = "UNSLOTH_DIFFUSION_FUSED_ROPE"
+FUSED_ADALN_ENV = "UNSLOTH_DIFFUSION_FUSED_ADALN"
+_MODULES = (
+ "diffusers.models.transformers.transformer_flux",
+ "diffusers.models.transformers.transformer_flux2",
+)
+_ROPE_ATTR = "apply_rotary_emb"
+_ADALN_CLASSES = ("AdaLayerNormZero", "AdaLayerNormZeroSingle", "AdaLayerNormContinuous")
+_MAX_D = 16384
+
+_LOCK = threading.Lock()
+_ROPE_STOCK: dict = {}
+_ADALN_PREV: dict = {}
+# Survives uninstall, so a fused forward restored later by another layer still reaches a real forward.
+_ADALN_ORIGINAL: dict = {}
+COUNTS = {"rope_fused": 0, "rope_stock": 0, "adaln_fused": 0, "adaln_stock": 0}
+
+
+def _mode(env: str) -> str:
+ v = (os.environ.get(env) or "auto").strip().lower()
+ if v in ("0", "off", "false", "no"):
+ return "off"
+ if v in ("1", "on", "true", "yes", "force"):
+ return "on"
+ return "auto"
+
+
+def _is_rocm() -> bool:
+ try:
+ import torch
+ except Exception: # noqa: BLE001
+ return False
+ return bool(getattr(torch.version, "hip", None))
+
+
+# gfx1151 klein 1024^2: RoPE 8.76 -> 8.09 s pixel-identical; AdaLN adds no speed and moves pixels (LPIPS 0.004).
+_AUTO_ON = {FUSED_ROPE_ENV: True, FUSED_ADALN_ENV: False}
+
+
+def _switch_on(env: str) -> bool:
+ mode = _mode(env)
+ return mode == "on" or (mode == "auto" and _AUTO_ON.get(env, False) and _is_rocm())
+
+
+def wanted(
+ env: str,
+ dtype: Any,
+ device: Any = "cuda",
+) -> bool:
+ if not _switch_on(env):
+ return False
+ try:
+ import torch
+ except Exception: # noqa: BLE001
+ return False
+ if dtype not in (torch.bfloat16, torch.float16) or not str(device).startswith("cuda"):
+ return False
+ if env == FUSED_ROPE_ENV:
+ return _rope_kernel() is not None
+ return _adaln_kernel() is not None
+
+
+# ----------------------------------------------------------------------------------------------------------------- RoPE
[email protected]_cache(maxsize = 1)
+def _rope_kernel() -> Optional[Callable]:
+ from .diffusion_flux2_rope import _kernel
+ return _kernel()
+
+
+def _rope_eligible(
+ x: Any, freqs_cis: Any, use_real: bool, use_real_unbind_dim: int, sequence_dim: int
+) -> bool:
+ import torch
+
+ if not use_real or use_real_unbind_dim != -1 or sequence_dim != 1:
+ return False
+ if not isinstance(freqs_cis, (tuple, list)) or len(freqs_cis) != 2:
+ return False
+ if (
+ not torch.is_tensor(x)
+ or x.dtype not in (torch.bfloat16, torch.float16)
+ or not x.is_cuda
+ or x.dim() != 4
+ ):
+ return False
+ if x.requires_grad and torch.is_grad_enabled():
+ return False
+ B, S, H, D = x.shape
+ if D % 2 or x.stride(3) != 1 or x.numel() == 0:
+ return False
+ # Kernel offsets are int32.
+ if x.storage_offset() + sum((n - 1) * st for n, st in zip(x.shape, x.stride())) >= 2**31 - 1:
+ return False
+ for f in freqs_cis:
+ if not torch.is_tensor(f) or f.dim() != 2 or tuple(f.shape) != (S, D):
+ return False
+ if f.device != x.device or f.stride(1) != 1 or f.dtype is not torch.float32:
+ return False
+ return True
+
+
+def _make_rope(module_name: str) -> Callable:
+ def _fused_apply_rotary_emb(
+ x,
+ freqs_cis,
+ use_real: bool = True,
+ use_real_unbind_dim: int = -1,
+ sequence_dim: int = 2,
+ ):
+ import torch
+
+ stock = _ROPE_STOCK.get(module_name) or _ROPE_ORIGINAL[module_name]
+ # Checked first: Dynamo graph-breaks on Triton's import path, so a compiled block stays whole on stock.
+ if not torch.compiler.is_compiling():
+ launch = _rope_kernel()
+ if launch is not None and _rope_eligible(
+ x, freqs_cis, use_real, use_real_unbind_dim, sequence_dim
+ ):
+ try:
+ out = launch(x, freqs_cis[0], freqs_cis[1])
+ COUNTS["rope_fused"] += 1
+ return out
+ except Exception: # noqa: BLE001 -- never fail a render over the fast path
+ pass
+ COUNTS["rope_stock"] += 1
+ return stock(
+ x,
+ freqs_cis,
+ use_real = use_real,
+ use_real_unbind_dim = use_real_unbind_dim,
+ sequence_dim = sequence_dim,
+ )
+
+ _fused_apply_rotary_emb.__unsloth_fused_rope__ = module_name
+ return _fused_apply_rotary_emb
+
+
+# Survives uninstall so a forward that looked up the patch just before teardown still reaches stock.
+_ROPE_ORIGINAL: dict = {}
+_ROPE_FNS: dict = {m: _make_rope(m) for m in _MODULES}
+
+
+def install_rope(
+ module_name: str,
+ dtype: Any,
+ device: Any = "cuda",
+) -> bool:
+ if module_name not in _ROPE_FNS or not wanted(FUSED_ROPE_ENV, dtype, device):
+ uninstall_rope()
+ return False
+ import importlib
+
+ with _LOCK:
+ if module_name in _ROPE_STOCK:
+ return True
+ try:
+ mod = importlib.import_module(module_name)
+ except Exception: # noqa: BLE001
+ return False
+ stock = getattr(mod, _ROPE_ATTR, None)
+ # Anything but diffusers' own function (another fused patch, a changed symbol) is left alone.
+ if stock is None or getattr(stock, "__name__", "") != "apply_rotary_emb":
+ return False
+ _ROPE_STOCK[module_name] = stock
+ _ROPE_ORIGINAL[module_name] = stock
+ setattr(mod, _ROPE_ATTR, _ROPE_FNS[module_name])
+ return True
+
+
+def uninstall_rope() -> None:
+ with _LOCK:
+ for name in list(_ROPE_STOCK):
+ stock = _ROPE_STOCK.pop(name)
+ mod = sys.modules.get(name)
+ if mod is not None and getattr(mod, _ROPE_ATTR, None) is _ROPE_FNS[name]:
+ setattr(mod, _ROPE_ATTR, stock)
+
+
+# ----------------------------------------------------------------------------------------------------------------- AdaLN
[email protected]_cache(maxsize = 1)
+def _adaln_kernel() -> Optional[Callable]:
+ try:
+ import triton
+ import triton.language as tl
+ except Exception: # noqa: BLE001
+ return None
+
+ @triton.jit
+ def _adaln_fwd(
+ X, SCALE, SHIFT, OUT, S, D, sxb, sxs, scb, shb, sob, sos, eps, BLOCK: tl.constexpr
+ ):
+ row = tl.program_id(0)
+ b = row // S
+ s = row - b * S
+ cols = tl.arange(0, BLOCK)
+ mask = cols < D
+ x = tl.load(X + b * sxb + s * sxs + cols, mask = mask, other = 0.0).to(tl.float32)
+ mean = tl.sum(x, axis = 0) / D
+ xc = tl.where(mask, x - mean, 0.0)
+ var = tl.sum(xc * xc, axis = 0) / D
+ rstd = 1.0 / tl.sqrt(var + eps)
+ dt = OUT.dtype.element_ty
+ # stock: layer_norm (rounded) * (1 + scale) (rounded) -> product (rounded) + shift (rounded)
+ n = (xc * rstd).to(dt)
+ sc = tl.load(SCALE + b * scb + cols, mask = mask, other = 0.0).to(tl.float32)
+ m = (1.0 + sc).to(dt)
+ p = (n.to(tl.float32) * m.to(tl.float32)).to(dt)
+ sh = tl.load(SHIFT + b * shb + cols, mask = mask, other = 0.0).to(tl.float32)
+ o = (p.to(tl.float32) + sh).to(dt)
+ tl.store(OUT + b * sob + s * sos + cols, o, mask = mask)
+
+ def launch(x: Any, scale: Any, shift: Any, eps: float) -> Any:
+ import torch
+
+ B, S, D = x.shape
+ out = torch.empty((B, S, D), dtype = x.dtype, device = x.device)
+ block = triton.next_power_of_2(D)
+ with torch.cuda.device(x.device):
+ _adaln_fwd[(B * S,)](
+ x,
+ scale,
+ shift,
+ out,
+ S,
+ D,
+ x.stride(0),
+ x.stride(1),
+ scale.stride(0),
+ shift.stride(0),
+ out.stride(0),
+ out.stride(1),
+ float(eps),
+ BLOCK = block,
+ num_warps = 4 if block <= 1024 else (8 if block <= 4096 else 16),
+ enable_fp_fusion = False,
+ )
+ return out
+
+ return launch
+
+
+def _plain_layer_norm(norm: Any) -> Optional[float]:
+ """eps when ``norm`` is a plain ``nn.LayerNorm`` with no affine over the last dim, else None."""
+ import torch
+
+ if type(norm) is not torch.nn.LayerNorm or norm.weight is not None or norm.bias is not None:
+ return None
+ if len(tuple(norm.normalized_shape)) != 1:
+ return None
+ return float(norm.eps)
+
+
+def _fused_modulate(norm: Any, x: Any, scale: Any, shift: Any) -> Optional[Any]:
+ """``norm(x) * (1 + scale[:, None]) + shift[:, None]`` in one kernel, or None when not eligible."""
+ import torch
+
+ if torch.compiler.is_compiling():
+ return None
+ eps = _plain_layer_norm(norm)
+ if eps is None or not torch.is_tensor(x) or not x.is_cuda or x.dim() != 3:
+ return None
+ if torch.is_grad_enabled() and (x.requires_grad or scale.requires_grad or shift.requires_grad):
+ return None
+ B, S, D = x.shape
+ if (
+ x.dtype not in (torch.bfloat16, torch.float16)
+ or D > _MAX_D
+ or D != norm.normalized_shape[0]
+ or x.numel() == 0
+ ):
+ return None
+ if x.stride(2) != 1 or x.numel() >= 2**31 - 1:
+ return None
+ for t in (scale, shift):
+ if (
+ not torch.is_tensor(t)
+ or t.dtype is not x.dtype
+ or t.device != x.device
+ or tuple(t.shape) != (B, D)
+ ):
+ return None
+ if t.stride(1) != 1:
+ return None
+ launch = _adaln_kernel()
+ if launch is None:
+ return None
+ try:
+ return launch(x, scale, shift, eps)
+ except Exception: # noqa: BLE001 -- never fail a render over the fast path
+ return None
+
+
+def _prev(cls: type) -> Callable:
+ prev = _ADALN_PREV.get(cls)
+ return prev if prev is not None else _ADALN_ORIGINAL[cls]
+
+
+def _adaln_zero_forward(
+ self,
+ x,
+ timestep = None,
+ class_labels = None,
+ hidden_dtype = None,
+ emb = None,
+):
+ cls = _CLASSES["AdaLayerNormZero"]
+ if self.emb is not None or timestep is not None or class_labels is not None:
+ COUNTS["adaln_stock"] += 1
+ return _prev(cls)(self, x, timestep, class_labels, hidden_dtype, emb)
+ e = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = e.chunk(6, dim = 1)
+ out = _fused_modulate(self.norm, x, scale_msa, shift_msa)
+ if out is None:
+ COUNTS["adaln_stock"] += 1
+ out = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ else:
+ COUNTS["adaln_fused"] += 1
+ return out, gate_msa, shift_mlp, scale_mlp, gate_mlp
+
+
+def _adaln_zero_single_forward(
+ self,
+ x,
+ emb = None,
+):
+ e = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa = e.chunk(3, dim = 1)
+ out = _fused_modulate(self.norm, x, scale_msa, shift_msa)
+ if out is None:
+ COUNTS["adaln_stock"] += 1
+ out = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ else:
+ COUNTS["adaln_fused"] += 1
+ return out, gate_msa
+
+
+def _adaln_continuous_forward(self, x, conditioning_embedding):
+ e = self.linear(self.silu(conditioning_embedding).to(x.dtype))
+ scale, shift = e.chunk(2, dim = 1)
+ out = _fused_modulate(self.norm, x, scale, shift)
+ if out is None:
+ COUNTS["adaln_stock"] += 1
+ out = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
+ else:
+ COUNTS["adaln_fused"] += 1
+ return out
+
+
+_FORWARDS = {
+ "AdaLayerNormZero": _adaln_zero_forward,
+ "AdaLayerNormZeroSingle": _adaln_zero_single_forward,
+ "AdaLayerNormContinuous": _adaln_continuous_forward,
+}
+# Source lines the fused forwards reimplement: a diffusers release that changes them keeps the stock class.
+_STOCK_LINES = {
+ "AdaLayerNormZero": (
+ "shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)",
+ "x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]",
+ ),
+ "AdaLayerNormZeroSingle": (
+ "shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)",
+ "x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]",
+ ),
+ "AdaLayerNormContinuous": (
+ "emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))",
+ "scale, shift = torch.chunk(emb, 2, dim=1)",
+ "x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]",
+ ),
+}
+_CLASSES: dict = {}
+
+
+def _stock_classes() -> dict:
+ if not _CLASSES:
+ try:
+ from diffusers.models import normalization as nm
+ except Exception: # noqa: BLE001
+ return {}
+ for name in _ADALN_CLASSES:
+ cls = getattr(nm, name, None)
+ if cls is not None:
+ _CLASSES[name] = cls
+ return _CLASSES
+
+
+def _stock_body_ok(cls: type, name: str) -> bool:
+ import inspect
+
+ # The stock body is checked on the ORIGINAL forward (the Studio eager patch may be live on top of it).
+ fn = cls.__dict__.get("forward")
+ for cand in (getattr(fn, "__wrapped__", None), fn):
+ if cand is None:
+ continue
+ try:
+ src = inspect.getsource(cand)
+ except (OSError, TypeError):
+ continue
+ if all(line in src for line in _STOCK_LINES[name]):
+ return True
+ return False
+
+
+def install_adaln(dtype: Any, device: Any = "cuda") -> int:
+ """Wrap the live AdaLN forwards (stock or Studio's eager addcmul patch). Returns the number wrapped."""
+ uninstall_adaln()
+ if not wanted(FUSED_ADALN_ENV, dtype, device):
+ return 0
+ classes = _stock_classes()
+ with _LOCK:
+ for name, cls in classes.items():
+ live = cls.forward
+ # Studio's eager addcmul patch was fingerprinted against the same stock body at its own install.
+ ours = (getattr(live, "__module__", "") or "").endswith("diffusion_eager_patches")
+ if not ours and not _stock_body_ok(cls, name):
+ continue
+ _ADALN_PREV[cls] = live
+ _ADALN_ORIGINAL.setdefault(cls, live)
+ cls.forward = _FORWARDS[name]
+ return len(_ADALN_PREV)
+
+
+def uninstall_adaln() -> None:
+ with _LOCK:
+ for cls, prev in list(_ADALN_PREV.items()):
+ # Not ours on top (deferred eager patch): keep the entry for the uninstall after that layer's.
+ if cls.__dict__.get("forward") in _FORWARDS.values():
+ cls.forward = prev
+ del _ADALN_PREV[cls]
+
+
+# ------------------------------------------------------------------------------------------------------------- lifecycle
+def install_for_pipe(
+ pipe: Any,
+ dtype: Any,
+ device: Any = "cuda",
+ logger: Any = None,
+) -> dict:
+ """Install for a FLUX.1 / FLUX.2 denoiser, otherwise restore stock."""
+ transformer = getattr(pipe, "transformer", None)
+ module_name = type(transformer).__module__ if transformer is not None else ""
+ if module_name not in _MODULES:
+ uninstall()
+ return {"rope": False, "adaln": 0}
+ uninstall()
+ rope = install_rope(module_name, dtype, device)
+ adaln = install_adaln(dtype, device)
+ if logger is not None and (rope or adaln):
+ try:
+ logger.info(
+ "diffusion.rocm_fused: fused RoPE %s, fused AdaLN on %d classes",
+ "on" if rope else "off",
+ adaln,
+ )
+ except Exception: # noqa: BLE001
+ pass
+ return {"rope": rope, "adaln": adaln}
+
+
+def uninstall() -> None:
+ uninstall_rope()
+ uninstall_adaln()
+
+
+def is_installed() -> bool:
+ return bool(_ROPE_STOCK) or any(
+ cls.__dict__.get("forward") in _FORWARDS.values() for cls in _ADALN_PREV
+ )
diff --git a/studio/backend/tests/test_diffusion_rocm_fused.py b/studio/backend/tests/test_diffusion_rocm_fused.py
new file mode 100644
index 00000000000..80e49141aa4
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_rocm_fused.py
@@ -0,0 +1,336 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for ``diffusion_rocm_fused.py``: the switches (auto = ROCm only), install / uninstall wiring, and on a GPU the
+kernels against diffusers (RoPE bit-identical, AdaLN within one rounding of stock) plus a tiny FLUX.1 transformer."""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion_eager_patches as ep # noqa: E402
+from core.inference import diffusion_rocm_fused as rf # noqa: E402
+
+fmod = pytest.importorskip("diffusers.models.transformers.transformer_flux")
+from diffusers.models import normalization as nm # noqa: E402
+from diffusers.models.embeddings import apply_rotary_emb as stock_rope # noqa: E402
+
+# Another test file in the same session may leave Studio's eager AdaLN patch live on the classes: start from stock.
+ep.uninstall_patches()
+_STOCK_FWD = {name: getattr(nm, name).forward for name in rf._ADALN_CLASSES}
+
+needs_gpu = pytest.mark.skipif(
+ not torch.cuda.is_available() or rf._rope_kernel() is None or rf._adaln_kernel() is None,
+ reason = "needs a CUDA / ROCm GPU and Triton",
+)
+
+
+class _PipeLike:
+ def __init__(self, module = "diffusers.models.transformers.transformer_flux"):
+ self.transformer = type("FluxTransformer2DModel", (), {"__module__": module})()
+
+
[email protected](autouse = True)
+def _restore(monkeypatch):
+ monkeypatch.delenv(rf.FUSED_ROPE_ENV, raising = False)
+ monkeypatch.delenv(rf.FUSED_ADALN_ENV, raising = False)
+ rf.uninstall()
+ ep.uninstall_patches()
+ yield
+ rf.uninstall()
+ assert fmod.apply_rotary_emb is stock_rope
+ for name, fwd in _STOCK_FWD.items():
+ assert getattr(nm, name).forward is fwd
+
+
+def fake_kernels(monkeypatch):
+ monkeypatch.setattr(rf, "_rope_kernel", lambda: (lambda x, cos, sin: None))
+ monkeypatch.setattr(rf, "_adaln_kernel", lambda: (lambda x, scale, shift, eps: None))
+
+
+def test_auto_is_inert_off_rocm(fake_kernels, monkeypatch):
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ assert rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda") == {"rope": False, "adaln": 0}
+ assert not rf.is_installed()
+
+
+def test_auto_engages_rope_only_on_rocm(fake_kernels, monkeypatch):
+ # auto = the bit-identical RoPE kernel on ROCm; fused AdaLN bought no speed on gfx1151 and is opt-in.
+ monkeypatch.setattr(torch.version, "hip", "7.2.0", raising = False)
+ got = rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")
+ assert got == {"rope": True, "adaln": 0}
+ assert fmod.apply_rotary_emb is rf._ROPE_FNS[rf._MODULES[0]]
+ assert nm.AdaLayerNormZero.forward is _STOCK_FWD["AdaLayerNormZero"]
+
+
+def test_adaln_opt_in_on_rocm(fake_kernels, monkeypatch):
+ monkeypatch.setattr(torch.version, "hip", "7.2.0", raising = False)
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ got = rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")
+ assert got == {"rope": True, "adaln": 3}
+ assert nm.AdaLayerNormZero.forward is rf._adaln_zero_forward
+
+
[email protected]("value", ["0", "off", "false"])
+def test_kill_switches_on_rocm(fake_kernels, monkeypatch, value):
+ monkeypatch.setattr(torch.version, "hip", "7.2.0", raising = False)
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, value)
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, value)
+ assert rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda") == {"rope": False, "adaln": 0}
+
+
+def test_force_on_engages_on_cuda(fake_kernels, monkeypatch):
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ assert rf.install_for_pipe(_PipeLike(), torch.float16, "cuda") == {"rope": True, "adaln": 3}
+
+
+def test_switches_are_independent(fake_kernels, monkeypatch):
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "0")
+ assert rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda") == {"rope": True, "adaln": 0}
+
+
+def test_fp32_cpu_and_other_families_stay_stock(fake_kernels, monkeypatch):
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ assert rf.install_for_pipe(_PipeLike(), torch.float32, "cuda") == {"rope": False, "adaln": 0}
+ assert rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cpu") == {"rope": False, "adaln": 0}
+ other = _PipeLike("diffusers.models.transformers.transformer_qwenimage")
+ assert rf.install_for_pipe(other, torch.bfloat16, "cuda") == {"rope": False, "adaln": 0}
+
+
+def test_no_triton_keeps_stock(monkeypatch):
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ monkeypatch.setattr(rf, "_rope_kernel", lambda: None)
+ monkeypatch.setattr(rf, "_adaln_kernel", lambda: None)
+ assert rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda") == {"rope": False, "adaln": 0}
+
+
+def test_reinstall_is_clean(fake_kernels, monkeypatch):
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ for _ in range(2):
+ rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")
+ # the second install must not have stashed the first install's fused forward as "previous"
+ assert all(prev not in rf._FORWARDS.values() for prev in rf._ADALN_PREV.values())
+
+
+def test_cpu_tensors_fall_through(fake_kernels, monkeypatch):
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")
+ x = torch.randn(1, 6, 2, 8)
+ pos = torch.randn(6, 4, dtype = torch.float64)
+ freqs = (pos.cos().repeat_interleave(2, -1).float(), pos.sin().repeat_interleave(2, -1).float())
+ assert torch.equal(
+ fmod.apply_rotary_emb(x, freqs, sequence_dim = 1), stock_rope(x, freqs, sequence_dim = 1)
+ )
+ torch.manual_seed(0)
+ norm = nm.AdaLayerNormZero(16)
+ xs, emb = torch.randn(2, 5, 16), torch.randn(2, 16)
+ got = norm(xs, emb = emb)
+ want = _STOCK_FWD["AdaLayerNormZero"](norm, xs, emb = emb)
+ assert all(torch.equal(a, b) for a, b in zip(got, want))
+
+
+def test_load_and_teardown_wiring():
+ src = (Path(__file__).resolve().parents[1] / "core" / "inference" / "diffusion.py").read_text(
+ encoding = "utf-8"
+ )
+ tree = ast.parse(src)
+ teardown = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_uninstall_fused_dit_patches"
+ )
+ assert "uninstall_rocm_fused()" in ast.unparse(teardown)
+ # Both unload paths unwind the fused AdaLN again after the eager layer (deferred profile installs it on top).
+ assert src.count("_uninstall_fused_dit_patches()") >= 4
+ load = next(
+ n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "load_pipeline"
+ )
+ assert "install_rocm_fused(pipe, dtype, device, logger)" in ast.unparse(load)
+
+
+def test_stock_lines_still_present_in_diffusers():
+ import inspect
+ for name in rf._ADALN_CLASSES:
+ src = inspect.getsource(_STOCK_FWD[name])
+ assert all(line in src for line in rf._STOCK_LINES[name]), name
+ assert "apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)" in Path(
+ fmod.__file__
+ ).read_text("utf-8")
+
+
+# ---------------------------------------------------------------------------------------------------------------- GPU
+def _freqs(S, D, device):
+ pos = torch.randn(S, D // 2, dtype = torch.float64, device = device) * 50
+ return (pos.cos().repeat_interleave(2, -1).float(), pos.sin().repeat_interleave(2, -1).float())
+
+
+@needs_gpu
[email protected]("dtype", [torch.bfloat16, torch.float16])
[email protected]("shape", [(1, 4608, 24, 128), (2, 333, 3, 64)])
+def test_rope_bit_identical(monkeypatch, dtype, shape):
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ dev = "cuda"
+ assert rf.install_for_pipe(_PipeLike(), dtype, dev)["rope"]
+ B, S, H, D = shape
+ x = torch.randn(B, S, H, D, device = dev).to(dtype)
+ freqs = _freqs(S, D, dev)
+ before = rf.COUNTS["rope_fused"]
+ with torch.no_grad():
+ got = fmod.apply_rotary_emb(x, freqs, sequence_dim = 1)
+ want = stock_rope(x, freqs, sequence_dim = 1)
+ assert rf.COUNTS["rope_fused"] == before + 1
+ assert torch.equal(got, want)
+
+
+def _bf16_ulp(t):
+ a = t.float().abs().clamp_min(2.0**-126)
+ return torch.exp2(torch.floor(torch.log2(a)) - (7 if t.dtype is torch.bfloat16 else 10))
+
+
+@needs_gpu
[email protected]("dtype", [torch.bfloat16, torch.float16])
+ "cls_name,D,S",
+ [
+ ("AdaLayerNormZero", 3072, 4096),
+ ("AdaLayerNormZeroSingle", 3072, 777),
+ ("AdaLayerNormContinuous", 256, 300),
+ ],
+)
+def test_adaln_matches_stock(monkeypatch, dtype, cls_name, D, S):
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ dev = "cuda"
+ torch.manual_seed(0)
+ cls = getattr(nm, cls_name)
+ if cls_name == "AdaLayerNormContinuous":
+ mod = cls(D, D, elementwise_affine = False, eps = 1e-6)
+ else:
+ mod = cls(D)
+ mod = mod.to(dev, dtype).eval()
+ assert rf.install_for_pipe(_PipeLike(), dtype, dev)["adaln"] == 3
+ x = (torch.randn(2, S, D, device = dev) * 3 + 0.5).to(dtype)
+ emb = torch.randn(2, D, device = dev).to(dtype)
+ before = rf.COUNTS["adaln_fused"]
+ with torch.no_grad():
+ got = mod(x, emb) if cls_name == "AdaLayerNormContinuous" else mod(x, emb = emb)
+ want = (
+ _STOCK_FWD[cls_name](mod, x, emb)
+ if cls_name == "AdaLayerNormContinuous"
+ else _STOCK_FWD[cls_name](mod, x, emb = emb)
+ )
+ assert rf.COUNTS["adaln_fused"] == before + 1
+ got0, want0 = (got, want) if torch.is_tensor(got) else (got[0], want[0])
+ if not torch.is_tensor(got): # gates / mlp modulation pass through untouched
+ assert all(torch.equal(a, b) for a, b in zip(got[1:], want[1:]))
+ diff = (got0.float() - want0.float()).abs()
+ # The stock rounding chain is reproduced; only the row reduction order differs, which can flip the rounding of the
+ # normalised value by one ULP. Bound: that flip carried through the product, plus one rounding of product and sum.
+ with torch.no_grad():
+ e = mod.linear(mod.silu(emb))
+ scale = (
+ e.chunk(2, dim = 1)[0]
+ if cls_name == "AdaLayerNormContinuous"
+ else e.chunk(6 if cls_name == "AdaLayerNormZero" else 3, dim = 1)[1]
+ )
+ n = mod.norm(x)
+ m = (1 + scale)[:, None, :]
+ p = n * m
+ bound = 2 * (_bf16_ulp(n) * m.float().abs() + _bf16_ulp(p) + _bf16_ulp(want0))
+ assert (diff <= bound).all(), float((diff / bound).max())
+ assert (diff > 0).float().mean().item() < 0.01, (diff > 0).float().mean().item()
+
+
+@needs_gpu
+def test_tiny_flux1_transformer_end_to_end(monkeypatch):
+ from diffusers import FluxTransformer2DModel
+
+ monkeypatch.setenv(rf.FUSED_ROPE_ENV, "1")
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ dev, dtype = "cuda", torch.bfloat16
+ torch.manual_seed(0)
+ model = (
+ FluxTransformer2DModel(
+ patch_size = 1,
+ in_channels = 16,
+ num_layers = 2,
+ num_single_layers = 2,
+ attention_head_dim = 32,
+ num_attention_heads = 4,
+ joint_attention_dim = 64,
+ pooled_projection_dim = 32,
+ axes_dims_rope = (8, 12, 12),
+ )
+ .to(dev, dtype)
+ .eval()
+ )
+ B, img, txt = 1, 256, 32
+ inputs = dict(
+ hidden_states = torch.randn(B, img, 16, device = dev, dtype = dtype),
+ encoder_hidden_states = torch.randn(B, txt, 64, device = dev, dtype = dtype),
+ pooled_projections = torch.randn(B, 32, device = dev, dtype = dtype),
+ timestep = torch.tensor([0.5], device = dev, dtype = dtype),
+ img_ids = torch.randint(0, 16, (img, 3), device = dev).float(),
+ txt_ids = torch.zeros(txt, 3, device = dev),
+ return_dict = False,
+ )
+ with torch.no_grad():
+ want = model(**inputs)[0]
+ rf.install_for_pipe(type("P", (), {"transformer": model})(), dtype, dev)
+ r0, a0 = rf.COUNTS["rope_fused"], rf.COUNTS["adaln_fused"]
+ got = model(**inputs)[0]
+ # 2 double blocks (img + txt AdaLN, q + k RoPE) + 2 single blocks + norm_out
+ assert rf.COUNTS["rope_fused"] - r0 == 2 * 2 + 2 * 2
+ assert rf.COUNTS["adaln_fused"] - a0 == 2 * 2 + 2 + 1
+ rf.uninstall()
+ rel = (got.float() - want.float()).norm() / want.float().norm()
+ assert rel < 1e-2, float(rel)
+
+
+def test_teardown_survives_a_later_eager_layer(fake_kernels, monkeypatch):
+ # Deferred speed profile: fused AdaLN at load, Studio's eager patch layered on top at the 3rd image, then unload
+ # in the order diffusion.py uses (fused teardown first, eager after).
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ try:
+ assert rf.install_adaln(torch.bfloat16, "cuda") == len(rf._ADALN_CLASSES)
+ ep.install_compile_safe_patches()
+ assert nm.AdaLayerNormZero.forward is not rf._FORWARDS["AdaLayerNormZero"]
+ rf.uninstall()
+ ep.uninstall_patches()
+ rf.uninstall()
+ assert {n: getattr(nm, n).forward for n in rf._ADALN_CLASSES} == _STOCK_FWD
+ torch.manual_seed(0)
+ norm = nm.AdaLayerNormZero(16)
+ xs, emb = torch.randn(2, 5, 16), torch.randn(2, 16)
+ got = norm(xs, emb = emb)
+ want = _STOCK_FWD["AdaLayerNormZero"](norm, xs, emb = emb)
+ assert all(torch.equal(a, b) for a, b in zip(got, want))
+ finally:
+ ep.uninstall_patches()
+ rf.uninstall()
+ for n, fwd in _STOCK_FWD.items():
+ getattr(nm, n).forward = fwd
+
+
+def test_stock_branch_never_loses_its_previous_forward(fake_kernels, monkeypatch):
+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")
+ rf.install_adaln(torch.bfloat16, "cuda")
+ cls = nm.AdaLayerNormZero
+ rf._ADALN_PREV.clear()
+ try:
+ assert rf._prev(cls) is _STOCK_FWD["AdaLayerNormZero"]
+ finally:
+ for n, fwd in _STOCK_FWD.items():
+ getattr(nm, n).forward = fwd