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
Keep xFormers attention masks on the GPU running each layer (#8516)
oobabooga1840f7bd7f07
diff --git a/tests/utils/test_attention_masks.py b/tests/utils/test_attention_masks.pyindex 45727fc7041..5d89e22ca74 100644--- a/tests/utils/test_attention_masks.py+++ b/tests/utils/test_attention_masks.py@@ -18,6 +18,7 @@import mathimport weakref+import pytestimport torchfrom unsloth.utils import attention_dispatch@@ -62,18 +63,24 @@ def test_xformers_block_mask_sliding_window(monkeypatch):self,lengths,window = None,+ device = None,):self.lengths = lengthsself.window = window+ self.device = torch.device(device)@classmethoddef from_seqlens(cls, lengths):- return cls(tuple(lengths))+ return cls(tuple(lengths), device = "cuda:0")def make_local_attention(self, window_size):- return _FakeMask(self.lengths, window = window_size)+ return _FakeMask(self.lengths, window = window_size, device = self.device)++ def to(self, device):+ return _FakeMask(self.lengths, window = self.window, device = device)monkeypatch.setattr(packing_utils, "_XFormersBlockMask", _FakeMask, raising = False)+ packing_utils.clear_packed_caches()seq_info = _make_seq_info([4, 4])mask = packing_utils.build_xformers_block_causal_mask(@@ -83,6 +90,222 @@ def test_xformers_block_mask_sliding_window(monkeypatch):assert isinstance(mask, _FakeMask)assert mask.window == 2+ assert mask.device == torch.device("cpu")+ packing_utils.clear_packed_caches()+++def test_xformers_block_mask_cache_is_scoped_to_device(monkeypatch):+ class _FakeMask:+ def __init__(self, lengths, device):+ self.lengths = tuple(lengths)+ self.device = torch.device(device)++ @classmethod+ def from_seqlens(cls, lengths):+ return cls(lengths, "cuda:0")++ def to(self, device):+ return _FakeMask(self.lengths, device)++ monkeypatch.setattr(packing_utils, "_XFormersBlockMask", _FakeMask, raising = False)+ packing_utils.clear_packed_caches()++ lengths = (4, 4)+ cuda_0 = torch.device("cuda:0")+ cuda_1 = torch.device("cuda:1")+ first = packing_utils._get_cached_block_mask(lengths, None, cuda_0)+ second = packing_utils._get_cached_block_mask(lengths, None, cuda_1)++ assert first.device == cuda_0+ assert second.device == cuda_1+ assert second is not first+ assert packing_utils._get_cached_block_mask(lengths, None, cuda_0) is first++ packing_utils.clear_packed_caches()+ assert not packing_utils._XFORMERS_MASK_CACHE+++def test_xformers_bias_move_supports_legacy_in_place_metadata():+ class _LegacySeqInfo:+ def __init__(self, device):+ self.device = torch.device(device)++ def to(self, device):+ self.device = torch.device(device)++ class _LegacyBias:+ def __init__(self):+ self.q_seqinfo = _LegacySeqInfo("cuda:0")+ self.k_seqinfo = self.q_seqinfo++ bias = _LegacyBias()+ moved = packing_utils.move_xformers_attention_bias(bias, torch.device("cuda:1"))++ assert moved is not bias+ assert moved.q_seqinfo is moved.k_seqinfo+ assert moved.q_seqinfo.device == torch.device("cuda:1")+ assert bias.q_seqinfo is bias.k_seqinfo+ assert bias.q_seqinfo.device == torch.device("cuda:0")+++def test_xformers_bias_move_replaces_all_shared_metadata_aliases():+ class _FakeTensor:+ def __init__(self, device):+ self.device = torch.device(device)++ class _ReturningSeqInfo:+ def __init__(self, device):+ self.seqstart = _FakeTensor(device)++ def to(self, device):+ return _ReturningSeqInfo(device)++ class _Bias:+ def __init__(self):+ self.q_seqinfo = _ReturningSeqInfo("cuda:0")+ self.k_seqinfo = self.q_seqinfo++ bias = _Bias()+ original = bias.q_seqinfo+ moved = packing_utils.move_xformers_attention_bias(bias, torch.device("cuda:1"))++ assert moved is not bias+ assert moved.q_seqinfo is moved.k_seqinfo+ assert moved.q_seqinfo is not original+ assert moved.q_seqinfo.seqstart.device == torch.device("cuda:1")+ assert bias.q_seqinfo is bias.k_seqinfo+ assert bias.q_seqinfo is original+ assert bias.q_seqinfo.seqstart.device == torch.device("cuda:0")+++def test_xformers_bias_move_preserves_causal_type_when_to_demotes():+ class _FakeTensor:+ def __init__(self, device):+ self.device = torch.device(device)++ class _ReturningSeqInfo:+ def __init__(self, device):+ self.seqstart = _FakeTensor(device)++ def to(self, device):+ return _ReturningSeqInfo(device)++ class _BaseBias:+ def __init__(self, seqinfo):+ self.q_seqinfo = seqinfo+ self.k_seqinfo = seqinfo++ def to(self, device):+ return _BaseBias(self.q_seqinfo.to(device))++ class _CausalBias(_BaseBias):+ pass++ bias = _CausalBias(_ReturningSeqInfo("cuda:0"))+ first = packing_utils.move_xformers_attention_bias(bias, torch.device("cuda:1"))+ second = packing_utils.move_xformers_attention_bias(bias, torch.device("cuda:2"))++ assert first is not bias+ assert type(first) is _CausalBias+ assert first.q_seqinfo is first.k_seqinfo+ assert first.q_seqinfo.seqstart.device == torch.device("cuda:1")+ assert second is not bias+ assert type(second) is _CausalBias+ assert second.q_seqinfo is second.k_seqinfo+ assert second.q_seqinfo.seqstart.device == torch.device("cuda:2")+ assert first.q_seqinfo.seqstart.device == torch.device("cuda:1")+ assert bias.q_seqinfo is bias.k_seqinfo+ assert bias.q_seqinfo.seqstart.device == torch.device("cuda:0")+++def test_xformers_bias_move_skips_matching_metadata_device():+ class _SeqInfo:+ def __init__(self):+ self.seqstart = torch.empty(0)++ class _Bias:+ def __init__(self):+ self.q_seqinfo = _SeqInfo()+ self.k_seqinfo = self.q_seqinfo++ def to(self, device):+ raise AssertionError("matching metadata should not be moved")++ bias = _Bias()+ assert packing_utils.move_xformers_attention_bias(bias, torch.device("cpu")) is bias+++ torch.cuda.device_count() < 2 or packing_utils._XFormersBlockMask is None,+ reason = "needs xFormers and two CUDA devices",+)+def test_real_xformers_packed_mask_validates_on_each_device():+ from xformers.ops.fmha.common import Inputs+ packing_utils.clear_packed_caches()+ try:+ masks = []+ for index in (0, 1):+ device = torch.device(f"cuda:{index}")+ lengths = torch.tensor([4, 4], dtype = torch.int32, device = device)+ masks.append(+ packing_utils.build_xformers_block_causal_mask(+ (lengths, torch.empty(0, dtype = torch.int32, device = device), 4)+ )+ )++ assert masks[0].q_seqinfo.seqstart.device == torch.device("cuda:0")+ assert masks[1].q_seqinfo.seqstart.device == torch.device("cuda:1")+ assert masks[1] is not masks[0]++ config = attention_dispatch.AttentionConfig(+ backend = attention_dispatch.XFORMERS,+ n_kv_heads = 1,+ n_groups = 1,+ )+ context = attention_dispatch.AttentionContext(+ bsz = 1,+ q_len = 8,+ kv_seq_len = 8,+ n_heads = 1,+ head_dim = 64,+ requires_grad = True,+ seq_info = None,+ attention_mask = None,+ causal_mask = masks[0],+ )+ queries = []+ outputs = []+ for index in (0, 1):+ device = torch.device(f"cuda:{index}")+ query = torch.zeros(+ (1, 8, 1, 64), dtype = torch.float16, device = device, requires_grad = True+ )+ Inputs(query = query, key = query, value = query, attn_bias = masks[index]).validate_inputs()+ model_query = query.transpose(1, 2)+ outputs.append(+ attention_dispatch.run_attention(+ config = config,+ context = context,+ Q = model_query,+ K = model_query,+ V = model_query,+ )+ )+ queries.append(query)++ assert masks[0].q_seqinfo.seqstart.device == torch.device("cuda:0")+ for index, output in enumerate(outputs):+ assert output.device == torch.device(f"cuda:{index}")+ assert bool(torch.isfinite(output).all())++ # Start backward only after the second shard has consumed the shared+ # source mask, matching model-parallel layer execution.+ for query, output in zip(queries, outputs):+ output.sum().backward()+ assert query.grad is not None+ assert bool(torch.isfinite(query.grad).all())+ finally:+ packing_utils.clear_packed_caches()def test_run_attention_sdpa_passes_sliding_window(monkeypatch):@@ -161,7 +384,11 @@ def test_run_attention_xformers_passes_sliding_window(monkeypatch):sliding_window = 3class _FakeBias:- pass+ def __init__(self, device = "cuda:0"):+ self.device = torch.device(device)++ def to(self, device):+ return _FakeBias(device)captured = {}@@ -222,6 +449,7 @@ def test_run_attention_xformers_passes_sliding_window(monkeypatch):assert captured["window"] == sliding_windowassert isinstance(captured["bias"], _FakeBias)+ assert captured["bias"].device == torch.device("cpu")def test_run_attention_flash_varlen_receives_window_and_softcap(monkeypatch):diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex fa229279802..cd3bbd678ad 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -29,6 +29,7 @@ from ..models._utils import *from ..utils.packing import (build_sdpa_packed_attention_mask,build_xformers_block_causal_mask,+ move_xformers_attention_bias,)flash_attn_func = None@@ -457,6 +458,7 @@ def run_attention(sliding_window = sliding_window,base_mask = context.causal_mask,)+ attn_bias = move_xformers_attention_bias(attn_bias, Q.device)Q_t = Q.transpose(1, 2)K_t = K.transpose(1, 2)diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex 1e1d8155b4a..3262589a6d8 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -17,6 +17,7 @@from __future__ import annotations+import copyimport inspectimport loggingimport os@@ -37,7 +38,7 @@ except Exception:_XFormersBlockMask = None_XFORMERS_MASK_CACHE_MAXSIZE = 32-_XFORMERS_MASK_CACHE: OrderedDict[Tuple[Tuple[int, ...], int], Any] = OrderedDict()+_XFORMERS_MASK_CACHE: OrderedDict[Tuple[torch.device, Tuple[int, ...], int], Any] = OrderedDict()# Cache per device for get_packed_info_from_kwargs to avoid repeated D2H sync across layers_PACKED_INFO_CACHE: dict = {}@@ -55,12 +56,62 @@ def _window_cache_key(sliding_window: Optional[int]) -> int:return int(sliding_window)-def _get_cached_block_mask(lengths: Tuple[int, ...], sliding_window: Optional[int]):+def move_xformers_attention_bias(attn_bias: Any, device: torch.device):+ """Return an xFormers attention bias whose tensor metadata is on ``device``."""+ if attn_bias is None:+ return None++ device = torch.device(device)+ seqinfos = [+ (name, seqinfo)+ for name in ("q_seqinfo", "k_seqinfo")+ if (seqinfo := getattr(attn_bias, name, None)) is not None+ ]+ if seqinfos:+ if all(+ getattr(getattr(seqinfo, "seqstart", None), "device", None) == device+ for _, seqinfo in seqinfos+ ):+ return attn_bias++ # Move the device-bearing metadata instead of the top-level mask. Older+ # xFormers versions demote causal masks in their inherited ``to`` method.+ # Copies also keep later model shards from rewriting masks retained for+ # backward by earlier shards.+ moved_bias = copy.copy(attn_bias)+ moved_seqinfos = {}+ for name, seqinfo in seqinfos:+ source_id = id(seqinfo)+ if source_id not in moved_seqinfos:+ moved_seqinfo = copy.copy(seqinfo)+ move = getattr(moved_seqinfo, "to", None)+ if callable(move):+ moved = move(device)+ if moved is not None:+ moved_seqinfo = moved+ moved_seqinfos[source_id] = moved_seqinfo+ setattr(moved_bias, name, moved_seqinfos[source_id])+ return moved_bias++ # Biases without sequence metadata can safely use their own move protocol.+ moved_bias = copy.copy(attn_bias)+ move = getattr(moved_bias, "to", None)+ if callable(move):+ moved = move(device)+ if moved is not None:+ moved_bias = moved+ return moved_bias+++def _get_cached_block_mask(+ lengths: Tuple[int, ...], sliding_window: Optional[int], device: torch.device+):if _XFormersBlockMask is None:return None+ device = torch.device(device)window_key = _window_cache_key(sliding_window)- cache_key = (lengths, window_key)+ cache_key = (device, lengths, window_key)cached = _XFORMERS_MASK_CACHE.get(cache_key)if cached is not None:_XFORMERS_MASK_CACHE.move_to_end(cache_key)@@ -69,6 +120,7 @@ def _get_cached_block_mask(lengths: Tuple[int, ...], sliding_window: Optional[inmask = _XFormersBlockMask.from_seqlens(list(lengths))if window_key and mask is not None and hasattr(mask, "make_local_attention"):mask = mask.make_local_attention(window_size = window_key)+ mask = move_xformers_attention_bias(mask, device)_XFORMERS_MASK_CACHE[cache_key] = maskif len(_XFORMERS_MASK_CACHE) > _XFORMERS_MASK_CACHE_MAXSIZE:@@ -575,7 +627,7 @@ def build_xformers_block_causal_mask(if lengths_tensor.numel() == 0:return Nonelengths = tuple(int(x) for x in lengths_tensor.tolist())- mask = _get_cached_block_mask(lengths, sliding_window)+ mask = _get_cached_block_mask(lengths, sliding_window, device)_XFORMERS_BLOCK_MASK_CACHE[device] = {"seq_lengths": seq_lengths,@@ -722,6 +774,7 @@ def mask_packed_boundary_labels(def clear_packed_caches():"""Release cached masks/metadata to free device memory."""+ _XFORMERS_MASK_CACHE.clear()_PACKED_INFO_CACHE.clear()_SDPA_MASK_CACHE.clear()_XFORMERS_BLOCK_MASK_CACHE.clear()@@ -732,6 +785,7 @@ __all__ = ["configure_padding_free","enable_sample_packing","enable_padding_free_metadata",+ "move_xformers_attention_bias","mark_allow_overlength","get_packed_info_from_kwargs","build_xformers_block_causal_mask",