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: flash attention by default for FLUX.2-klein on ROCm gfx11 (#12703)

Daniel Han9d8453e761ff
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 635f669e552..b130e3988d7 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -191,6 +191,7 @@ from .diffusion_vae_fp16 import enable_fp16_vae_decode
from .diffusion_vae_tiling import install as install_wide_vae_tiles
from .diffusion_attention import (
apply_attention_backend,
+ auto_attention_reason,
normalize_attention_backend,
sdpa_math_only,
sdpa_subquadratic_confirmed,
@@ -6914,7 +6915,11 @@ class DiffusionBackend:
attention_engaged = apply_attention_backend(
pipe,
select_attention_backend(
- target, attention_backend, speed_active = effective_speed != SPEED_OFF
+ target,
+ attention_backend,
+ speed_active = effective_speed != SPEED_OFF,
+ family = fam,
+ speed_unset = speed_mode is None,
),
logger = logger,
target = target,
@@ -7350,7 +7355,7 @@ class DiffusionBackend:
"attention_backend": (
attention_backend,
attention_engaged or "native",
- "cuDNN fused attention upgrade"
+ auto_attention_reason(attention_engaged)
if attention_engaged and attention_backend is None
else "diffusers default"
if attention_engaged is None
@@ -9171,7 +9176,9 @@ class DiffusionBackend:
# Re-run the load-time selection with the caller's ORIGINAL request: auto still upgrades to cuDNN here.
attention_engaged = apply_attention_backend(
state.pipe,
- select_attention_backend(target, state.attention_request, speed_active = True),
+ select_attention_backend(
+ target, state.attention_request, speed_active = True, family = state.family
+ ),
logger = logger,
target = target,
)
@@ -9239,9 +9246,7 @@ class DiffusionBackend:
att = (state.resolved or {}).get("attention_backend")
if isinstance(att, dict) and att.get("source") == "auto":
att["value"] = attention_engaged or "native"
- att["reason"] = (
- "cuDNN fused attention upgrade" if attention_engaged else "diffusers default"
- )
+ att["reason"] = auto_attention_reason(attention_engaged)
# The load recorded "speed tier does not capture" for the deferred tier; the profile that just engaged may
# have armed graphs, so re-derive the entry the same way the load does or the badge keeps saying "off".
graph = (state.resolved or {}).get("cuda_graph")
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index 75d21429d4b..0eb59028928 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -247,13 +247,19 @@ def warn_if_sdpa_math_only(target: Any, logger: Any = None) -> bool:
def select_attention_backend(
- target: Any, requested: Optional[str], *, speed_active: bool
+ target: Any,
+ requested: Optional[str],
+ *,
+ speed_active: bool,
+ family: Any = None,
+ speed_unset: bool = False,
) -> Optional[str]:
"""The dispatcher backend name to apply, or None to leave the diffusers default.
An explicit alias is honored (apply falls back if its kernel is unavailable). ``auto``
upgrades to cuDNN on NVIDIA CUDA only when a speed profile is active (so ``off`` stays
- bit-identical); elsewhere returns None (native)."""
+ bit-identical), and to verified ROCm flash for ``ROCM_AUTO_FLASH_FAMILIES`` on gfx11 unless speed is
+ explicitly ``off``; elsewhere returns None (native)."""
alias = normalize_attention_backend(requested)
if alias != ATTN_AUTO:
backend = _ALIASES[alias]
@@ -281,15 +287,73 @@ def select_attention_backend(
return "_native_cudnn"
if speed_active and ROCM_AUTO_FLASH and _is_cuda_rocm(target) and _rocm_flash_attn_runs(target):
return "flash"
+ if (speed_active or speed_unset) and _rocm_auto_flash(target, family):
+ return "flash"
return None
+def auto_attention_reason(engaged: Optional[str]) -> str:
+ """Status reason for an ``auto`` pick that engaged ``engaged`` (None = native)."""
+ if not engaged:
+ return "diffusers default"
+ if "cudnn" in engaged:
+ return "cuDNN fused attention upgrade"
+ if engaged == "flash":
+ return "verified ROCm flash attention"
+ return f"{engaged} attention upgrade"
+
+
def _is_cuda_rocm(target: Any) -> bool:
return getattr(target, "device", None) == "cuda" and not _is_cuda_nvidia(target)
# ``auto`` -> verified ROCm flash under a speed profile. Off: gfx1151 gains over AOTriton SDPA were too small/narrow.
ROCM_AUTO_FLASH = False
+# Also with speed unset (the UI default). gfx1151 klein 1024^2: 7.37-7.40 s vs SDPA 8.04-8.09 s, LPIPS 0.008.
+# FLUX.1 measured LPIPS 0.048 vs SDPA (over the 0.02 bar): stays native.
+ROCM_AUTO_FLASH_FAMILIES = frozenset({"flux.2-klein"})
+ROCM_AUTO_FLASH_ARCHES = ("gfx11",)
+
+
+def _rocm_gfx_arch(target: Any) -> str:
+ try:
+ import torch
+ from utils.hardware.hardware import _props_gfx_arch
+
+ device = torch.device(
+ _indexed_cuda_device(
+ str(getattr(target, "torch_device", None) or getattr(target, "device", None) or "")
+ )
+ )
+ index = device.index if device.index is not None else torch.cuda.current_device()
+ return _props_gfx_arch(torch.cuda.get_device_properties(index))
+ except Exception: # noqa: BLE001
+ return ""
+
+
+def _flash_attn_installed() -> bool:
+ """Without importing it, so an ``auto`` load on a card without flash_attn logs nothing."""
+ import sys
+
+ if "flash_attn" in sys.modules:
+ return sys.modules["flash_attn"] is not None
+ try:
+ import importlib.util
+ return importlib.util.find_spec("flash_attn") is not None
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _rocm_auto_flash(target: Any, family: Any) -> bool:
+ if not _is_cuda_rocm(target):
+ return False
+ name = family if isinstance(family, str) else getattr(family, "name", None)
+ if name not in ROCM_AUTO_FLASH_FAMILIES:
+ return False
+ if not _rocm_gfx_arch(target).startswith(ROCM_AUTO_FLASH_ARCHES):
+ return False
+ return _flash_attn_installed() and _rocm_flash_attn_runs(target)
+
# Max abs error of the probe's flash_attn output against an fp32 reference (bf16 eps is ~4e-3).
_ROCM_FLASH_PROBE_TOL = 2e-2
diff --git a/studio/backend/tests/test_diffusion_attention_rocm_flash.py b/studio/backend/tests/test_diffusion_attention_rocm_flash.py
index c9e04529045..2c8e59475fa 100644
--- a/studio/backend/tests/test_diffusion_attention_rocm_flash.py
+++ b/studio/backend/tests/test_diffusion_attention_rocm_flash.py
@@ -240,3 +240,149 @@ def test_cudnn_head_dim_probe_still_answers_fp32_at_bf16(monkeypatch):
)
assert att._run_cudnn_head_dim_probe("cpu", torch.float32, 128) is True
assert seen == [torch.bfloat16]
+
+
+# ``auto`` -> flash for FLUX.2-klein on ROCm gfx11 (measured on gfx1151); every other family and arch unchanged.
+
+
+def _klein():
+ return types.SimpleNamespace(name = "flux.2-klein")
+
+
+def _arch(monkeypatch, arch = "gfx1151"):
+ monkeypatch.setattr(att, "_rocm_gfx_arch", lambda target: arch)
+
+
+def test_rocm_auto_flash_for_klein_on_gfx11(monkeypatch):
+ calls = _rocm(monkeypatch)
+ _arch(monkeypatch)
+ assert (
+ select_attention_backend(_target(), "auto", speed_active = True, family = _klein()) == "flash"
+ )
+ assert (
+ select_attention_backend(_target(), None, speed_active = True, family = "flux.2-klein")
+ == "flash"
+ )
+ # unset speed (ROCm resolves it to `off`): the default path, so flash too
+ assert (
+ select_attention_backend(
+ _target(), "auto", speed_active = False, family = _klein(), speed_unset = True
+ )
+ == "flash"
+ )
+ # an explicit `off` stays native (the bit-identical reference path)
+ assert select_attention_backend(_target(), "auto", speed_active = False, family = _klein()) is None
+ assert calls == [("cuda:0", "torch.bfloat16")]
+
+
[email protected]("family", ["flux.1", "flux.2", "z-image", "qwen-image", "sdxl", None])
+def test_rocm_auto_stays_native_for_unmeasured_families(monkeypatch, family):
+ calls = _rocm(monkeypatch)
+ _arch(monkeypatch)
+ fam = None if family is None else types.SimpleNamespace(name = family)
+ assert select_attention_backend(_target(), "auto", speed_active = True, family = fam) is None
+ assert (
+ select_attention_backend(
+ _target(), "auto", speed_active = False, family = fam, speed_unset = True
+ )
+ is None
+ )
+ assert calls == []
+
+
+def test_rocm_gfx_arch_reads_the_selected_card(monkeypatch):
+ import torch
+
+ asked = []
+
+ def props(index):
+ asked.append(index)
+ return types.SimpleNamespace(gcnArchName = "gfx1100" if index == 1 else "gfx90a")
+
+ monkeypatch.setattr(torch.cuda, "get_device_properties", props)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ target = types.SimpleNamespace(device = "cuda", torch_device = "cuda:1", dtype = "torch.bfloat16")
+ assert att._rocm_gfx_arch(target) == "gfx1100"
+ assert asked == [1]
+
+
[email protected]("arch", ["gfx942", "gfx90a", "gfx1201", "gfx1030", ""])
+def test_rocm_auto_klein_flash_gfx11_only(monkeypatch, arch):
+ calls = _rocm(monkeypatch)
+ _arch(monkeypatch, arch)
+ assert select_attention_backend(_target(), "auto", speed_active = True, family = _klein()) is None
+ assert calls == []
+
+
+def test_rocm_auto_klein_without_flash_attn_is_silent(monkeypatch, caplog):
+ calls = _rocm(monkeypatch, flash_attn = False)
+ _arch(monkeypatch)
+ logged = []
+ monkeypatch.setattr(
+ att, "_module_logger", lambda: types.SimpleNamespace(warning = lambda *a: logged.append(a))
+ )
+ assert select_attention_backend(_target(), "auto", speed_active = True, family = _klein()) is None
+ assert calls == [] and logged == []
+
+
+def test_rocm_auto_klein_failed_probe_stays_native(monkeypatch):
+ _rocm(monkeypatch, probe = False)
+ _arch(monkeypatch)
+ assert select_attention_backend(_target(), "auto", speed_active = True, family = _klein()) is None
+
+
+def test_rocm_auto_klein_explicit_native_wins(monkeypatch):
+ calls = _rocm(monkeypatch)
+ _arch(monkeypatch)
+ for alias in ("native", "sdpa"):
+ assert (
+ select_attention_backend(_target(), alias, speed_active = True, family = _klein()) is None
+ )
+ assert calls == []
+
+
+def test_nvidia_auto_klein_unchanged(monkeypatch):
+ monkeypatch.setattr(att, "_is_cuda_nvidia", lambda target: True)
+ monkeypatch.setattr(att, "_cudnn_attention_supported", lambda: True)
+ assert (
+ select_attention_backend(_target(), "auto", speed_active = True, family = _klein())
+ == "_native_cudnn"
+ )
+ for unset in (False, True):
+ assert (
+ select_attention_backend(
+ _target(), "auto", speed_active = False, family = _klein(), speed_unset = unset
+ )
+ is None
+ )
+
+
+def test_image_load_passes_the_family():
+ import ast
+ import pathlib
+
+ src = pathlib.Path(att.__file__).with_name("diffusion.py").read_text(encoding = "utf-8")
+ calls = [
+ n
+ for n in ast.walk(ast.parse(src))
+ if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "select_attention_backend"
+ ]
+ with_family = [c for c in calls if any(k.arg == "family" for k in c.keywords)]
+ # the load-time pick and the eager re-pick; the pre-lock preinstall needs no family (no ROCm pip install)
+ assert len(with_family) == 2
+ assert sum(any(k.arg == "speed_unset" for k in c.keywords) for c in with_family) == 1
+
+
+def test_auto_attention_reason_names_the_engaged_kernel():
+ assert att.auto_attention_reason(None) == "diffusers default"
+ assert att.auto_attention_reason("_native_cudnn") == "cuDNN fused attention upgrade"
+ assert "cuDNN" not in att.auto_attention_reason("flash")
+ assert "ROCm flash" in att.auto_attention_reason("flash")
+
+
+def test_status_reason_is_derived_from_the_engaged_backend():
+ src = open(
+ att.__file__.replace("diffusion_attention.py", "diffusion.py"), encoding = "utf-8"
+ ).read()
+ assert src.count("auto_attention_reason(attention_engaged)") == 2
+ assert '"cuDNN fused attention upgrade"' not in src
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index b710d4ad58f..7cad898a5dc 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -1214,7 +1214,9 @@ def test_dense_speed_auto_defers_compile_to_third_generation(fake_runtime, tmp_p
monkeypatch.setattr(
dmod,
"select_attention_backend",
- lambda target, requested, speed_active = False: ("_native_cudnn" if speed_active else None),
+ lambda target, requested, speed_active = False, family = None, speed_unset = False: (
+ "_native_cudnn" if speed_active else None
+ ),
)
monkeypatch.setattr(dmod.compile_cache, "begin", lambda **k: None)
@@ -1404,6 +1406,8 @@ def test_deferred_speed_preserves_explicit_attention(fake_runtime, tmp_path, mon
target,
requested,
speed_active = False,
+ family = None,
+ speed_unset = False,
):
if requested in (None, "", "auto"):
return "_native_cudnn" if speed_active else None