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.

Lean varlen: ask torch 2.15's backend selector instead of the removed _can_use_cudnn (#16288)

Daniel Hanf3d5b72d464e
diff --git a/tests/test_lean_flash_varlen.py b/tests/test_lean_flash_varlen.py
index 9ffdc48f7c5..6eb7a327ea9 100644
--- a/tests/test_lean_flash_varlen.py
+++ b/tests/test_lean_flash_varlen.py
@@ -78,7 +78,7 @@ def test_dispatch_uses_lean_in_eager_and_torch_when_compiling(monkeypatch):
q = torch.randn(64, 4, 64, device = "cuda", dtype = torch.float16)
cu = torch.tensor([0, 30, 64], dtype = torch.int32, device = "cuda")
ad._varlen_attn_call(q, q, q, cu, 34, scale = None, window_size = (-1, 0), enable_gqa = False)
- expect = 0 if ad._varlen_can_use_cudnn(q, q, q, 34, [-1, 0], False) else 1
+ expect = 0 if ad._varlen_can_use_cudnn(q, q, q, cu, 34, [-1, 0], False) else 1
assert len(calls) == expect
monkeypatch.setattr(torch.compiler, "is_compiling", lambda: True)
ad._varlen_attn_call(q, q, q, cu, 34, scale = None, window_size = (-1, 0), enable_gqa = False)
diff --git a/tests/test_lean_varlen_backend_check.py b/tests/test_lean_varlen_backend_check.py
new file mode 100644
index 00000000000..3d6c239802a
--- /dev/null
+++ b/tests/test_lean_varlen_backend_check.py
@@ -0,0 +1,120 @@
+# Unsloth Zoo - Utilities for Unsloth
+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+"""The lean varlen path runs only where torch's varlen_attn would run flash, for each torch varlen API."""
+
+import importlib
+import sys
+import types
+
+import pytest
+import torch
+
+ad = pytest.importorskip("unsloth.utils.attention_dispatch")
+
+CUDNN = torch.nn.attention.SDPBackend.CUDNN_ATTENTION.value
+FLASH = torch.nn.attention.SDPBackend.FLASH_ATTENTION.value
+Q = types.SimpleNamespace(is_cuda = True, device = types.SimpleNamespace(index = 0))
+
+
+def _varlen_attn(
+ query,
+ key,
+ value,
+ cu_seq_q,
+ cu_seq_k,
+ max_q,
+ max_k,
+ *,
+ scale = None,
+ window_size = None,
+ enable_gqa = False,
+):
+ raise AssertionError("not called")
+
+
+def reload_with(monkeypatch):
+ real = sys.modules.get("torch.nn.attention.varlen")
+
+ def load(**attrs):
+ fake = types.ModuleType("torch.nn.attention.varlen")
+ fake.varlen_attn = _varlen_attn
+ fake._should_use_cudnn = lambda device_index: True
+ for k, v in attrs.items():
+ setattr(fake, k, v)
+ monkeypatch.setitem(sys.modules, "torch.nn.attention.varlen", fake)
+ monkeypatch.setattr(torch.backends.cuda, "is_flash_attention_available", lambda: True)
+ monkeypatch.setenv("UNSLOTH_LEAN_VARLEN", "1")
+ monkeypatch.setenv("UNSLOTH_TORCH_VARLEN", "1")
+ return importlib.reload(ad)
+
+ yield load
+ monkeypatch.undo()
+ if real is not None:
+ sys.modules["torch.nn.attention.varlen"] = real
+ importlib.reload(ad)
+
+
+def test_torch_215_lean_where_torch_selects_flash(reload_with):
+ seen = []
+
+ def select(query, key, value, cu_seq_q, cu_seq_k, max_q, window_size, *rest):
+ seen.append((cu_seq_q, cu_seq_k, max_q, window_size))
+ return FLASH
+
+ m = reload_with(_select_backend = select, _CUDNN_ATTENTION_BACKEND = CUDNN)
+ assert m._LEAN_VARLEN
+ cu = object()
+ assert m._varlen_can_use_cudnn(Q, Q, Q, cu, 512, [-1, 0], False) is False
+ assert seen == [(cu, cu, 512, [-1, 0])]
+
+
+def test_torch_215_no_lean_where_torch_selects_cudnn(reload_with):
+ m = reload_with(_select_backend = lambda *a: CUDNN, _CUDNN_ATTENTION_BACKEND = CUDNN)
+ assert m._varlen_can_use_cudnn(Q, Q, Q, object(), 512, [-1, 0], False) is True
+
+
+def test_torch_215_no_lean_when_no_backend_is_viable(reload_with):
+ def select(*a):
+ raise RuntimeError("No viable backend for varlen_attn")
+
+ m = reload_with(_select_backend = select, _CUDNN_ATTENTION_BACKEND = CUDNN)
+ assert m._varlen_can_use_cudnn(Q, Q, Q, object(), 512, [-1, 0], False) is True
+
+
+def test_torch_214_keeps_can_use_cudnn(reload_with):
+ seen = []
+
+ def can_use(
+ query,
+ key,
+ value,
+ max_q,
+ window_size,
+ enable_gqa = False,
+ ):
+ seen.append((max_q, window_size, enable_gqa))
+ return False
+
+ m = reload_with(_can_use_cudnn = can_use)
+ assert m._varlen_can_use_cudnn(Q, Q, Q, object(), 100, [-1, 0], True) is False
+ assert seen == [(100, [-1, 0], True)]
+
+
+def test_torch_213_falls_back_to_the_device_check(reload_with):
+ m = reload_with()
+ assert m._varlen_can_use_cudnn(Q, Q, Q, object(), 100, [-1, 0], False) is True
diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.py
index ba35399f6b7..a3d0b1c6ba5 100644
--- a/unsloth/utils/attention_dispatch.py
+++ b/unsloth/utils/attention_dispatch.py
@@ -518,23 +518,62 @@ _LEAN_VARLEN = _TORCH_VARLEN_ATTN is not None and os.environ.get(
).lower() not in ("0", "false", "no", "off")
if _LEAN_VARLEN:
try:
- from torch.nn.attention.varlen import _can_use_cudnn as _varlen_can_use_cudnn
+ # torch 2.15 removed _can_use_cudnn: varlen_attn takes the first eligible backend in SDPA
+ # priority order, and the per-device _should_use_cudnn below would rule lean out on every H100 / B200.
+ from torch.nn.attention.varlen import (
+ _CUDNN_ATTENTION_BACKEND as _VARLEN_CUDNN,
+ _select_backend as _varlen_select_backend,
+ )
+ def _varlen_can_use_cudnn(
+ query,
+ key,
+ value,
+ cu_seqlens,
+ max_q,
+ window_size,
+ enable_gqa = False,
+ ):
+ try:
+ backend = _varlen_select_backend(
+ query, key, value, cu_seqlens, cu_seqlens, max_q, window_size
+ )
+ except RuntimeError:
+ return True # no flash either: varlen_attn raises its own error
+ return backend == _VARLEN_CUDNN
+
except Exception:
- # torch 2.12 / 2.13 decide per device only (_should_use_cudnn, False on every GPU in 2.13).
try:
- from torch.nn.attention.varlen import _should_use_cudnn as _varlen_should_use_cudnn
+ from torch.nn.attention.varlen import _can_use_cudnn as _torch_varlen_can_use_cudnn
def _varlen_can_use_cudnn(
query,
key,
value,
+ cu_seqlens,
max_q,
window_size,
enable_gqa = False,
):
- return query.is_cuda and _varlen_should_use_cudnn(query.device.index)
+ return _torch_varlen_can_use_cudnn(
+ query, key, value, max_q, window_size, enable_gqa
+ )
except Exception:
- _LEAN_VARLEN = False
+ # torch 2.12 / 2.13 decide per device only (_should_use_cudnn, False on every GPU in 2.13).
+ try:
+ from torch.nn.attention.varlen import _should_use_cudnn as _varlen_should_use_cudnn
+ def _varlen_can_use_cudnn(
+ query,
+ key,
+ value,
+ cu_seqlens,
+ max_q,
+ window_size,
+ enable_gqa = False,
+ ):
+ return query.is_cuda and _varlen_should_use_cudnn(query.device.index)
+
+ except Exception:
+ _LEAN_VARLEN = False
class _LeanFlashVarlen(torch.autograd.Function):
@@ -591,7 +630,9 @@ def _varlen_attn_call(Q_f, K_f, V_f, cu_seqlens, max_seqlen, *, scale, window_si
if (
_LEAN_VARLEN
and not torch.compiler.is_compiling()
- and not _varlen_can_use_cudnn(Q_f, K_f, V_f, max_seqlen, list(window_size), enable_gqa)
+ and not _varlen_can_use_cudnn(
+ Q_f, K_f, V_f, cu_seqlens, max_seqlen, list(window_size), enable_gqa
+ )
):
return _LeanFlashVarlen.apply(
Q_f,