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
Don't select Flash Attention 2 for float32 model loads (#9110)
Nilay409063a9e205
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex d454f90acb4..51e9ed9c0e6 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -433,6 +433,8 @@ class InferenceBackend:model, tokenizer = FastModel.from_pretrained(config.path,dtype = torch.float32,+ # Flash Attention cannot run float32+ attn_implementation = "sdpa",load_in_4bit = False,device_map = device_map,token = hf_token if hf_token and hf_token.strip() else None,@@ -505,6 +507,8 @@ class InferenceBackend:model, tokenizer = FastModel.from_pretrained(llm_path,dtype = torch.float32,+ # Flash Attention cannot run float32+ attn_implementation = "sdpa",load_in_4bit = False,device_map = device_map,token = hf_token if hf_token and hf_token.strip() else None,diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex b6131c2e38d..e1a7fecd4bd 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -1083,6 +1083,7 @@ class UnslothTrainer:model_name = llm_path,max_seq_length = max_seq_length,dtype = torch.float32, # Spark-TTS requires float32+ attn_implementation = "sdpa", # Flash Attention cannot run float32load_in_4bit = False,device_map = device_map,full_finetuning = full_finetuning,diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 918fc6a045f..768e8b2ebac 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -7,8 +7,8 @@ Some newer model architectures (Ministral-3, GLM-4.7-Flash, Qwen3-30B-A3B MoE,tiny_qwen3_moe) require transformers>=5.3.0, while Gemma 4 models require anewer 5.x sidecar. Dense NemotronH models (e.g. NVIDIA-Nemotron-3-Nano-4B) useMLP layers that only transformers>=5.10 can parse natively, so they go on the-5.10 sidecar too. Everything else needs the default 4.57.x that ships with-Unsloth.+5.10 sidecar too. Everything else runs on the ambient default that ships with+Unsloth (TRANSFORMERS_DEFAULT_VERSION).Two separate target directories are maintained:- .venv_t5_530/ — transformers 5.3.0 (Ministral-3, GLM, Qwen3 MoE, etc.)@@ -488,7 +488,9 @@ def activate_transformers_for_subprocess(model_name: str, hf_token: str | None =_pp = os.environ.get("PYTHONPATH", "")os.environ["PYTHONPATH"] = _VENV_T5_530_DIR + (os.pathsep + _pp if _pp else "")else:- logger.info("Using default transformers (4.57.x) for %s", model_name)+ logger.info(+ "Using default transformers (%s) for %s", TRANSFORMERS_DEFAULT_VERSION, model_name+ )def latest_tier_active_for(model_name: str, hf_token: str | None = None) -> bool:@@ -1432,7 +1434,7 @@ _TRUSTSTORE_VENDOR = """+ inline_gate_source()+ r"""target_dir, model_name = sys.argv[1], sys.argv[2]-if target_dir: # empty = probe the ambient (default 4.57.x) transformers, no sidecar prepend+if target_dir: # empty = probe the ambient (default-tier) transformers, no sidecar prependsys.path.insert(0, target_dir)try:from transformers import AutoConfig@@ -1469,7 +1471,7 @@ def _stderr_is_transient(err: str) -> bool:def _probe_tier_venvs():"""tier -> (target_dir, ensure_fn), a function so the later _ensure_* defs resolve. The- ``default`` entry (empty target_dir = ambient 4.57.x) is only probed with include_default."""+ ``default`` entry (empty target_dir = ambient default) is only probed with include_default."""return {"default": ("", lambda: True),"530": (_VENV_T5_530_DIR, _ensure_venv_t5_530_exists),@@ -1561,8 +1563,8 @@ def _probe_tier(- all tiers probed, none parse -> remote-code/custom model_type; keep *floor*.Known-5.x callers use ``floor='530'``; weak-signal callers (config saved by transformers- 5.x) use ``include_default=True, floor='default'`` so a model that still parses on 4.57.x- stays on the default. Cached per _probe_cache_key (process lifetime). No Hub sha is+ 5.x) use ``include_default=True, floor='default'`` so a model that still parses on the+ ambient default stays there. Cached per _probe_cache_key (process lifetime). No Hub sha isresolved: that would import huggingface_hub before the sidecar is on sys.path."""if os.environ.get("UNSLOTH_DISABLE_TIER_PROBE", "").lower() in ("1", "true", "yes", "on"):@@ -1698,14 +1700,14 @@ def get_transformers_tier(Returns ``"510"`` for models needing transformers 5.10.x (Gemma 4 Unified),``"550"`` for models needing transformers 5.5.0 (e.g. Gemma 4 or mlx-vlm processors),``"530"`` for models needing transformers 5.3.0 (e.g. Ministral-3, Qwen3 MoE),- or ``"default"`` for everything else (4.57.x).+ or ``"default"`` for everything else.Strong signals (architecture/model_type, name substrings) are fast paths. For local paths,``config.json`` is checked before name heuristics to avoid false-positives from directoryname fragments. When the only signal is the 5.x tokenizer class, the exact tier is resolvedby probing AutoConfig in each sidecar; a config saved by transformers 5.x with no fast-path- match is probed default-first, catching a new 5.x-only arch while 4.57.x-loadable models- stay on default.+ match is probed default-first, catching a new 5.x-only arch while models the ambient+ default can load stay on default.``probe=False`` skips the sidecar subprocesses (used by the cheap:func:`needs_transformers_5`); it still classifies via cheap signals (a 5.x-saved config@@ -1812,7 +1814,8 @@ def get_transformers_tier(if tier != "default":return tierlogger.info(- "Transformers tier default (4.57.x) selected for %s (local config.json no match)",+ "Transformers tier default (%s) selected for %s (local config.json no match)",+ TRANSFORMERS_DEFAULT_VERSION,model_name,)return "default"@@ -1892,7 +1895,11 @@ def get_transformers_tier(if tier != "default":return tier- logger.info("Transformers tier default (4.57.x) selected for %s (no match)", model_name)+ logger.info(+ "Transformers tier default (%s) selected for %s (no match)",+ TRANSFORMERS_DEFAULT_VERSION,+ model_name,+ )return "default"diff --git a/tests/test_attention_implementation.py b/tests/test_attention_implementation.pyindex 839d504b27d..4fff5f0eeea 100644--- a/tests/test_attention_implementation.py+++ b/tests/test_attention_implementation.py@@ -1,5 +1,6 @@from types import SimpleNamespace+import torchimport unsloth # noqa: F401from transformers.utils import import_utils@@ -12,6 +13,12 @@ class SupportsFlexAndSdpa:_supports_sdpa = True+class SupportsFlashAndSdpa:+ _supports_flash_attn_2 = True+ _supports_flex_attn = False+ _supports_sdpa = True++def _config(model_type, **kwargs):values = {"model_type": model_type, "attention_dropout": 0}values.update(kwargs)@@ -54,3 +61,160 @@ def test_gpt_oss_falls_back_to_eager_when_flex_unavailable(monkeypatch):assert impl == "eager"assert config._attn_implementation == "eager"+++def test_float32_downgrades_flash_to_sdpa(monkeypatch):+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ config = _config("qwen2")++ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ supports_sdpa = True,+ dtype = torch.float32,+ )++ assert impl == "sdpa"+ assert config._attn_implementation == "sdpa"+++def test_float32_downgrades_explicit_flash_request(monkeypatch):+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ config = _config("qwen2")++ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ requested_attn_implementation = "flash_attention_2",+ supports_sdpa = True,+ dtype = torch.float32,+ )++ assert impl == "sdpa"+++def test_half_dtypes_keep_flash(monkeypatch):+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ for dtype in (torch.float16, torch.bfloat16, None):+ config = _config("qwen2")++ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ supports_sdpa = True,+ dtype = dtype,+ )++ assert impl == "flash_attention_2"+++def test_float32_does_not_reroute_an_explicit_non_flash_request(monkeypatch):+ """A float32 load must only veto flash, not re-answer other requests.++ gemma3's SDPA is known-broken, so an explicit "sdpa" resolves to eager, but the flash+ fallback ladder prefers gemma3's flex_attention. Routing fp32 through the ladder would+ answer the same request differently for float32 than for bfloat16.+ """+ _set_flex_available(monkeypatch, True)+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)++ answers = {}+ for dtype in (torch.bfloat16, torch.float32):+ config = _config("gemma3")+ answers[dtype] = _utils.resolve_attention_implementation(+ SupportsFlexAndSdpa,+ config,+ requested_attn_implementation = "sdpa",+ supports_sdpa = False,+ dtype = dtype,+ )++ assert answers[torch.float32] == answers[torch.bfloat16] == "eager"+++def test_float32_still_downgrades_an_explicit_flash_request(monkeypatch):+ """The narrowing above must not let a flash request through on float32."""+ _set_flex_available(monkeypatch, True)+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ config = _config("qwen2")++ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ requested_attn_implementation = "flash_attention_2",+ supports_sdpa = True,+ dtype = torch.float32,+ )++ assert impl == "sdpa"+++def test_config_disable_reason_still_reroutes_a_non_flash_request(monkeypatch):+ """Only the float32 reason is narrowed - a config-driven one keeps its old behaviour."""+ _set_flex_available(monkeypatch, True)+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ config = _config("gemma3", head_dim = 512)++ impl = _utils.resolve_attention_implementation(+ SupportsFlexAndSdpa,+ config,+ requested_attn_implementation = "sdpa",+ supports_sdpa = False,+ dtype = torch.bfloat16,+ )++ assert impl == "flex_attention"+++def test_float32_does_not_let_a_config_seeded_eager_win(monkeypatch):+ """A checkpoint shipping `"attn_implementation": "eager"` must not drag fp32 to eager.++ With no flash-specific reason the config value never steered the choice, so float32 must+ leave the checkpoint on sdpa exactly as bfloat16 does.+ """+ _set_flex_available(monkeypatch, True)+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", False)++ answers = {}+ for dtype in (torch.bfloat16, torch.float32):+ config = _config("qwen2", _attn_implementation = "eager")+ answers[dtype] = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ supports_sdpa = True,+ dtype = dtype,+ )++ assert answers[torch.float32] == answers[torch.bfloat16] == "sdpa"+++def test_float32_with_flash_available_and_config_seeded_eager_lands_on_sdpa(monkeypatch):+ """Same shape, but flash was genuinely on the table - the fallback is sdpa, not eager."""+ _set_flex_available(monkeypatch, True)+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ config = _config("qwen2", _attn_implementation = "eager")++ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ supports_sdpa = True,+ dtype = torch.float32,+ )++ assert impl == "sdpa"+++def test_config_disable_reason_still_honors_a_config_seeded_eager(monkeypatch):+ """The narrowing is float32-only: a real flash exclusion keeps reading the config."""+ _set_flex_available(monkeypatch, True)+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", True)+ config = _config("qwen2", head_dim = 512, _attn_implementation = "eager")++ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ supports_sdpa = True,+ dtype = torch.bfloat16,+ )++ assert impl == "eager"diff --git a/tests/test_attn_dtype_custom_datatype.py b/tests/test_attn_dtype_custom_datatype.pynew file mode 100644index 00000000000..62c8a6526e2--- /dev/null+++ b/tests/test_attn_dtype_custom_datatype.py@@ -0,0 +1,138 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The dtype handed to `resolve_attention_implementation` is the *attention* dtype.++The resolver turns Flash Attention off for float32 because the kernels only accept fp16/bf16,+so it must be told the dtype the attention projections end up in, not the checkpoint load+dtype. Two loader paths load wide and narrow again afterwards:++ UNSLOTH_FORCE_FLOAT32 loads bfloat16 (loader.py sets dtype = torch.bfloat16) with a+ float16 bnb compute dtype.++ UNSLOTH_FORCE_CUSTOM_DTYPE csm, falcon_h1 and nemotron_h load float32 so the Mamba /+ Triton kernels keep ieee precision, then cast every projection to+ `correct_dtype` (float16) after the load. Attention never sees+ float32, so flash is usable and must not be turned off.++Falcon-H1 at dtype = torch.float16 takes that second path, and reporting the transient+float32 downgraded a working flash_attention_2 to sdpa.++This checks the selection expression itself rather than a whole model load: the statements+between `model_class = resolve_model_class(...)` and the resolver call are lifted out of+vision.py and evaluated against each combination.+"""++import ast+import sys+from pathlib import Path++import pytest+import torch++REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO_ROOT))++VISION = REPO_ROOT / "unsloth" / "models" / "vision.py"+SRC = VISION.read_text(encoding = "utf-8")+++def _attention_dtype_expression():+ """The statements building the resolver's `dtype`, plus that keyword's expression.++ Found structurally, so inserting code above it cannot retarget this at another call.+ """+ for node in ast.walk(ast.parse(SRC)):+ if not isinstance(node, ast.FunctionDef) or node.name != "from_pretrained":+ continue+ body = node.body+ for index, statement in enumerate(body):+ call = getattr(statement, "value", None)+ if not isinstance(call, ast.Call):+ continue+ if getattr(call.func, "id", None) != "resolve_attention_implementation":+ continue+ keyword = next((k for k in call.keywords if k.arg == "dtype"), None)+ if keyword is None:+ pytest.fail(+ "vision.py no longer passes dtype = to resolve_attention_implementation"+ )+ # Everything between `model_class = resolve_model_class(...)` and the call.+ for start in range(index - 1, -1, -1):+ previous = body[start]+ if (+ isinstance(previous, ast.Assign)+ and getattr(previous.targets[0], "id", None) == "model_class"+ ):+ return body[start + 1 : index], keyword.value+ pytest.fail("no model_class assignment ahead of the resolver call in vision.py")+ pytest.fail("could not find the resolve_attention_implementation call in vision.py")+++PREAMBLE, DTYPE_EXPR = _attention_dtype_expression()+++def _selected(dtype, do_forced_float32, correct_dtype):+ namespace = {+ "torch": torch,+ "dtype": dtype,+ "do_forced_float32": do_forced_float32,+ "correct_dtype": correct_dtype,+ "auto_config": None,+ "auto_model": None,+ "model_name": "",+ "resolve_model_class": lambda *args, **kwargs: None,+ }+ module = ast.Module(body = list(PREAMBLE), type_ignores = [])+ ast.fix_missing_locations(module)+ exec(compile(module, str(VISION), "exec"), namespace)+ expression = ast.Expression(body = DTYPE_EXPR)+ ast.fix_missing_locations(expression)+ return eval(compile(expression, str(VISION), "eval"), namespace)+++ "dtype, do_forced_float32, correct_dtype, expected",+ [+ # Plain loads: the load dtype is the attention dtype.+ (torch.float32, False, None, torch.float32),+ (torch.bfloat16, False, None, torch.bfloat16),+ (torch.float16, False, None, torch.float16),+ # UNSLOTH_FORCE_FLOAT32: loaded bfloat16 despite the name, so flash stays on.+ (torch.bfloat16, True, None, torch.bfloat16),+ (torch.float32, True, None, torch.bfloat16),+ # UNSLOTH_FORCE_CUSTOM_DTYPE: csm / falcon_h1 / nemotron_h load float32 and cast+ # the projections back to correct_dtype, so attention runs in float16.+ (torch.float32, False, torch.float16, torch.float16),+ ],+)+def test_attention_dtype_is_the_post_cast_dtype(dtype, do_forced_float32, correct_dtype, expected):+ assert _selected(dtype, do_forced_float32, correct_dtype) is expected+++def test_custom_datatype_load_does_not_disable_flash_attention():+ """The falcon_h1 / nemotron_h shape end to end through the resolver."""+ import unsloth # noqa: F401+ from unsloth.models import _utils++ class SupportsFlashAndSdpa:+ _supports_flash_attn_2 = True+ _supports_flex_attn = False+ _supports_sdpa = True++ from types import SimpleNamespace++ original = _utils.HAS_FLASH_ATTENTION+ _utils.HAS_FLASH_ATTENTION = True+ try:+ config = SimpleNamespace(model_type = "falcon_h1", attention_dropout = 0)+ impl = _utils.resolve_attention_implementation(+ SupportsFlashAndSdpa,+ config,+ supports_sdpa = True,+ dtype = _selected(torch.float32, False, torch.float16),+ )+ finally:+ _utils.HAS_FLASH_ATTENTION = original++ assert impl == "flash_attention_2"diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex fc2d6930194..ab1a2aef500 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -636,6 +636,7 @@ def _disable_flash_attention_if_needed(supports_flex_attention = False,would_use_flash_attention = False,disable_reason = None,+ honor_config_attn_implementation = True,):if disable_reason is None:disable_reason = _get_flash_attention_disable_reason(config)@@ -648,11 +649,14 @@ def _disable_flash_attention_if_needed(# defaults, so they must not be treated as a deliberate user choice.explicit_request = attn_implementation+ # Off for a float32 load: with no flash-specific reason the config never steered the+ # choice, so a config-seeded "eager" must not drag an fp32 load from sdpa down to eager.requested_attn_implementation = attn_implementation- if requested_attn_implementation is None:- requested_attn_implementation = _config_get(config, "_attn_implementation", None)- if requested_attn_implementation is None:- requested_attn_implementation = _config_get(config, "attn_implementation", None)+ if honor_config_attn_implementation:+ if requested_attn_implementation is None:+ requested_attn_implementation = _config_get(config, "_attn_implementation", None)+ if requested_attn_implementation is None:+ requested_attn_implementation = _config_get(config, "attn_implementation", None)if requested_attn_implementation == "eager":return _set_attn_impl(config, "eager")@@ -832,6 +836,7 @@ def resolve_attention_implementation(config,requested_attn_implementation = None,supports_sdpa = None,+ dtype = None,):model_type_name = _config_get(config, "model_type", "")model_type = model_type_name.lower()@@ -849,6 +854,10 @@ def resolve_attention_implementation()supports_flex_attention = _supports_flex_attention(model_class, config, model_type)disable_reason = _get_flash_attention_disable_reason(config)+ float32_is_only_disable_reason = disable_reason is None and dtype is torch.float32+ if float32_is_only_disable_reason:+ # FA2 kernels only accept fp16/bf16, and fp32 generate runs without autocast, so it raises.+ disable_reason = "the model loads in float32 which Flash Attention does not support"flash_attention_disabled = disable_reason is not Noneif model_class is None:@@ -869,8 +878,16 @@ def resolve_attention_implementation(config,supports_sdpa = supports_sdpa,supports_flex_attention = supports_flex_attention,- would_use_flash_attention = (HAS_FLASH_ATTENTION and supports_flash_attention),+ would_use_flash_attention = (+ HAS_FLASH_ATTENTION+ and supports_flash_attention+ # An explicit request is settled below and reports its own downgrade.+ and not (+ float32_is_only_disable_reason and requested_attn_implementation is not None+ )+ ),disable_reason = disable_reason,+ honor_config_attn_implementation = not float32_is_only_disable_reason,)elif supports_sdpa:attn_impl = _set_attn_impl(config, "sdpa")@@ -882,9 +899,17 @@ def resolve_attention_implementation(else:attn_impl = _set_attn_impl(config, "eager")+ # float32 only rules out flash, unlike config-driven reasons which say something about the+ # model itself. So an explicit non-flash request must skip the flash fallback ladder, which+ # answers differently: gemma3 + "sdpa" resolves to eager, but the ladder says flex_attention.+ reroute_request_through_flash_fallback = flash_attention_disabled and not (+ float32_is_only_disable_reason+ and not _is_flash_attention_requested(requested_attn_implementation)+ )+if requested_attn_implementation is None:final_attn_impl = attn_impl- elif flash_attention_disabled:+ elif reroute_request_through_flash_fallback:final_attn_impl = _disable_flash_attention_if_needed(config,requested_attn_implementation,diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 5d1dbfd079d..02c59f407f9 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -2478,7 +2478,9 @@ class FastLlamaModel:model_function = MODEL_FOR_CAUSAL_LM_MAPPING[model_config.__class__]IS_FALCON_H1 = model_config.model_type.startswith("falcon_h1")- preferred_attn_impl = resolve_attention_implementation(model_function, model_config)+ preferred_attn_impl = resolve_attention_implementation(+ model_function, model_config, dtype = dtype+ )# Prefetch the repo (killable child) so the weight load is a cache hit. Runs after the# AutoConfig/model-class check so an unsupported repo fails on its small config fetch.diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex d5e60a7d82c..8e121fea675 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -1122,11 +1122,20 @@ class FastBaseModel:revision = _revision,)model_class = resolve_model_class(auto_model, auto_config)+ # Check if using forced float32 - we load it in bfloat16, then cast to float16!+ torch_dtype = dtype+ if do_forced_float32:+ torch_dtype = torch.bfloat16+ # What attention actually runs in, not the checkpoint load dtype: the+ # UNSLOTH_FORCE_CUSTOM_DTYPE families (csm, falcon_h1, nemotron_h) load float32 to keep+ # Mamba precision, then cast projections back to correct_dtype (float16), so flash stays.+ attn_dtype = correct_dtype if correct_dtype is not None else torch_dtypeattn_impl = resolve_attention_implementation(model_class,auto_config,requested_attn_implementation = kwargs.get("attn_implementation", None),supports_sdpa = supports_sdpa,+ dtype = attn_dtype,)# Handle FP8 models: get_model_name has already redirected this to BF16 sibling if the model ships with@@ -1317,11 +1326,6 @@ class FastBaseModel:if user_quantization_config is None:kwargs["quantization_config"] = quantization_config- # Check if using forced float32 - we load it in bfloat16, then cast to float16!- torch_dtype = dtype- if do_forced_float32:- torch_dtype = torch.bfloat16-kwargs = add_dtype_kwargs(torch_dtype, kwargs)config_attn_impl = kwargs.get("attn_implementation", None)