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
fix: replace deprecated transformers attention mask imports (#6880)
Taranum Wasu7367955bcbc9
diff --git a/tests/utils/test_attn_mask_compat.py b/tests/utils/test_attn_mask_compat.pynew file mode 100644index 00000000000..929a270e31b--- /dev/null+++ b/tests/utils/test_attn_mask_compat.py@@ -0,0 +1,308 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Equivalence tests for local attention-mask compat helpers (issue #6860)."""++import importlib+import importlib.util+import sys+import types+import warnings+from pathlib import Path+from unittest import mock++import pytest+import torch++_REPO_ROOT = Path(__file__).resolve().parents[2]+_COMPAT_PATH = _REPO_ROOT / "unsloth" / "models" / "_attn_mask_compat.py"+++def _load_compat_module():+ module_name = "unsloth.models._attn_mask_compat"+ spec = importlib.util.spec_from_file_location(module_name, _COMPAT_PATH)+ module = importlib.util.module_from_spec(spec)+ assert spec.loader is not None+ sys.modules[module_name] = module+ spec.loader.exec_module(module)+ return module+++compat = _load_compat_module()+++def test_no_deprecation_warning_on_causal_mask():+ with warnings.catch_warnings(record = True) as caught:+ warnings.simplefilter("always")+ compat.AttentionMaskConverter(is_causal = True, sliding_window = 3).to_causal_4d(+ 1,+ 8,+ 8,+ dtype = torch.float16,+ )+ assert not any(+ issubclass(w.category, FutureWarning) and "modeling_attn_mask_utils" in str(w.message)+ for w in caught+ )++[email protected]("batch_size", [1, 2])[email protected]("query_length", [1, 4, 8])[email protected]("sliding_window", [None, 3, 5])+def test_causal_4d_matches_transformers(batch_size, query_length, sliding_window):+ try:+ legacy = importlib.import_module("transformers.modeling_attn_mask_utils")+ except ImportError:+ pytest.skip("transformers.modeling_attn_mask_utils unavailable")++ key_value_length = query_length+ dtype = torch.float32++ with warnings.catch_warnings():+ warnings.simplefilter("ignore", FutureWarning)+ expected = legacy.AttentionMaskConverter(+ is_causal = True,+ sliding_window = sliding_window,+ ).to_causal_4d(+ batch_size,+ query_length,+ key_value_length,+ dtype = dtype,+ )++ actual = compat.AttentionMaskConverter(+ is_causal = True,+ sliding_window = sliding_window,+ ).to_causal_4d(+ batch_size,+ query_length,+ key_value_length,+ dtype = dtype,+ )++ if expected is None:+ assert actual is None+ else:+ assert torch.equal(actual, expected)+++ "attention_mask,past_length",+ [+ (None, 0),+ (None, 4),+ (torch.ones(2, 5), 0),+ (torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]]), 0),+ ],+)+def test_prepare_4d_causal_attention_mask_for_sdpa_matches_transformers(+ attention_mask, past_length+):+ try:+ legacy = importlib.import_module("transformers.modeling_attn_mask_utils")+ except ImportError:+ pytest.skip("transformers.modeling_attn_mask_utils unavailable")++ batch_size = 2 if attention_mask is not None else 1+ query_length = 5+ inputs_embeds = torch.zeros(batch_size, query_length, 16, dtype = torch.float32)++ with warnings.catch_warnings():+ warnings.simplefilter("ignore", FutureWarning)+ expected = legacy._prepare_4d_causal_attention_mask_for_sdpa(+ attention_mask,+ (batch_size, query_length),+ inputs_embeds,+ past_length,+ sliding_window = 3,+ )++ actual = compat._prepare_4d_causal_attention_mask_for_sdpa(+ attention_mask,+ (batch_size, query_length),+ inputs_embeds,+ past_length,+ sliding_window = 3,+ )++ if expected is None:+ assert actual is None+ else:+ assert torch.equal(actual, expected)++[email protected](not torch.cuda.is_available(), reason = "needs CUDA")+ "attention_mask,past_length",+ [+ (None, 8),+ (None, 0),+ ("ones", 8),+ ("left_pad", 8),+ ],+)+def test_sdpa_mask_matches_transformers_on_cuda(attention_mask, past_length):+ """CUDA counterpart of the test above.++ `_unmask_unattended` is gated on ``device.type in ("cuda", "xpu")``, so a+ CPU-only comparison never reaches it. Asserts stride and storage too: an+ expanded view materialised into a dense [bsz, 1, q, kv] tensor is a memory+ regression even when every element compares equal.+ """+ try:+ legacy = importlib.import_module("transformers.modeling_attn_mask_utils")+ except ImportError:+ pytest.skip("transformers.modeling_attn_mask_utils unavailable")++ batch_size, query_length = 4, 5+ key_value_length = query_length + past_length+ inputs_embeds = torch.zeros(+ batch_size,+ query_length,+ 16,+ dtype = torch.float32,+ device = "cuda",+ )+ if attention_mask == "ones":+ mask = torch.ones(batch_size, key_value_length, dtype = torch.int64, device = "cuda")+ elif attention_mask == "left_pad":+ mask = torch.ones(batch_size, key_value_length, dtype = torch.int64, device = "cuda")+ mask[:, :2] = 0+ else:+ mask = None++ with warnings.catch_warnings():+ warnings.simplefilter("ignore", FutureWarning)+ expected = legacy._prepare_4d_causal_attention_mask_for_sdpa(+ mask,+ (batch_size, query_length),+ inputs_embeds,+ past_length,+ sliding_window = 3,+ )+ actual = compat._prepare_4d_causal_attention_mask_for_sdpa(+ mask,+ (batch_size, query_length),+ inputs_embeds,+ past_length,+ sliding_window = 3,+ )++ if expected is None:+ assert actual is None+ return++ assert torch.equal(actual, expected)+ assert actual.stride() == expected.stride(), (+ f"layout diverged: {actual.stride()} vs upstream {expected.stride()} — "+ "an expanded view was materialised"+ )+ assert actual.untyped_storage().nbytes() == expected.untyped_storage().nbytes(), (+ f"allocation diverged: {actual.untyped_storage().nbytes()} bytes vs "+ f"upstream {expected.untyped_storage().nbytes()}"+ )+++def test_prepare_4d_attention_mask_for_sdpa_matches_transformers():+ try:+ legacy = importlib.import_module("transformers.modeling_attn_mask_utils")+ except ImportError:+ pytest.skip("transformers.modeling_attn_mask_utils unavailable")++ mask = torch.tensor([[1, 1, 0, 0], [1, 1, 1, 1]], dtype = torch.float32)+ dtype = torch.float32++ with warnings.catch_warnings():+ warnings.simplefilter("ignore", FutureWarning)+ expected = legacy._prepare_4d_attention_mask_for_sdpa(mask, dtype = dtype)++ actual = compat._prepare_4d_attention_mask_for_sdpa(mask, dtype = dtype)++ if expected is None:+ assert actual is None+ else:+ assert torch.equal(actual, expected)+++def test_repo_has_no_direct_deprecated_imports():+ model_dir = _REPO_ROOT / "unsloth" / "models"+ offenders = []+ for path in model_dir.glob("*.py"):+ if path.name == "_attn_mask_compat.py":+ continue+ text = path.read_text(encoding = "utf-8")+ if "transformers.modeling_attn_mask_utils" in text:+ offenders.append(str(path.relative_to(_REPO_ROOT)))+ assert offenders == []+++def test_import_falls_back_when_is_tracing_missing():+ """Regression for Codex review on PR #6880.++ The compat module imports `is_tracing` from `transformers.utils.import_utils`,+ but that symbol is only exported from transformers >= 5.0.0. It is absent+ from every 4.x release, including the declared `transformers>=4.51.3` floor+ and the 4.57.6 pin used by tests/version_compat, so the fallback below is+ the live path across the whole 4.x half of the supported range.++ Reload the module with `is_tracing` removed from the namespace and confirm+ the local fallback is used. The fallback must mirror the legacy+ `transformers==4.51.3` inline expression+ (``torch.jit.is_tracing() or isinstance(tensor, torch.fx.Proxy) or+ is_torchdynamo_compiling()``) so the data-dependent ``torch.all(...)``+ branches in the mask helpers continue to be skipped during JIT trace,+ symbolic trace, and Dynamo compilation — otherwise tracing/exporting+ these models on transformers 4.51.x either fails on proxy control flow+ or bakes the wrong SDPA causal-mask path.+ """+ fake_import_utils = types.ModuleType("transformers.utils.import_utils")++ def _is_torchdynamo_compiling() -> bool:+ return False++ fake_import_utils.is_torchdynamo_compiling = _is_torchdynamo_compiling+ # Deliberately no `is_tracing` attribute.++ # Ensure both the leaf and the parent's `transformers.utils` package+ # resolve to our stub so the `from ... import is_tracing` inside the+ # compat module body raises ImportError as it would on transformers+ # < 4.52. We re-use `transformers.utils` if it's already in sys.modules+ # (so we don't disturb the rest of the test suite), and only replace+ # the leaf submodule.+ existing_utils_pkg = sys.modules.get("transformers.utils")+ with mock.patch.dict(+ sys.modules,+ {"transformers.utils.import_utils": fake_import_utils},+ ):+ reloaded = _load_compat_module()++ assert existing_utils_pkg is not None, (+ "transformers.utils was not pre-imported; stubbing the leaf alone "+ "would not exercise the fallback path"+ )++ # Dynamo idle and no JIT/FX active → False.+ assert reloaded.is_tracing() is False+ # Sanity: accepts an optional tensor positional arg without raising.+ assert reloaded.is_tracing(torch.zeros(1)) is False++ # ``torch.fx.Proxy`` should be detected even when Dynamo is idle, since+ # symbolic_trace / export-only paths don't go through dynamo. Construct+ # the Proxy from a real fx.Graph node (passing a Tensor directly to+ # ``Proxy(...)`` is a common foot-gun that raises AttributeError).+ fx_graph = torch.fx.Graph()+ fx_node = fx_graph.create_node("call_function", torch.zeros, (torch.zeros(1).shape,))+ proxy = torch.fx.Proxy(fx_node)+ assert reloaded.is_tracing(proxy) is True++ # ``torch.jit.is_tracing()`` should be detected via patch.+ with mock.patch("torch.jit.is_tracing", return_value = True):+ assert reloaded.is_tracing() is True++ # Dynamo compilation is also covered (the fallback calls+ # ``is_torchdynamo_compiling`` from the module-level import, which is+ # bound at fallback-definition time — exactly the same import binding+ # that the real ``is_tracing`` uses). We don't re-test the dynamo path+ # here because it's already exercised by the upstream test suite, and+ # patching the import after the module is loaded would not affect the+ # closure's reference.diff --git a/tests/utils/test_attn_mask_upstream_drift.py b/tests/utils/test_attn_mask_upstream_drift.pynew file mode 100644index 00000000000..8ba3fff8c65--- /dev/null+++ b/tests/utils/test_attn_mask_upstream_drift.py@@ -0,0 +1,283 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Guards `_attn_mask_compat.py` against drifting from the upstream it vendors.++`unsloth/models/_attn_mask_compat.py` is a copy of Transformers'+`modeling_attn_mask_utils.py`, kept because that module is deprecated and will be+deleted. A hand-copied file drifts silently: two defects during review of #6880+were both invisible in the diff and only surfaced under differential testing.++So compare the two ASTs directly, after erasing differences that are stylistic+rather than semantic:++ * docstrings, type-annotation text, and the deprecation `warnings.warn` calls+ the vendored copy exists to drop;+ * `is_tracing`, which 4.x computes inline as a 3-way `or` and 5.x exposes as a+ helper the vendored copy imports (with a fallback);+ * single-use temporaries and a dead `else` after a `return`.++Two further differences are deliberate: the vendored copy carries forward-ports+that older Transformers lacks. Those are relaxed **only** below the version that+introduced them, so on newer installs they are still compared exactly:++ * the `xpu` device gate, added in 5.x;+ * the 0-dim inversion tensor, added in 4.53.0 (huggingface/transformers#38637).++Skips when the upstream module is gone, which is the end state this file is for.+"""++import ast+import importlib+import inspect+from pathlib import Path++import pytest++_REPO_ROOT = Path(__file__).resolve().parents[2]+_COMPAT_PATH = _REPO_ROOT / "unsloth" / "models" / "_attn_mask_compat.py"+++def _upstream_source():+ try:+ legacy = importlib.import_module("transformers.modeling_attn_mask_utils")+ except ImportError:+ pytest.skip("transformers.modeling_attn_mask_utils removed upstream")+ try:+ return inspect.getsource(legacy)+ except (OSError, TypeError):+ pytest.skip("upstream source unavailable (zipimport or compiled install)")+++def _transformers_version():+ import transformers++ parts = []+ for chunk in transformers.__version__.split(".")[:2]:+ digits = "".join(c for c in chunk if c.isdigit())+ parts.append(int(digits) if digits else 0)+ while len(parts) < 2:+ parts.append(0)+ return tuple(parts)+++def _is_deprecation_warning(stmt):+ return (+ isinstance(stmt, ast.Expr)+ and isinstance(stmt.value, ast.Call)+ and "warn" in ast.dump(stmt.value.func)+ and "DEPRECATION_MESSAGE" in ast.dump(stmt.value)+ )+++def _inline_tracing_expr(node):+ """Recognise 4.x's inline `torch.jit.is_tracing() or isinstance(...) or ...`."""+ if not isinstance(node, ast.BoolOp) or not isinstance(node.op, ast.Or):+ return None+ dumped = ast.dump(node)+ if "is_tracing" not in dumped or "is_torchdynamo_compiling" not in dumped:+ return None+ for sub in ast.walk(node):+ if (+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "isinstance"+ and sub.args+ ):+ return sub.args[0]+ return ast.Constant(value = None)+++class _Canonicalise(ast.NodeTransformer):+ def __init__(self, relax_device, relax_inversion):+ self.relax_device = relax_device+ self.relax_inversion = relax_inversion++ def _clean(self, node):+ if (+ node.body+ and isinstance(node.body[0], ast.Expr)+ and isinstance(node.body[0].value, ast.Constant)+ and isinstance(node.body[0].value.value, str)+ ):+ node.body = node.body[1:]+ node.body = [s for s in node.body if not _is_deprecation_warning(s)] or [ast.Pass()]+ return node++ def visit_FunctionDef(self, node):+ self.generic_visit(node)+ node = self._clean(node)+ node.returns = None+ for arg in list(node.args.args) + list(node.args.kwonlyargs) + list(node.args.posonlyargs):+ arg.annotation = None+ node.body = _hoist_dead_else(_inline_single_use(node.body))+ return node++ def visit_ClassDef(self, node):+ self.generic_visit(node)+ return self._clean(node)++ def visit_AnnAssign(self, node):+ # Dataclass field: the explicit __init__ makes any default unreachable.+ return ast.AnnAssign(+ target = node.target,+ annotation = ast.Name(id = "_", ctx = ast.Load()),+ value = None,+ simple = node.simple,+ )++ def visit_Name(self, node):+ # `is_tracing_` only avoids shadowing the imported helper.+ if node.id == "is_tracing_":+ return ast.Name(id = "is_tracing", ctx = node.ctx)+ return node++ def visit_BoolOp(self, node):+ self.generic_visit(node)+ arg = _inline_tracing_expr(node)+ if arg is not None:+ return ast.Call(func = ast.Name(id = "_TRACING", ctx = ast.Load()), args = [arg], keywords = [])+ return node++ def visit_Call(self, node):+ self.generic_visit(node)+ if isinstance(node.func, ast.Name) and node.func.id == "is_tracing":+ return ast.Call(+ func = ast.Name(id = "_TRACING", ctx = ast.Load()),+ args = list(node.args),+ keywords = [],+ )+ return node++ def visit_Compare(self, node):+ self.generic_visit(node)+ if self.relax_device and "'cuda'" in ast.dump(node):+ return ast.Name(id = "_DEVICE_GATE", ctx = ast.Load())+ return node++ def visit_BinOp(self, node):+ self.generic_visit(node)+ if (+ self.relax_inversion+ and isinstance(node.op, ast.Sub)+ and "value=1.0" in ast.dump(node.left)+ ):+ return ast.BinOp(+ left = ast.Name(id = "_ONE", ctx = ast.Load()), op = ast.Sub(), right = node.right+ )+ return node+++def _inline_single_use(body):+ """`t = expr` with exactly one later read of `t` becomes that expr inline."""+ out = list(body)+ changed = True+ while changed:+ changed = False+ for i, stmt in enumerate(out[:-1]):+ if not (+ isinstance(stmt, ast.Assign)+ and len(stmt.targets) == 1+ and isinstance(stmt.targets[0], ast.Name)+ ):+ continue+ name = stmt.targets[0].id+ rest = out[i + 1 :]+ reads = sum(+ 1+ for s in rest+ for n in ast.walk(s)+ if isinstance(n, ast.Name) and n.id == name and isinstance(n.ctx, ast.Load)+ )+ writes = sum(+ 1+ for s in rest+ for n in ast.walk(s)+ if isinstance(n, ast.Name) and n.id == name and isinstance(n.ctx, ast.Store)+ )+ if reads != 1 or writes:+ continue++ class _Sub(ast.NodeTransformer):+ def visit_Name(self, n):+ if n.id == name and isinstance(n.ctx, ast.Load):+ return stmt.value+ return n++ out = out[:i] + [_Sub().visit(s) for s in rest]+ changed = True+ break+ return out+++def _hoist_dead_else(body):+ """`if c: return A` + `else: B` is the same as the `if` followed by `B`."""+ out = []+ for stmt in body:+ if (+ isinstance(stmt, ast.If)+ and stmt.orelse+ and stmt.body+ and isinstance(stmt.body[-1], (ast.Return, ast.Raise, ast.Continue, ast.Break))+ ):+ tail = stmt.orelse+ stmt.orelse = []+ out.append(stmt)+ out.extend(_hoist_dead_else(tail))+ else:+ out.append(stmt)+ return out+++def _symbols(source, relax_device, relax_inversion):+ tree = _Canonicalise(relax_device, relax_inversion).visit(ast.parse(source))+ ast.fix_missing_locations(tree)+ found = {}+ for node in tree.body:+ if isinstance(node, (ast.FunctionDef, ast.ClassDef)):+ found[node.name] = node+ if isinstance(node, ast.ClassDef):+ for member in node.body:+ if isinstance(member, ast.FunctionDef):+ found[f"{node.name}.{member.name}"] = member+ return found+++def test_vendored_module_has_not_drifted_from_upstream():+ upstream_src = _upstream_source()+ version = _transformers_version()+ relax_device = version < (5, 0) # xpu gate forward-ported from 5.x+ relax_inversion = version < (4, 53) # 0-dim inversion forward-ported from 4.53.0++ upstream = _symbols(upstream_src, relax_device, relax_inversion)+ vendored = _symbols(_COMPAT_PATH.read_text(encoding = "utf-8"), relax_device, relax_inversion)++ shared = sorted(set(upstream) & set(vendored))+ assert shared, "no shared symbols found; the comparison is not doing anything"++ drifted = []+ for name in shared:+ if ast.dump(upstream[name]) != ast.dump(vendored[name]):+ drifted.append(+ f"\n--- {name} ---\nupstream:\n{ast.unparse(upstream[name])}\n"+ f"vendored:\n{ast.unparse(vendored[name])}"+ )++ assert not drifted, (+ f"{len(drifted)} symbol(s) drifted from transformers "+ f"{'.'.join(str(v) for v in version)}. Re-sync `_attn_mask_compat.py`, or if the "+ f"divergence is deliberate, relax it here behind a version gate and say why."+ + "".join(drifted)+ )+++def test_vendored_module_exports_everything_unsloth_imports():+ """The copy may be a subset of upstream, but not of what Unsloth uses."""+ upstream_src = _upstream_source()+ upstream = _symbols(upstream_src, False, False)+ vendored = _symbols(_COMPAT_PATH.read_text(encoding = "utf-8"), False, False)++ # Anything vendored must actually exist upstream; inventing symbols under an+ # upstream module's name would be a silent behavioural fork.+ invented = sorted(set(vendored) - set(upstream))+ assert invented == [], f"vendored symbols with no upstream counterpart: {invented}"diff --git a/unsloth/models/_attn_mask_compat.py b/unsloth/models/_attn_mask_compat.pynew file mode 100644index 00000000000..df6d2c7e70b--- /dev/null+++ b/unsloth/models/_attn_mask_compat.py@@ -0,0 +1,314 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+Attention-mask helpers, verified equivalent across Transformers 4.51.3 - 5.14.1.++`transformers.modeling_attn_mask_utils` warns on every call from 5.5.0 and+announces removal in v5.10. It still ships in 5.14.1, but Transformers itself no+longer imports it (135 internal references at 4.51.3, none from 5.5.0), so it can+be dropped at any release. Keeping a local copy of the surface we use means+imports survive that, and forward passes stop emitting deprecation warnings.++Adapted from HuggingFace Transformers `modeling_attn_mask_utils.py`+(Copyright 2023 The HuggingFace Team, Apache License 2.0).+See: https://github.com/unslothai/unsloth/issues/6860+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Union++import torch++from transformers.utils.import_utils import is_torchdynamo_compiling++try:+ # `is_tracing` exists only from Transformers 5.0.0, so the fallback below is+ # the live path for all of 4.x, not just the 4.51.3 floor. The fallback+ # mirrors what 4.x `modeling_attn_mask_utils` computes inline+ # (`torch.jit.is_tracing() or isinstance(x, torch.fx.Proxy) or+ # is_torchdynamo_compiling()`), so the data-dependent `torch.all(...)`+ # branches stay skipped under JIT / FX / Dynamo and SDPA path selection is+ # unchanged.+ from transformers.utils.import_utils import is_tracing # type: ignore[attr-defined]+except ImportError:++ def is_tracing(tensor = None) -> bool: # type: ignore[no-redef]+ """Local fallback for transformers < 5.0.0.++ True under ``torch.jit.trace``, ``torch.fx.symbolic_trace`` or Dynamo.+ The 5.x helper also detects CUDA stream capture, FakeTensor and JAX via+ torchax; 4.x itself detects none of those, so behaviour on 4.x matches.+ """+ if torch.jit.is_tracing():+ return True+ if tensor is not None and isinstance(tensor, torch.fx.Proxy):+ return True+ return is_torchdynamo_compiling()+++@dataclass+class AttentionMaskConverter:+ is_causal: bool+ sliding_window: int | None = None++ def __init__(+ self,+ is_causal: bool,+ sliding_window: int | None = None,+ ):+ self.is_causal = is_causal+ self.sliding_window = sliding_window++ if self.sliding_window is not None and self.sliding_window <= 0:+ raise ValueError(+ f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`"+ )++ def to_causal_4d(+ self,+ batch_size: int,+ query_length: int,+ key_value_length: int,+ dtype: torch.dtype,+ device: Union[torch.device, str] = "cpu",+ ) -> torch.Tensor | None:+ if not self.is_causal:+ raise ValueError(+ f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True."+ )++ input_shape = (batch_size, query_length)+ past_key_values_length = key_value_length - query_length++ causal_4d_mask = None+ if input_shape[-1] > 1 or self.sliding_window is not None:+ causal_4d_mask = self._make_causal_mask(+ input_shape,+ dtype,+ device = device,+ past_key_values_length = past_key_values_length,+ sliding_window = self.sliding_window,+ )++ return causal_4d_mask++ def to_4d(+ self,+ attention_mask_2d: torch.Tensor,+ query_length: int,+ dtype: torch.dtype,+ key_value_length: int | None = None,+ ) -> torch.Tensor:+ input_shape = (attention_mask_2d.shape[0], query_length)++ causal_4d_mask = None+ if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:+ if key_value_length is None:+ raise ValueError(+ "This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask."+ )++ past_key_values_length = key_value_length - query_length+ causal_4d_mask = self._make_causal_mask(+ input_shape,+ dtype,+ device = attention_mask_2d.device,+ past_key_values_length = past_key_values_length,+ sliding_window = self.sliding_window,+ )+ elif self.sliding_window is not None:+ raise NotImplementedError(+ "Sliding window is currently only implemented for causal masking"+ )++ expanded_attn_mask = self._expand_mask(+ attention_mask_2d, dtype, tgt_len = input_shape[-1]+ ).to(attention_mask_2d.device)++ if causal_4d_mask is not None:+ expanded_attn_mask = causal_4d_mask.masked_fill(+ expanded_attn_mask.bool(), torch.finfo(dtype).min+ )++ return expanded_attn_mask++ @staticmethod+ def _make_causal_mask(+ input_ids_shape: torch.Size,+ dtype: torch.dtype,+ device: torch.device,+ past_key_values_length: int = 0,+ sliding_window: int | None = None,+ ):+ bsz, tgt_len = input_ids_shape+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device = device)+ mask_cond = torch.arange(mask.size(-1), device = device)+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)++ mask = mask.to(dtype)++ if past_key_values_length > 0:+ mask = torch.cat(+ [torch.zeros(tgt_len, past_key_values_length, dtype = dtype, device = device), mask],+ dim = -1,+ )++ if sliding_window is not None:+ diagonal = past_key_values_length - sliding_window - 1++ context_mask = torch.tril(torch.ones_like(mask, dtype = torch.bool), diagonal = diagonal)+ if is_torchdynamo_compiling():+ mask = mask.clone()+ mask.masked_fill_(context_mask, torch.finfo(dtype).min)++ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)++ @staticmethod+ def _expand_mask(+ mask: torch.Tensor,+ dtype: torch.dtype,+ tgt_len: int | None = None,+ ):+ bsz, src_len = mask.size()+ tgt_len = tgt_len if tgt_len is not None else src_len++ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)++ # 0-dim tensor, not a Python float: a float literal lowers to an fp32+ # scalar and breaks ExecuTorch edge-dialect export on fp16/bf16 masks.+ # Matches upstream from 4.53.0 (huggingface/transformers#38637).+ inverted_mask = torch.tensor(1.0, dtype = dtype) - expanded_mask++ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)++ @staticmethod+ def _unmask_unattended(expanded_mask: torch.FloatTensor, min_dtype: float):+ if expanded_mask.dtype == torch.bool:+ raise ValueError(+ "AttentionMaskConverter._unmask_unattended expects a float `expanded_mask`, got a BoolTensor."+ )++ return expanded_mask.mul(~torch.all(expanded_mask == min_dtype, dim = -1, keepdim = True))++ @staticmethod+ def _ignore_causal_mask_sdpa(+ attention_mask: torch.Tensor | None,+ inputs_embeds: torch.Tensor,+ past_key_values_length: int,+ sliding_window: int | None = None,+ is_training: bool = False,+ ) -> bool:+ _, query_length = inputs_embeds.shape[0], inputs_embeds.shape[1]+ key_value_length = query_length + past_key_values_length++ is_tracing_ = is_tracing(inputs_embeds)++ ignore_causal_mask = False++ if attention_mask is None:+ if (+ (is_training or not is_tracing_)+ and (query_length == 1 or key_value_length == query_length)+ and (sliding_window is None or key_value_length < sliding_window)+ ):+ ignore_causal_mask = True+ elif sliding_window is None or key_value_length < sliding_window:+ if len(attention_mask.shape) == 4:+ return False+ elif not is_tracing_ and torch.all(attention_mask == 1):+ if query_length == 1 or key_value_length == query_length:+ ignore_causal_mask = True++ return ignore_causal_mask+++def _prepare_4d_causal_attention_mask_for_sdpa(+ attention_mask: torch.Tensor | None,+ input_shape: torch.Size | tuple | list,+ inputs_embeds: torch.Tensor,+ past_key_values_length: int,+ sliding_window: int | None = None,+):+ attn_mask_converter = AttentionMaskConverter(is_causal = True, sliding_window = sliding_window)++ key_value_length = input_shape[-1] + past_key_values_length++ is_tracing_ = is_tracing(inputs_embeds)++ ignore_causal_mask = AttentionMaskConverter._ignore_causal_mask_sdpa(+ attention_mask = attention_mask,+ inputs_embeds = inputs_embeds,+ past_key_values_length = past_key_values_length,+ sliding_window = sliding_window,+ )++ if ignore_causal_mask:+ expanded_4d_mask = None+ elif attention_mask is None:+ expanded_4d_mask = attn_mask_converter.to_causal_4d(+ input_shape[0],+ input_shape[-1],+ key_value_length,+ dtype = inputs_embeds.dtype,+ device = inputs_embeds.device,+ )+ else:+ if attention_mask.dim() == 4:+ expanded_4d_mask = attention_mask+ else:+ expanded_4d_mask = attn_mask_converter.to_4d(+ attention_mask,+ input_shape[-1],+ dtype = inputs_embeds.dtype,+ key_value_length = key_value_length,+ )++ # Attend to all tokens in masked rows, e.g. the first rows under left+ # padding. Required by F.scaled_dot_product_attention's memory-efficient+ # path: https://github.com/pytorch/pytorch/issues/110213+ # Scoped to this branch to match upstream. At function scope it also runs+ # on the `attention_mask is None` path, where it is a no-op numerically+ # but materialises `to_causal_4d`'s stride-0 view into a dense+ # [bsz, 1, q, kv] tensor.+ if not is_tracing_ and expanded_4d_mask.device.type in ["cuda", "xpu"]:+ expanded_4d_mask = AttentionMaskConverter._unmask_unattended(+ expanded_4d_mask, min_dtype = torch.finfo(inputs_embeds.dtype).min+ )++ return expanded_4d_mask+++def _prepare_4d_attention_mask(+ mask: torch.Tensor,+ dtype: torch.dtype,+ tgt_len: int | None = None,+):+ return AttentionMaskConverter._expand_mask(mask = mask, dtype = dtype, tgt_len = tgt_len)+++def _prepare_4d_attention_mask_for_sdpa(+ mask: torch.Tensor,+ dtype: torch.dtype,+ tgt_len: int | None = None,+):+ _, key_value_length = mask.shape+ tgt_len = tgt_len if tgt_len is not None else key_value_length++ if not is_tracing(mask) and torch.all(mask == 1):+ return None++ return AttentionMaskConverter._expand_mask(mask = mask, dtype = dtype, tgt_len = tgt_len)diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 9305f94e31d..5782763f27c 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -2895,7 +2895,7 @@ def create_boolean_mask(n = 4096, sliding_window = 2048):def test_mask_creation():- from transformers.modeling_attn_mask_utils import AttentionMaskConverter+ from unsloth.models._attn_mask_compat import AttentionMaskConverterfor n in range(2, 23):for s in range(1, 23):correct_mask = (diff --git a/unsloth/models/cohere.py b/unsloth/models/cohere.pyindex cb367d451e2..0ac2bed66b5 100644--- a/unsloth/models/cohere.py+++ b/unsloth/models/cohere.py@@ -45,7 +45,7 @@ except:f"to obtain the latest transformers build, then restart this session.")-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (_prepare_4d_causal_attention_mask_for_sdpa,)diff --git a/unsloth/models/falcon_h1.py b/unsloth/models/falcon_h1.pyindex e3e04e4fdcb..02260b25a19 100644--- a/unsloth/models/falcon_h1.py+++ b/unsloth/models/falcon_h1.py@@ -50,7 +50,7 @@ except:f'Try `pip install --upgrade "transformers>=4.53.0"`\n'f"to obtain the latest transformers build, then restart this session.")-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (_prepare_4d_causal_attention_mask_for_sdpa,)from transformers.utils import (diff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.pyindex 34655c57354..452a12fa754 100644--- a/unsloth/models/gemma.py+++ b/unsloth/models/gemma.py@@ -44,7 +44,7 @@ except:f"to obtain the latest transformers build, then restart this session.")-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (_prepare_4d_causal_attention_mask_for_sdpa,)diff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex 4a0531db781..144fb6ed46c 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -51,7 +51,7 @@ except:f"to obtain the latest transformers build, then restart this session.")-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (_prepare_4d_causal_attention_mask_for_sdpa,)diff --git a/unsloth/models/granite.py b/unsloth/models/granite.pyindex 17a44590023..382a9c33cd2 100644--- a/unsloth/models/granite.py+++ b/unsloth/models/granite.py@@ -63,7 +63,7 @@ except:f"to obtain the latest transformers build, then restart this session.")-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (_prepare_4d_causal_attention_mask_for_sdpa,)diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 4d4daec59f4..00cb2b92b33 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -76,7 +76,8 @@ from transformers.models.llama.modeling_llama import (BaseModelOutputWithPast,CausalLMOutputWithPast,)-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (+ AttentionMaskConverter,_prepare_4d_causal_attention_mask_for_sdpa,)from ..kernels import *@@ -1103,8 +1104,6 @@ def LlamaModel_fast_forward(# masked_fill is making stuff slower!# self. GA_mask = create_boolean_mask(n = n, sliding_window = 0)# self.SWA_mask = create_boolean_mask(n = n, sliding_window = self.config.sliding_window)- from transformers.modeling_attn_mask_utils import AttentionMaskConverter-self.SWA_mask = (AttentionMaskConverter(is_causal = True,diff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.pyindex 0d05a2d5384..173424d9f50 100644--- a/unsloth/models/qwen3.py+++ b/unsloth/models/qwen3.py@@ -47,7 +47,7 @@ except:f'Try `pip install --upgrade "transformers>=4.50.3"`\n'f"to obtain the latest transformers build, then restart this session.")-from transformers.modeling_attn_mask_utils import (+from unsloth.models._attn_mask_compat import (_prepare_4d_causal_attention_mask_for_sdpa,)diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 1482c2a6f8a..b309b3b2f0e 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -32,7 +32,7 @@ import torchfrom transformers.modeling_outputs import BaseModelOutputfrom collections import OrderedDictfrom transformers.models.distilbert import modeling_distilbert-from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa+from unsloth.models._attn_mask_compat import _prepare_4d_attention_mask_for_sdpaimport transformersfrom packaging.version import Versionimport re