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.

Pick the attention backend per device on mixed-generation multi-GPU hosts (#13698)

Daniel Han77245f1c1b70
diff --git a/tests/utils/test_attention_dispatch_mixed_devices.py b/tests/utils/test_attention_dispatch_mixed_devices.py
new file mode 100644
index 00000000000..44c2213bf2f
--- /dev/null
+++ b/tests/utils/test_attention_dispatch_mixed_devices.py
@@ -0,0 +1,335 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Mixed-generation multi-GPU hosts: the attention backend follows the device Q lives on, not
+device 0, and homogeneous hosts never consult the per-device table."""
+
+from types import SimpleNamespace
+
+import pytest
+import torch
+import unsloth # noqa: F401
+
+from unsloth.models import _utils as mu
+from unsloth.utils import attention_dispatch as ad
+
+AMPERE, TURING, PASCAL, HOPPER, B200, RTX50 = (8, 6), (7, 5), (6, 1), (9, 0), (10, 0), (12, 0)
+
+
+def _cuda(index):
+ return SimpleNamespace(type = "cuda", index = index)
+
+
+def _table(
+ monkeypatch,
+ capabilities,
+ flash = True,
+ xformers = True,
+ probe = lambda *a, **k: True,
+):
+ monkeypatch.setattr(ad, "HAS_FLASH_ATTENTION", flash)
+ monkeypatch.setattr(ad, "HAS_XFORMERS", xformers)
+ monkeypatch.setattr(ad, "_xformers_runs_on_device", probe)
+ monkeypatch.setattr(ad, "_XFORMERS_PROBED", {})
+ return ad._per_device_backends(capabilities)
+
+
+ "capabilities",
+ [(), (AMPERE,), (AMPERE, AMPERE), (TURING, TURING), (B200,) * 8, (AMPERE, HOPPER)],
+)
+def test_homogeneous_hosts_skip_the_table(monkeypatch, capabilities):
+ assert _table(monkeypatch, capabilities) is None
+
+
+def test_flash_is_kept_on_ampere_and_dropped_on_turing(monkeypatch):
+ table = _table(monkeypatch, (AMPERE, TURING))
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ for backend in (ad.FLASH_DENSE, ad.FLASH_VARLEN):
+ assert ad._backend_for_device(backend, _cuda(0)) == backend
+ assert ad._backend_for_device(backend, _cuda(1)) == ad.SDPA
+
+
+def test_turing_at_device_0_keeps_flash_off_and_sdpa_untouched(monkeypatch):
+ # HAS_FLASH_ATTENTION is device-0 based, so a Turing device 0 leaves flash off everywhere.
+ table = _table(monkeypatch, (TURING, AMPERE), flash = False)
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(0), torch.float16) == ad.XFORMERS
+ assert ad._backend_for_device(ad.SDPA, _cuda(1)) == ad.SDPA
+
+
+def test_xformers_bf16_on_pre_ampere_goes_to_sdpa(monkeypatch):
+ table = _table(monkeypatch, (AMPERE, PASCAL), flash = False)
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(0), torch.bfloat16) == ad.XFORMERS
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(1), torch.float16) == ad.XFORMERS
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(1), torch.bfloat16) == ad.SDPA
+
+
+def test_rtx50_beyond_device_0_is_probed_only_without_flash(monkeypatch):
+ probed = []
+
+ def probe(device, supports_bf16 = None):
+ probed.append(device)
+ return False
+
+ table = _table(monkeypatch, (AMPERE, RTX50), flash = False, probe = probe)
+ assert probed == [] # lazy: import never touches another rank's card
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(0), torch.bfloat16) == ad.XFORMERS
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(1), torch.bfloat16) == ad.SDPA
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(1), torch.bfloat16) == ad.SDPA
+ assert probed == ["cuda:1"] # probed once, on first dispatch there
+
+ probed.clear()
+ _table(monkeypatch, (AMPERE, RTX50), flash = True, probe = probe)
+ assert probed == []
+
+
+def test_fp32_downcast_follows_the_device(monkeypatch):
+ table = _table(monkeypatch, (AMPERE, B200), flash = False)
+ assert [row[2] for row in table] == [False, True]
+
+
+def test_non_cuda_and_out_of_range_devices_are_left_alone(monkeypatch):
+ table = _table(monkeypatch, (AMPERE, TURING))
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ assert ad._backend_for_device(ad.FLASH_DENSE, SimpleNamespace(type = "cpu", index = None)) == (
+ ad.FLASH_DENSE
+ )
+ assert ad._backend_for_device(ad.FLASH_DENSE, _cuda(5)) == ad.FLASH_DENSE
+
+
+def _run(
+ monkeypatch,
+ table,
+ config_kwargs = None,
+):
+ calls = []
+
+ def fake_flash(Q, K, V, **kwargs):
+ calls.append("flash")
+ return torch.zeros_like(Q)
+
+ real_sdpa = ad.scaled_dot_product_attention
+
+ def fake_sdpa(*args, **kwargs):
+ calls.append("sdpa")
+ return real_sdpa(*args, **kwargs)
+
+ monkeypatch.setattr(ad, "flash_attn_func", fake_flash, raising = False)
+ monkeypatch.setattr(ad, "scaled_dot_product_attention", fake_sdpa)
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ Q = torch.randn(1, 2, 4, 8, dtype = torch.float16, device = "cuda:0")
+ config = ad.AttentionConfig(
+ backend = ad.FLASH_DENSE,
+ n_kv_heads = 2,
+ n_groups = 1,
+ flash_dense_kwargs = {"causal": True, **(config_kwargs or {})},
+ )
+ context = ad.AttentionContext(
+ bsz = 1,
+ q_len = 4,
+ kv_seq_len = 4,
+ n_heads = 2,
+ head_dim = 8,
+ requires_grad = False,
+ seq_info = None,
+ attention_mask = None,
+ causal_mask = None,
+ )
+ ad.run_attention(config = config, context = context, Q = Q, K = Q, V = Q)
+ return calls
+
+
+requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs a CUDA tensor")
+
+
+@requires_cuda
+def test_run_attention_reroutes_only_the_incapable_device(monkeypatch):
+ capable = ((True, True, False, True), (False, True, False, False))
+ assert _run(monkeypatch, capable) == ["flash"]
+ incapable = ((False, True, False, False), (True, True, False, True))
+ assert _run(monkeypatch, incapable) == ["sdpa"]
+ assert _run(monkeypatch, None) == ["flash"]
+
+
+@requires_cuda
+def test_run_attention_refuses_to_drop_a_softcap(monkeypatch):
+ incapable = ((False, True, False, False), (True, True, False, True))
+ with pytest.raises(RuntimeError, match = "softcaps"):
+ _run(monkeypatch, incapable, {"softcap": 50.0})
+
+
+class _Model(torch.nn.Module):
+ _supports_sdpa = True
+
+ def __init__(
+ self,
+ device_map,
+ impl = "flash_attention_2",
+ model_type = "llama",
+ ):
+ super().__init__()
+ self.config = SimpleNamespace(_attn_implementation = impl, model_type = model_type)
+ self.hf_device_map = device_map
+
+
+def _capability(monkeypatch, capabilities):
+ monkeypatch.setattr(mu, "HAS_FLASH_ATTENTION", True)
+ monkeypatch.setattr(mu, "DEVICE_TYPE", "cuda")
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda i = None: capabilities[i or 0])
+
+
+ "device_map, expected",
+ [
+ ({"": 0}, "flash_attention_2"),
+ ({"model.layers.0": 0, "model.layers.1": "cuda:2"}, "flash_attention_2"),
+ ({"model.layers.0": 0, "model.layers.1": 1}, "sdpa"),
+ ({"model.layers.0": "cuda:0", "model.layers.1": "cuda:1"}, "sdpa"),
+ ({"model.layers.0": 0, "lm_head": "cpu", "model.norm": "disk"}, "flash_attention_2"),
+ (None, "flash_attention_2"),
+ ],
+)
+def test_hf_flash_falls_back_only_when_layers_reach_pre_ampere(monkeypatch, device_map, expected):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING, 2: HOPPER})
+ model = _Model(device_map)
+ mu.fall_back_from_flash_attention_on_pre_ampere(model)
+ assert model.config._attn_implementation == expected
+
+
+def test_hf_non_flash_models_are_untouched(monkeypatch):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"a": 0, "b": 1}, impl = "eager")
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is False
+ assert model.config._attn_implementation == "eager"
+
+
+class _SelfAttention(torch.nn.Module):
+ pass
+
+
+class _Decoder(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.self_attn = _SelfAttention()
+
+
+def test_hf_flash_stays_when_only_non_attention_modules_reach_pre_ampere(monkeypatch):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"layers.0": 0, "lm_head": 1, "embed": "cuda:1"})
+ model.layers = torch.nn.ModuleList([_Decoder()])
+ model.lm_head = torch.nn.Linear(2, 2)
+ model.embed = torch.nn.Embedding(2, 2)
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is False
+ assert model.config._attn_implementation == "flash_attention_2"
+ model.hf_device_map = {"layers.0": 1, "lm_head": 0}
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "sdpa"
+
+
+def test_hf_fallback_keeps_known_broken_sdpa_models_on_eager(monkeypatch):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"a": 0, "b": 1}, model_type = "gpt_oss")
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "eager"
+
+
+def test_hf_fine_grained_projection_placements_count_as_attention(monkeypatch):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"layers.0.self_attn.q_proj": 1, "layers.0": 0})
+ model.layers = torch.nn.ModuleList([_Decoder()])
+ model.layers[0].self_attn.q_proj = torch.nn.Linear(2, 2)
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "sdpa"
+
+
+def test_hf_fallback_keeps_softcapped_models_on_eager(monkeypatch):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"a": 0, "b": 1}, model_type = "gemma2")
+ model.config.attn_logit_softcapping = 50.0
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "eager"
+
+
+def test_same_class_secondary_cards_are_never_probed(monkeypatch):
+ calls = []
+
+ def probe(device, supports_bf16 = None):
+ calls.append(device)
+ return True
+
+ assert _table(monkeypatch, ((12, 0), (12, 0), (12, 0)), flash = False, probe = probe) is None
+ assert calls == []
+
+
+def test_no_probe_inside_a_traced_region(monkeypatch):
+ calls = []
+ table = _table(monkeypatch, (AMPERE, RTX50), flash = False, probe = lambda *a, **k: calls.append(1))
+ monkeypatch.setattr(ad, "_DEVICE_BACKENDS", table)
+ monkeypatch.setattr(torch.compiler, "is_compiling", lambda: True)
+ assert ad._backend_for_device(ad.XFORMERS, _cuda(1), torch.float16) == ad.SDPA
+ assert calls == []
+
+
+def test_hf_fallback_reads_child_configs_before_rewriting_the_composite(monkeypatch):
+ # T5Gemma shape: only the encoder config softcaps, and a composite write would recurse into it.
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"a": 0, "b": 1}, model_type = "t5gemma")
+ encoder = SimpleNamespace(
+ _attn_implementation = "flash_attention_2",
+ model_type = "t5gemma_module",
+ attn_logit_softcapping = 50.0,
+ )
+ model.config.sub_configs = {"encoder": None}
+ model.config.encoder = encoder
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "eager"
+ assert encoder._attn_implementation == "eager"
+
+
[email protected]("current, expected", [(0, "flash_attention_2"), (1, "sdpa")])
+def test_bare_cuda_placement_reads_the_current_device(monkeypatch, current, expected):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: current)
+ model = _Model({"": "cuda"})
+ model.layers = torch.nn.ModuleList([_Decoder()])
+ mu.fall_back_from_flash_attention_on_pre_ampere(model)
+ assert model.config._attn_implementation == expected
+
+
+def test_hierarchical_maps_follow_the_most_specific_entry(monkeypatch):
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"": 1, "layers": 0})
+ model.layers = torch.nn.ModuleList([_Decoder()])
+ model.lm_head = torch.nn.Linear(2, 2)
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is False
+ assert model.config._attn_implementation == "flash_attention_2"
+ model.hf_device_map = {"": 1, "lm_head": 0}
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "sdpa"
+
+
+def test_hf_fallback_keeps_an_eager_only_tower_on_eager(monkeypatch):
+ # Donut shape: the root runs flash, its DonutSwin encoder was put on eager (no SDPA).
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"a": 0, "b": 1}, model_type = "vision-encoder-decoder")
+ encoder = SimpleNamespace(_attn_implementation = "eager", model_type = "donut-swin")
+ model.config.sub_configs = {"encoder": None}
+ model.config.encoder = encoder
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "eager"
+ assert encoder._attn_implementation == "eager"
+
+
+def test_hf_fallback_reads_sdpa_support_of_every_tower(monkeypatch):
+ from transformers import PretrainedConfig, PreTrainedModel
+
+ class _Tower(PreTrainedModel):
+ config_class = PretrainedConfig
+ _supports_sdpa = False
+
+ _capability(monkeypatch, {0: AMPERE, 1: TURING})
+ model = _Model({"a": 0, "b": 1})
+ model.tower = _Tower(PretrainedConfig())
+ assert mu.fall_back_from_flash_attention_on_pre_ampere(model) is True
+ assert model.config._attn_implementation == "eager"
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 2029a5e0f78..fad3738e871 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -71,6 +71,7 @@ __all__ = [
"unsloth_compile_transformers",
"resolve_model_class",
"resolve_attention_implementation",
+ "fall_back_from_flash_attention_on_pre_ampere",
"resolve_encoder_attention_implementation",
"_set_attn_impl",
"set_task_config_attr",
@@ -1614,6 +1615,127 @@ def _set_attn_impl(config, impl):
return impl
+def _cuda_index(placement):
+ """CUDA index of a device-map placement, or None for cpu / disk offload."""
+ if isinstance(placement, int):
+ return placement
+ try:
+ device = torch.device(placement)
+ except (RuntimeError, TypeError):
+ return None
+ if device.type != "cuda":
+ return None
+ # A bare "cuda" means the current device, which a framework may have moved off device 0.
+ return torch.cuda.current_device() if device.index is None else device.index
+
+
+def _attention_placements(model, device_map):
+ """Device-map keys that run attention: each attention module's longest-prefix entry, plus entries inside
+ one (a fine-grained map can place q_proj alone). An unresolvable key counts."""
+ keys = sorted((k for k in device_map if isinstance(k, str)), key = len, reverse = True)
+ out = set()
+ for key in keys:
+ try:
+ model.get_submodule(key)
+ except Exception:
+ out.add(key)
+ for name, module in model.named_modules():
+ if not name or "attention" not in type(module).__name__.lower():
+ continue
+ owner = next((k for k in keys if k == "" or name == k or name.startswith(k + ".")), None)
+ if owner is not None:
+ out.add(owner)
+ out.update(k for k in keys if k.startswith(name + "."))
+ return out
+
+
+def _pre_ampere_cuda_devices(model):
+ """CUDA indices that Flash Attention 2 cannot run on (sm < 80) and that the loaded `hf_device_map`
+ puts attention layers on. An `lm_head` or embedding alone there never calls flash."""
+ device_map = getattr(model, "hf_device_map", None)
+ if DEVICE_TYPE != "cuda" or not isinstance(device_map, dict):
+ return []
+ try:
+ indices = {k: _cuda_index(v) for k, v in device_map.items()}
+ pre_ampere = {
+ i
+ for i in set(indices.values())
+ if i is not None and torch.cuda.get_device_capability(i)[0] < 8
+ }
+ except Exception:
+ return []
+ if not pre_ampere:
+ return [] # same-generation hosts never walk the modules
+ attention = _attention_placements(model, device_map)
+ return sorted({indices[k] for k in attention if indices.get(k) in pre_ampere})
+
+
+def fall_back_from_flash_attention_on_pre_ampere(model):
+ """Device 0 chose Flash Attention 2; switch to SDPA (or eager) when the device map also put attention
+ layers on a pre-Ampere card, where every flash call would raise. Same-generation hosts never change."""
+ if not HAS_FLASH_ATTENTION:
+ return False
+ pre_ampere = _pre_ampere_cuda_devices(model)
+ if not pre_ampere:
+ return False
+ model_class = type(model)
+ # Same SDPA eligibility as resolve_attention_implementation: a known-wrong SDPA stays on eager.
+ class_sdpa = getattr(model_class, "_supports_sdpa", False) and not _declares_no_sdpa(
+ model_class
+ )
+ configs, seen = [], set()
+
+ def _collect(config):
+ if config is None or id(config) in seen:
+ return
+ seen.add(id(config))
+ configs.append(config)
+ for key in getattr(config, "sub_configs", None) or ():
+ _collect(getattr(config, key, None))
+
+ for module in model.modules():
+ _collect(getattr(module, "config", None))
+ flash = [
+ config
+ for config in configs
+ if str(_config_get(config, "_attn_implementation", None) or "").startswith(
+ "flash_attention"
+ )
+ ]
+ if not flash:
+ return False
+
+ def _sdpa_ok(config):
+ model_type = (_config_get(config, "model_type", "") or "").lower()
+ # SDPA cannot apply an attention-logit softcap (Gemma 2), so those stay exact on eager.
+ softcap = _config_get(config, "attn_logit_softcapping", None)
+ # A tower already on eager (no SDPA, e.g. DonutSwin) must keep it.
+ eager = _config_get(config, "_attn_implementation", None) == "eager"
+ return not _is_sdpa_excluded(model_type) and not softcap and not eager
+
+ try:
+ from transformers.modeling_utils import PreTrainedModel
+ except Exception:
+ PreTrainedModel = ()
+ towers_sdpa = all(
+ getattr(type(m), "_supports_sdpa", False) and not _declares_no_sdpa(type(m))
+ for m in model.modules()
+ if isinstance(m, PreTrainedModel)
+ )
+ # One answer for the whole tree, decided before any write: a composite's setter recurses into
+ # its children, so a parent rewritten to sdpa would carry a softcapped child with it.
+ ok = class_sdpa and towers_sdpa and all(_sdpa_ok(c) for c in configs)
+ changed = "sdpa" if ok else "eager"
+ for config in flash:
+ _write_attn_impl(config, changed)
+ if changed:
+ print(
+ f"Unsloth: Layers were placed on cuda:{pre_ampere[0]}, which cannot run Flash Attention 2 "
+ f"(compute capability below 8.0), so the model uses {changed} attention instead."
+ )
+ return bool(changed)
+
+
_REMOTE_CODE_HUB_KWARGS = (
"revision",
"code_revision",
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 901e2c53be7..43163a3d95b 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -3799,6 +3799,8 @@ class FastBaseModel:
finally:
# The load deep-copied the config; give the caller's object its fp8 block back.
disarm_fp8_to_nf4(model_config)
+ # Before extracting the text core, which does not carry hf_device_map over.
+ fall_back_from_flash_attention_on_pre_ampere(model)
model = _text_trainable_core(
model, text_intent = bool(text_only) if text_intent is None else bool(text_intent)
)
diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.py
index 9af708bbc7f..e5195ed2669 100644
--- a/unsloth/utils/attention_dispatch.py
+++ b/unsloth/utils/attention_dispatch.py
@@ -23,6 +23,7 @@ import torch
from torch import Tensor
from torch.nn.functional import scaled_dot_product_attention
+from ..device_type import DEVICE_TYPE
from ..models._utils import *
from ..utils.packing import (
build_sdpa_packed_attention_mask,
@@ -40,17 +41,19 @@ if HAS_FLASH_ATTENTION:
HAS_XFORMERS = xformers is not None
-def _xformers_runs_on_device() -> bool:
+def _xformers_runs_on_device(device = "cuda", supports_bf16 = None) -> bool:
"""One tiny attention forward; True iff the xformers kernel actually runs here."""
try:
# Pre-Ampere GPUs (sm < 80: Turing/Volta) have no bfloat16 attention kernel but run xformers fine in
# float16, so pick the dtype the device supports.
- dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16
- q = torch.zeros((1, 8, 1, 64), device = "cuda", dtype = dtype)
+ if supports_bf16 is None:
+ supports_bf16 = SUPPORTS_BFLOAT16
+ dtype = torch.bfloat16 if supports_bf16 else torch.float16
+ q = torch.zeros((1, 8, 1, 64), device = device, dtype = dtype)
attn_bias = xformers.attn_bias.BlockDiagonalCausalMask.from_seqlens([8])
xformers_attention(q, q, q, attn_bias = attn_bias)
# Launches are async, so synchronize or a deferred kernel failure escapes this probe.
- torch.cuda.synchronize()
+ torch.cuda.synchronize(device)
return True
except Exception:
return False
@@ -86,6 +89,75 @@ if HAS_XFORMERS and not HAS_FLASH_ATTENTION and torch.cuda.is_available():
_XFORMERS_FP32_UNSUPPORTED = (
torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 10
)
+
+
+def _per_device_backends(capabilities):
+ """(flash runs, xformers runs, xformers rejects fp32, bf16 kernels) per CUDA device index, or None
+ when every device has device 0's capability class, so homogeneous hosts never consult the table.
+ xformers runs is None where it needs a probe on that card, taken on first dispatch there."""
+ if len({(c[0] >= 8, c[0] >= 10, c[0] >= 12) for c in capabilities}) < 2:
+ return None
+ table = []
+ for index, capability in enumerate(capabilities):
+ flash = HAS_FLASH_ATTENTION and capability[0] >= 8
+ xformers_ok = HAS_XFORMERS
+ # Device 0 was probed above; xformers only serves another sm_120 card when flash cannot.
+ if xformers_ok and index > 0 and not flash and capability[0] >= 12:
+ xformers_ok = None
+ table.append((flash, xformers_ok, capability[0] >= 10, capability[0] >= 8))
+ if all(row == table[0] for row in table):
+ return None
+ return tuple(table)
+
+
+def _visible_capabilities():
+ if DEVICE_TYPE != "cuda" or not torch.cuda.is_available():
+ return ()
+ try:
+ return tuple(torch.cuda.get_device_capability(i) for i in range(torch.cuda.device_count()))
+ except Exception:
+ return ()
+
+
+# Mixed-generation hosts only (e.g. sm_86 + sm_75): the backend is re-checked against Q's device, since a
+# device-0 verdict is wrong for layers a device_map places on another card.
+_DEVICE_BACKENDS = _per_device_backends(_visible_capabilities())
+
+
+# Lazy so import never opens a CUDA context on another rank's card (torchrun sees every GPU).
+_XFORMERS_PROBED: dict = {}
+
+
+def _xformers_runs_on(index: int) -> bool:
+ if index not in _XFORMERS_PROBED:
+ if torch.compiler.is_compiling():
+ return False # never probe inside a traced region; SDPA is always valid
+ _XFORMERS_PROBED[index] = _xformers_runs_on_device(f"cuda:{index}", supports_bf16 = True)
+ return _XFORMERS_PROBED[index]
+
+
+def _backend_for_device(
+ backend: str,
+ device,
+ dtype = None,
+) -> str:
+ index = getattr(device, "index", None)
+ if getattr(device, "type", None) != "cuda" or index is None or index >= len(_DEVICE_BACKENDS):
+ return backend
+ flash, xformers_ok, _, bf16 = _DEVICE_BACKENDS[index]
+ if backend in (FLASH_DENSE, FLASH_VARLEN) and not flash:
+ return SDPA
+ # A bfloat16 model (chosen from device 0) has no xformers kernel on a pre-Ampere card.
+ if backend == XFORMERS:
+ if dtype == torch.bfloat16 and not bf16:
+ return SDPA
+ if xformers_ok is None:
+ xformers_ok = _xformers_runs_on(index)
+ if not xformers_ok:
+ return SDPA
+ return backend
+
+
SDPA_HAS_GQA = "enable_gqa" in (scaled_dot_product_attention.__doc__ or "")
# Packed SDPA runs per segment: a dense (T, T) mask + enable_gqa leaves only the math kernel.
@@ -551,6 +623,19 @@ def run_attention(
backend = config.backend
if backend == FLASH_VARLEN and context.seq_info is None:
backend = FLASH_DENSE if HAS_FLASH_ATTENTION else SDPA
+ xformers_fp32_unsupported = _XFORMERS_FP32_UNSUPPORTED
+ if _DEVICE_BACKENDS is not None and backend != SDPA:
+ device_backend = _backend_for_device(backend, Q.device, Q.dtype)
+ if device_backend != backend and _configured_softcap(config):
+ raise RuntimeError(
+ f"Unsloth: This model softcaps attention logits, which needs Flash Attention, but "
+ f"{Q.device} cannot run it (compute capability below 8.0). Place the model on "
+ "Ampere or newer GPUs, e.g. with CUDA_VISIBLE_DEVICES."
+ )
+ backend = device_backend
+ index = Q.device.index
+ if Q.device.type == "cuda" and index is not None and index < len(_DEVICE_BACKENDS):
+ xformers_fp32_unsupported = _DEVICE_BACKENDS[index][2]
# Flash/xFormers do not support arbitrary attn masks, so with a padding mask present (left-padded
# generation) fall back to SDPA.
@@ -637,7 +722,7 @@ def run_attention(
# flash-2 op on sm_100+), so downcast any fp32 Q/K/V to a supported dtype (#1013).
if (
backend in (FLASH_DENSE, FLASH_VARLEN)
- or (backend == XFORMERS and _XFORMERS_FP32_UNSUPPORTED)
+ or (backend == XFORMERS and xformers_fp32_unsupported)
) and torch.float32 in (
Q.dtype,
K.dtype,