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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio diffusion: auto attention keeps native flash SDPA on A100 / L4 class cards (#17290)
Daniel Hana691227711b2
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.pyindex 3dc1afbe126..aef204ecbd0 100644--- a/studio/backend/core/inference/diffusion_attention.py+++ b/studio/backend/core/inference/diffusion_attention.py@@ -689,6 +689,19 @@ BLACKWELL_NATIVE_ATTN_ENV = ("UNSLOTH_DIFFUSION_BLACKWELL_NATIVE_ATTN" # auto (default) | 0 keeps the cuDNN pin)_NATIVE_DISPATCH_CACHE: dict[tuple[str, str, int], bool] = {}+# Native flash measured faster than the cuDNN pin at every DiT/U-Net shape, bf16+fp16 (torch 2.14.1+cu130); others keep the pin.+FLASH_FASTER_CAPABILITIES: dict[tuple[int, int], str] = {+ (+ 8,+ 0,+ ): "A100: cuDNN 1-44% slower than native flash (FLUX 0.92x, Lumina-2 0.74x, SD3.5 0.97x per call)",+ (+ 8,+ 9,+ ): "L4: cuDNN never faster than native flash (Lumina-2 0.70x per call, the rest 0.93-1.00x)",+}+NATIVE_FLASH_ATTN_ENV = "UNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN" # auto (default) | 0 keeps the cuDNN pin on FLASH_FASTER_CAPABILITIES cards+_NATIVE_FLASH_CACHE: dict[tuple[str, str, int], bool] = {}ROCM_FLASH_ENV = "UNSLOTH_DIFFUSION_ROCM_FLASH" # auto (timed) | 0 (auto never picks flash) | 1 (verified is enough)ROCM_FLASH_MIN_GAIN = 0.03# Accuracy is judged on the raw attention output (flash vs native SDPA, same inputs), not the block: the residual and@@ -3432,6 +3445,41 @@ def _native_dispatches_cudnn(pipe: Any, target: Any) -> bool:return False+def _native_flash_measured_faster(pipe: Any, target: Any) -> bool:+ """True on a ``FLASH_FASTER_CAPABILITIES`` card whose native SDPA picks FLASH for every DiT head dim; else keep the pin."""+ if (os.environ.get(NATIVE_FLASH_ATTN_ENV) or "").strip().lower() in ("0", "off", "false", "no"):+ return False+ if not _is_cuda_nvidia(target):+ return False+ device = str(getattr(target, "torch_device", None) or getattr(target, "device", None) or "")+ if not device.startswith("cuda"):+ return False+ dims = _dit_head_dims(pipe)+ if not dims:+ return False+ try:+ import torch+ from torch.nn.attention import SDPBackend++ device = _indexed_cuda_device(device)+ if tuple(_device_capability(device)) not in FLASH_FASTER_CAPABILITIES:+ return False+ dtype = getattr(target, "dtype", None)+ if dtype not in (torch.bfloat16, torch.float16):+ return False+ for dim in sorted(dims):+ key = (device, str(dtype), int(dim))+ hit = _NATIVE_FLASH_CACHE.get(key)+ if hit is None:+ hit = _native_sdp_choice(device, dtype, dim) == int(SDPBackend.FLASH_ATTENTION)+ _NATIVE_FLASH_CACHE[key] = hit+ if not hit:+ return False+ return True+ except Exception: # noqa: BLE001 - unaskable: keep the pin+ return False++def _cudnn_serves_pipe(pipe: Any,target: Any,@@ -3576,6 +3624,18 @@ def apply_attention_backend(BLACKWELL_NATIVE_ATTN_ENV,)backend = None+ if (+ isinstance(backend, _AutoCudnn)+ and target is not None+ and _native_flash_measured_faster(pipe, target)+ ):+ if logger is not None:+ logger.info(+ "diffusion.attention: auto keeps native SDPA (flash attention measured faster than the cuDNN "+ "pin on this card; %s=0 pins cuDNN)",+ NATIVE_FLASH_ATTN_ENV,+ )+ backend = Noneif backend is not None:backend = str(backend)if backend == "flash_4_hub" and not _install_fa4_dispatch_guard():diff --git a/studio/backend/tests/test_diffusion_attention_native_flash.py b/studio/backend/tests/test_diffusion_attention_native_flash.pynew file mode 100644index 00000000000..daa160c766e--- /dev/null+++ b/studio/backend/tests/test_diffusion_attention_native_flash.py@@ -0,0 +1,145 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Auto attention on cards where native flash measured faster than the cuDNN pin: native SDPA when torch's own+dispatch picks FLASH at every DiT head dim; the pin on every other card, for an explicit request and with the kill+switch."""++from __future__ import annotations++import types++import pytest+import torch++import core.inference.diffusion_attention as att+from core.inference.diffusion_attention import apply_attention_backend, select_attention_backend++CUDNN = int(torch.nn.attention.SDPBackend.CUDNN_ATTENTION)+FLASH = int(torch.nn.attention.SDPBackend.FLASH_ATTENTION)+EFFICIENT = int(torch.nn.attention.SDPBackend.EFFICIENT_ATTENTION)+++class _Dit:+ def __init__(self, head_dim = 128):+ self.config = {"attention_head_dim": head_dim}+ self.set_to = None++ def set_attention_backend(self, name):+ self.set_to = name+++def _target(dtype = torch.bfloat16):+ return types.SimpleNamespace(device = "cuda", dtype = dtype)+++def ampere(monkeypatch):+ """An NVIDIA SM80 card whose native dispatch picks FLASH up to head_dim 256 (torch 2.14 / A100)."""+ att._NATIVE_DISPATCH_CACHE.clear()+ att._NATIVE_FLASH_CACHE.clear()+ monkeypatch.delenv(att.NATIVE_FLASH_ATTN_ENV, raising = False)+ monkeypatch.delenv(att.BLACKWELL_NATIVE_ATTN_ENV, raising = False)+ monkeypatch.setenv(att.CUDNN_HEAD_DIM_PROBE_ENV, "0")+ monkeypatch.setattr(att, "_is_cuda_nvidia", lambda target: True)+ monkeypatch.setattr(att, "_cuda_capability", lambda: (8, 0))+ monkeypatch.setattr(att, "_indexed_cuda_device", lambda device: "cuda:0")+ monkeypatch.setattr(att, "guard_rocm_fused_sdpa", lambda target, logger = None: None)+ state = {"cap": (8, 0), "asked": []}+ monkeypatch.setattr(att, "_device_capability", lambda device: state["cap"])++ def choice(device, dtype, dim):+ state["asked"].append((dtype, dim))+ return FLASH if dim <= 256 else EFFICIENT++ monkeypatch.setattr(att, "_native_sdp_choice", choice)+ yield state+ att._NATIVE_DISPATCH_CACHE.clear()+ att._NATIVE_FLASH_CACHE.clear()+++def test_the_measured_table_holds_only_pre_blackwell_cards():+ assert att.FLASH_FASTER_CAPABILITIES+ assert all(cap < (10, 0) for cap in att.FLASH_FASTER_CAPABILITIES)+ assert (9, 0) not in att.FLASH_FASTER_CAPABILITIES # Hopper unmeasured: keeps the pin++[email protected]("dtype", [torch.bfloat16, torch.float16])[email protected]("head_dim", [64, 96, 128])+def test_auto_leaves_native_flash_on_a_measured_card(ampere, dtype, head_dim):+ dit = _Dit(head_dim)+ target = _target(dtype)+ pick = select_attention_backend(target, "auto", speed_active = True)+ assert pick == "_native_cudnn" and isinstance(pick, att._AutoCudnn)+ assert (+ apply_attention_backend(types.SimpleNamespace(transformer = dit), pick, target = target) is None+ )+ assert dit.set_to in (None, "native")+ assert ampere["asked"] == [(dtype, head_dim)]+++def test_an_explicit_cudnn_request_is_still_pinned(ampere):+ dit = _Dit(128)+ engaged = apply_attention_backend(+ types.SimpleNamespace(transformer = dit), "_native_cudnn", target = _target()+ )+ assert engaged == "_native_cudnn" and dit.set_to == "_native_cudnn"+ assert ampere["asked"] == []+++ "case",+ [+ "unmeasured_card",+ "hopper",+ "not_flash",+ "fp32",+ "kill_switch",+ "unknown_head_dim",+ "no_target",+ ],+)+def test_auto_keeps_the_cudnn_pin_wherever_flash_is_unproven(ampere, monkeypatch, case):+ dit = _Dit(512 if case == "not_flash" else 128)+ target = _target(torch.float32 if case == "fp32" else torch.bfloat16)+ if case == "unmeasured_card":+ ampere["cap"] = (8, 6)+ if case == "hopper":+ ampere["cap"] = (9, 0)+ if case == "kill_switch":+ monkeypatch.setenv(att.NATIVE_FLASH_ATTN_ENV, "0")+ if case == "unknown_head_dim":+ dit.config = {}+ pick = select_attention_backend(target, "auto", speed_active = True)+ engaged = apply_attention_backend(+ types.SimpleNamespace(transformer = dit), pick, target = None if case == "no_target" else target+ )+ assert engaged == "_native_cudnn" and dit.set_to == "_native_cudnn"+ assert type(engaged) is str+++def test_mixed_head_dims_need_flash_at_every_one(ampere):+ pipe = types.SimpleNamespace(transformer = _Dit(128), transformer_2 = _Dit(512))+ assert att._native_flash_measured_faster(pipe, _target()) is False+ ampere["asked"].clear()+ att._NATIVE_FLASH_CACHE.clear()+ one = types.SimpleNamespace(transformer = _Dit(64))+ assert att._native_flash_measured_faster(one, _target()) is True+ assert att._native_flash_measured_faster(one, _target()) is True+ assert ampere["asked"] == [(torch.bfloat16, 64)] # cached per (device, dtype, head_dim)+++def test_an_unaskable_probe_keeps_the_pin(ampere, monkeypatch):+ def boom(device, dtype, dim):+ raise RuntimeError("no device")++ monkeypatch.setattr(att, "_native_sdp_choice", boom)+ assert (+ att._native_flash_measured_faster(types.SimpleNamespace(transformer = _Dit(128)), _target())+ is False+ )+++def test_speed_off_never_reaches_the_check(ampere):+ assert select_attention_backend(_target(), "auto", speed_active = False) is None+ assert ampere["asked"] == []