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.

Carry the sliding window into SDPA, and treat a zero window as no window (#8253)

Daniel Han7088df88ea22
diff --git a/tests/utils/test_attention_masks.py b/tests/utils/test_attention_masks.py
index 627da0552fb..45727fc7041 100644
--- a/tests/utils/test_attention_masks.py
+++ b/tests/utils/test_attention_masks.py
@@ -16,6 +16,7 @@
"""Unit tests for packed-attention mask helpers with sliding-window logic."""
import math
+import weakref
import torch
@@ -285,3 +286,202 @@ def test_run_attention_flash_varlen_receives_window_and_softcap(monkeypatch):
"""Unit tests for packed-attention mask helpers with sliding-window logic."""
+
+
+def test_run_attention_sdpa_windows_an_unpacked_unmasked_batch(monkeypatch):
+ """No packing, no padding mask: the case that had nothing to hang the window off.
+
+ SDPA's ``is_causal`` is FULL causal -- it has no window -- so with neither the xformers
+ bias nor flash's ``window_size`` in play, a model whose config declares a sliding window
+ attended its entire causal history. That is reachable from a Mistral training step the
+ moment xFormers is disabled and FlashAttention is absent, which is precisely what the
+ kernel probe can now decide.
+ """
+ captured = {}
+
+ def _fake_sdpa(Q, K, V, **kwargs):
+ captured["mask"] = kwargs.get("attn_mask")
+ captured["is_causal"] = kwargs.get("is_causal")
+ return torch.zeros_like(Q)
+
+ monkeypatch.setattr(attention_dispatch, "scaled_dot_product_attention", _fake_sdpa)
+
+ config = attention_dispatch.AttentionConfig(
+ backend = attention_dispatch.SDPA,
+ n_kv_heads = 1,
+ n_groups = 1,
+ )
+ context = attention_dispatch.AttentionContext(
+ bsz = 1,
+ q_len = 6,
+ kv_seq_len = 6,
+ n_heads = 1,
+ head_dim = 1,
+ requires_grad = True,
+ seq_info = None,
+ attention_mask = None,
+ causal_mask = None,
+ sliding_window = 3,
+ )
+ Q = torch.zeros(1, 1, 6, 1)
+
+ attention_dispatch.run_attention(config = config, context = context, Q = Q, K = Q, V = Q)
+
+ mask = captured["mask"]
+ assert mask is not None, "a declared window must not fall through to plain is_causal"
+ assert captured["is_causal"] is False
+ assert mask.shape == (1, 1, 6, 6)
+ # Row 5 sees 3, 4, 5 and nothing older; the future stays masked either way.
+ assert [bool(v) for v in mask[0, 0, 5]] == [False, False, False, True, True, True]
+
+
+def test_run_attention_sdpa_leaves_a_short_sequence_alone(monkeypatch):
+ # Shorter than the window: nothing to clamp, and the cheap is_causal path must survive.
+ captured = {}
+ monkeypatch.setattr(
+ attention_dispatch,
+ "scaled_dot_product_attention",
+ lambda Q, K, V, **kw: (captured.update(kw), torch.zeros_like(Q))[1],
+ )
+ config = attention_dispatch.AttentionConfig(
+ backend = attention_dispatch.SDPA, n_kv_heads = 1, n_groups = 1
+ )
+ context = attention_dispatch.AttentionContext(
+ bsz = 1,
+ q_len = 4,
+ kv_seq_len = 4,
+ n_heads = 1,
+ head_dim = 1,
+ requires_grad = True,
+ seq_info = None,
+ attention_mask = None,
+ causal_mask = None,
+ sliding_window = 8,
+ )
+ Q = torch.zeros(1, 1, 4, 1)
+ attention_dispatch.run_attention(config = config, context = context, Q = Q, K = Q, V = Q)
+ assert captured["attn_mask"] is None and captured["is_causal"] is True
+
+
+def test_mistral_hands_the_dispatcher_its_configured_window():
+ """The context Mistral builds omitted `sliding_window` entirely, so even a correct SDPA
+ window path had nothing to act on."""
+ import ast
+ from pathlib import Path
+
+ src = Path(attention_dispatch.__file__).resolve().parents[1] / "models" / "mistral.py"
+ tree = ast.parse(src.read_text(encoding = "utf-8"))
+ contexts = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "AttentionContext"
+ ]
+ assert contexts, "AttentionContext construction not found in mistral.py"
+ for call in contexts:
+ assert "sliding_window" in {kw.arg for kw in call.keywords}
+
+
+def test_a_zero_configured_window_is_full_causal_not_a_blank_mask():
+ """`sliding_window = 0` means "no local attention", the same as absent -- which is how
+ Mistral's own mask builders read it. Passing the 0 through makes the SDPA lower bound
+ `q_pos - (0 - 1)` sit above the causal upper bound, so every position is masked and the
+ layer returns nothing at all."""
+ import ast
+ from pathlib import Path
+
+ src = Path(attention_dispatch.__file__).resolve().parents[1] / "models" / "mistral.py"
+ text = src.read_text(encoding = "utf-8")
+ assert "isinstance(sw_cfg, int) and sw_cfg <= 0" in text, (
+ "a non-positive configured window must be normalised before it reaches window_size "
+ "or the dispatcher"
+ )
+ ast.parse(text)
+
+
+def test_run_attention_sdpa_ignores_a_zero_window(monkeypatch):
+ # Belt and braces at the dispatcher: even handed a zero, it must not build a mask that
+ # hides everything.
+ captured = {}
+ monkeypatch.setattr(
+ attention_dispatch,
+ "scaled_dot_product_attention",
+ lambda Q, K, V, **kw: (captured.update(kw), torch.zeros_like(Q))[1],
+ )
+ config = attention_dispatch.AttentionConfig(
+ backend = attention_dispatch.SDPA, n_kv_heads = 1, n_groups = 1
+ )
+ context = attention_dispatch.AttentionContext(
+ bsz = 1,
+ q_len = 4,
+ kv_seq_len = 4,
+ n_heads = 1,
+ head_dim = 1,
+ requires_grad = True,
+ seq_info = None,
+ attention_mask = None,
+ causal_mask = None,
+ sliding_window = 0,
+ )
+ Q = torch.zeros(1, 1, 4, 1)
+ attention_dispatch.run_attention(config = config, context = context, Q = Q, K = Q, V = Q)
+ mask = captured["attn_mask"]
+ assert mask is None or bool(mask.any()), "a zero window must not mask everything"
+
+
+def test_the_window_mask_is_built_once_per_shape(monkeypatch):
+ """Every layer asks for the identical mask, and at 32K that tensor is 1 GiB with two more
+ alive while it is built. Rebuilding it per layer is how this SDPA fallback OOMs a run that
+ xFormers or flash would have carried."""
+ attention_dispatch._WINDOW_MASK_CACHE.clear()
+ built = []
+ real_arange = torch.arange
+
+ def _counting_arange(*args, **kwargs):
+ built.append(1)
+ return real_arange(*args, **kwargs)
+
+ monkeypatch.setattr(attention_dispatch.torch, "arange", _counting_arange)
+
+ first = attention_dispatch._windowed_causal_mask(6, 6, 3, torch.device("cpu"))
+ calls_after_first = len(built)
+ second = attention_dispatch._windowed_causal_mask(6, 6, 3, torch.device("cpu"))
+
+ assert second is first, "the same shape and window must not be rebuilt"
+ assert len(built) == calls_after_first, "a cache hit must allocate nothing"
+ assert [bool(v) for v in first[0, 0, 5]] == [False, False, False, True, True, True]
+
+ # A different window is a different mask, not a stale hit.
+ third = attention_dispatch._windowed_causal_mask(6, 6, 2, torch.device("cpu"))
+ assert third is not first
+ assert [bool(v) for v in third[0, 0, 5]] == [False, False, False, False, True, True]
+ # ...and so is a different shape.
+ assert attention_dispatch._windowed_causal_mask(4, 4, 3, torch.device("cpu")) is not third
+ attention_dispatch._WINDOW_MASK_CACHE.clear()
+
+
+def test_the_outgoing_window_mask_is_freed_before_its_replacement(monkeypatch):
+ """A shape change must not hold two dense masks at once. Dynamic-length training walks
+ through shapes, and at 32K each mask is 1 GiB on top of the construction temporaries."""
+ attention_dispatch._WINDOW_MASK_CACHE.clear()
+ device = torch.device("cpu")
+ first = attention_dispatch._windowed_causal_mask(6, 6, 3, device)
+ live = weakref.ref(first)
+ del first
+
+ cached_during_build = []
+ real_arange = torch.arange
+
+ def _observing_arange(*args, **kwargs):
+ cached_during_build.append(live() is not None)
+ return real_arange(*args, **kwargs)
+
+ monkeypatch.setattr(attention_dispatch.torch, "arange", _observing_arange)
+ attention_dispatch._windowed_causal_mask(8, 8, 3, device)
+
+ assert cached_during_build, "the replacement must actually have been built"
+ assert not any(
+ cached_during_build
+ ), "the previous mask was still alive while its replacement was allocated"
+ attention_dispatch._WINDOW_MASK_CACHE.clear()
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index c80f274ecc9..d73942c27fd 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -40,6 +40,7 @@ from ..utils.packing import (
from ..utils.attention_dispatch import (
AttentionConfig,
AttentionContext,
+ HAS_XFORMERS,
run_attention,
SDPA,
select_attention_backend,
@@ -127,7 +128,11 @@ except:
from huggingface_hub.utils._token import get_token
from triton import __version__ as triton_version
-HAS_XFORMERS = xformers is not None
+# Not `xformers is not None`: attention_dispatch probes the install and turns HAS_XFORMERS
+# off when the library imports but has no kernel that runs here. Recomputing it from the
+# import alone left the model code on the xFormers path the dispatcher had already left --
+# and Mistral answers "xFormers" by skipping the 4D sliding-window mask, so every sequence
+# longer than config.sliding_window attended to the whole causal history on SDPA instead.
BlockDiagonalCausalMask = xformers.attn_bias.BlockDiagonalCausalMask if HAS_XFORMERS else None
diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.py
index 4350565fe24..da6468fdd15 100644
--- a/unsloth/models/mistral.py
+++ b/unsloth/models/mistral.py
@@ -109,7 +109,13 @@ def MistralAttention_fast_forward(
# Attention module
sw_cfg = getattr(self.config, "sliding_window", None)
- sw = kv_seq_len if (sw_cfg is None or sw_cfg == "null") else sw_cfg
+ # A non-positive window means "no local attention", the same as absent. Passing 0 through
+ # made window_size (0, 0) for flash and an all-false SDPA mask, since the lower bound
+ # q_pos - (0 - 1) sits above the causal upper bound.
+ if sw_cfg is None or sw_cfg == "null" or (isinstance(sw_cfg, int) and sw_cfg <= 0):
+ sw = kv_seq_len
+ else:
+ sw = sw_cfg
window_size = (-1, -1) if (kv_seq_len <= sw) else (sw, sw)
use_varlen = seq_info is not None and past_key_value is None and window_size == (-1, -1)
@@ -138,6 +144,12 @@ def MistralAttention_fast_forward(
seq_info = seq_info,
attention_mask = attention_mask,
causal_mask = causal_mask,
+ # The window the flash path already gets through window_size. SDPA needs it too, and
+ # not only in the branch above: training takes `elif self.training: pass`, so no 4D
+ # mask is synthesized, and with xformers off and flash absent the local window was the
+ # one thing nothing carried -- every sequence past config.sliding_window silently
+ # attended its whole causal history.
+ sliding_window = None if window_size == (-1, -1) else sw,
prefix_seg_info = _pg_seg,
)
diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.py
index 54f8100ca12..07df8f1be21 100644
--- a/unsloth/utils/attention_dispatch.py
+++ b/unsloth/utils/attention_dispatch.py
@@ -175,6 +175,33 @@ def resolve_prefix_seg_info(kwargs, past_key_value, attention_mask):
return seg
+# One dense window mask per (device, shape, window), reused across layers. Every layer of a
+# Mistral-style model asks for the identical mask, and at 32K that tensor is 1 GiB with two more
+# alive while it is built, so rebuilding it 32 times is how this SDPA fallback OOMs a run that
+# xFormers or flash would have carried. Same single-entry-per-device shape as _SDPA_MASK_CACHE.
+_WINDOW_MASK_CACHE: dict = {}
+
+
+def _windowed_causal_mask(q_len: int, k_len: int, sliding_window: int, device) -> Tensor:
+ """Causal band mask of shape (1, 1, q_len, k_len). Read-only: callers must not mutate it."""
+ params = (q_len, k_len, sliding_window)
+ entry = _WINDOW_MASK_CACHE.get(device)
+ if entry is not None and entry["params"] == params:
+ return entry["mask"]
+ # Drop the outgoing mask first. It is dead either way, and holding it while the replacement
+ # and its temporaries are allocated would make a shape change peak a whole mask higher.
+ _WINDOW_MASK_CACHE.pop(device, None)
+ entry = None
+ q_pos = torch.arange(k_len - q_len, k_len, device = device)
+ k_pos = torch.arange(k_len, device = device)
+ mask = (
+ (k_pos[None, :] <= q_pos[:, None])
+ & (k_pos[None, :] >= (q_pos[:, None] - (sliding_window - 1)))
+ )[None, None, :, :]
+ _WINDOW_MASK_CACHE[device] = {"params": params, "mask": mask}
+ return mask
+
+
def run_attention(
*, config: AttentionConfig, context: AttentionContext, Q: Tensor, K: Tensor, V: Tensor
) -> Tensor:
@@ -234,6 +261,11 @@ def run_attention(
kv_seq_len = context.kv_seq_len
requires_grad = context.requires_grad
sliding_window = context.sliding_window
+ # A non-positive window means "no local attention", not "a window of nothing": a config
+ # spelling it 0 would otherwise put the mask's lower bound above its causal upper bound
+ # and hide every position from every other.
+ if sliding_window is not None and sliding_window <= 0:
+ sliding_window = None
# DoRA promotes q/k/v_proj outputs to fp32, which FlashAttention rejects (and so does
# the xformers flash-2 op on sm_100+, see _XFORMERS_FP32_UNSUPPORTED), so downcast any
@@ -393,6 +425,15 @@ def run_attention(
no_allowed = ~local_mask.any(dim = -1, keepdim = True) # (bsz,1,q_len,1)
local_mask = local_mask | no_allowed
+ if local_mask is None and sliding_window is not None and k_len_local > sliding_window:
+ # SDPA's is_causal is FULL causal; it has no window. With no padding mask to
+ # hang the window off, a model whose config declares one attended its whole
+ # history whenever neither the xformers bias nor flash's window_size was the
+ # thing running.
+ local_mask = _windowed_causal_mask(
+ q_len_local, k_len_local, sliding_window, Q.device
+ )
+
is_causal_local = local_mask is None and q_len_local == k_len_local
kwargs = dict(sdpa_kwargs)