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.

XPU: train an explicit bf16 load in bf16 under the fp16 idiom, and match vLLM's dtype when it refuses bf16 (#14606)

Daniel Hancdd0900c6128
diff --git a/tests/test_xpu_explicit_bf16_trainer_precision.py b/tests/test_xpu_explicit_bf16_trainer_precision.py
new file mode 100644
index 00000000000..eb5eae83275
--- /dev/null
+++ b/tests/test_xpu_explicit_bf16_trainer_precision.py
@@ -0,0 +1,48 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""An explicit bf16 load stays bf16 on an XPU without native bf16, so the notebook idiom
+`fp16 = not is_bfloat16_supported()` asks float16 for a bfloat16 model: follow the model."""
+
+import pytest
+import torch
+
+from tests.test_float32_no_fp16_autocast import _run
+
+
+def test_xpu_bf16_model_with_the_fp16_idiom_trains_in_bf16():
+ args, env = _run(torch.bfloat16, bf16_supported = False, fp16 = True, device_type = "xpu")
+ assert (args.fp16, args.bf16) == (False, True)
+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"
+
+
+def test_xpu_bf16_model_with_both_flags_trains_in_bf16():
+ args, env = _run(torch.bfloat16, bf16_supported = False, fp16 = True, bf16 = True, device_type = "xpu")
+ assert (args.fp16, args.bf16) == (False, True)
+ assert env["ACCELERATE_MIXED_PRECISION"] == "bf16"
+
+
[email protected]("device_type", ["cuda", "hip", "mps", None])
+def test_other_devices_still_refuse_fp16_on_a_bf16_model(device_type):
+ with pytest.raises(TypeError, match = "bfloat16 precision but you want to use float16"):
+ _run(torch.bfloat16, bf16_supported = False, fp16 = True, device_type = device_type)
+
+
+def test_native_bf16_xpu_still_refuses_an_explicit_fp16():
+ # With native bf16 the idiom asks bf16, so fp16 here is the caller's own conflicting choice.
+ with pytest.raises(TypeError, match = "bfloat16 precision but you want to use float16"):
+ _run(torch.bfloat16, bf16_supported = True, fp16 = True, device_type = "xpu")
+
+
+def test_xpu_fp16_model_with_the_fp16_idiom_unchanged():
+ args, env = _run(torch.float16, bf16_supported = False, fp16 = True, device_type = "xpu")
+ assert (args.fp16, args.bf16) == (True, False)
+ assert env["ACCELERATE_MIXED_PRECISION"] == "fp16"
+
+
+def test_xpu_forced_float32_still_wins():
+ args, env = _run(
+ torch.bfloat16, bf16_supported = False, fp16 = True, force_float32 = "1", device_type = "xpu"
+ )
+ assert (args.fp16, args.bf16) == (False, False)
+ assert env["ACCELERATE_MIXED_PRECISION"] == "no"
diff --git a/tests/test_xpu_vllm_refuses_bf16.py b/tests/test_xpu_vllm_refuses_bf16.py
new file mode 100644
index 00000000000..8ade129a0a2
--- /dev/null
+++ b/tests/test_xpu_vllm_refuses_bf16.py
@@ -0,0 +1,184 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""vLLM refuses bf16 on an Arc A770 (vllm/platforms/xpu.py check_if_supports_dtype). When vLLM will
+own the weights, the HF load takes fp16 as well, so the engine and the shared weights agree."""
+
+import ast
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+MODELS = Path(__file__).resolve().parents[1] / "unsloth" / "models"
+
+
+def _vllm_gate(name):
+ tree = ast.parse((MODELS / name).read_text(encoding = "utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.If) and "xpu_vllm_refuses_bf16()" in ast.unparse(node.test):
+ return compile(ast.Module(body = [node], type_ignores = []), name, "exec")
+ raise AssertionError(f"vLLM bf16 gate not found in {name}")
+
+
+def _resolve(
+ name,
+ device_type,
+ dtype,
+ fast_inference,
+ refuses,
+ vllm_available = True,
+ env = None,
+):
+ namespace = {
+ "torch": torch,
+ "dtype": dtype,
+ "DEVICE_TYPE": device_type,
+ "fast_inference": fast_inference,
+ "num_labels": None,
+ "_vllm_will_load_weights": lambda fi, nl: bool(fi) and nl is None and vllm_available,
+ "is_vLLM_available": lambda: vllm_available,
+ "xpu_vllm_refuses_bf16": lambda: refuses,
+ "logger": types.SimpleNamespace(warning_once = lambda *a, **k: None),
+ "os": types.SimpleNamespace(environ = dict(env or {})),
+ }
+ exec(_vllm_gate(name), namespace)
+ return namespace["dtype"]
+
+
[email protected]("name", ["llama.py", "vision.py"])
+def test_refused_bf16_becomes_fp16_only_for_a_vllm_load_on_xpu(name):
+ assert _resolve(name, "xpu", torch.bfloat16, True, refuses = True) is torch.float16
+ # vLLM accepts it, vLLM is not loading the weights, or not XPU: unchanged.
+ assert _resolve(name, "xpu", torch.bfloat16, True, refuses = False) is torch.bfloat16
+ assert _resolve(name, "xpu", torch.bfloat16, False, refuses = True) is torch.bfloat16
+ assert (
+ _resolve(name, "xpu", torch.bfloat16, True, refuses = True, vllm_available = False)
+ is torch.bfloat16
+ )
+ assert _resolve(name, "cuda", torch.bfloat16, True, refuses = True) is torch.bfloat16
+ assert _resolve(name, "xpu", torch.float16, True, refuses = True) is torch.float16
+ assert _resolve(name, "xpu", torch.float32, True, refuses = True) is torch.float32
+
+
+def test_a_stale_forced_float32_env_does_not_fail_a_language_model_load():
+ # FastLanguageModel never sets UNSLOTH_FORCE_FLOAT32; an earlier FastModel load (Gemma 3) can
+ # leave it at "1" in the process, which must not refuse a later Llama-path load.
+ assert (
+ _resolve(
+ "llama.py",
+ "xpu",
+ torch.bfloat16,
+ True,
+ refuses = True,
+ env = {"UNSLOTH_FORCE_FLOAT32": "1"},
+ )
+ is torch.float16
+ )
+
+
[email protected]("name", ["vision.py"])
+def test_a_forced_float32_model_refuses_to_load_in_fp16(name):
+ # Gemma 3/4, Qwen3.5: float16 gives NaN gradients, so a refused bf16 fails early instead.
+ with pytest.raises(RuntimeError, match = "fast_inference = False"):
+ _resolve(
+ name, "xpu", torch.bfloat16, True, refuses = True, env = {"UNSLOTH_FORCE_FLOAT32": "1"}
+ )
+ assert (
+ _resolve(
+ name, "xpu", torch.bfloat16, True, refuses = False, env = {"UNSLOTH_FORCE_FLOAT32": "1"}
+ )
+ is torch.bfloat16
+ )
+
+
+def test_helper_follows_the_zoo_check(monkeypatch):
+ from unsloth import device_type as dt
+
+ zoo = pytest.importorskip("unsloth_zoo.device_type")
+ monkeypatch.setattr(dt, "DEVICE_TYPE", "xpu")
+ monkeypatch.setattr(zoo, "_xpu_vllm_refuses_bf16", lambda: True, raising = False)
+ assert dt.xpu_vllm_refuses_bf16() is True
+ monkeypatch.setattr(zoo, "_xpu_vllm_refuses_bf16", lambda: False, raising = False)
+ assert dt.xpu_vllm_refuses_bf16() is False
+
+ def _boom():
+ raise RuntimeError("probe failed")
+
+ monkeypatch.setattr(zoo, "_xpu_vllm_refuses_bf16", _boom, raising = False)
+ assert dt.xpu_vllm_refuses_bf16() is False
+ # An older unsloth_zoo without the check refuses nothing.
+ monkeypatch.delattr(zoo, "_xpu_vllm_refuses_bf16", raising = False)
+ assert dt.xpu_vllm_refuses_bf16() is False
+ monkeypatch.setattr(zoo, "_xpu_vllm_refuses_bf16", lambda: True, raising = False)
+ monkeypatch.setattr(dt, "DEVICE_TYPE", "cuda")
+ assert dt.xpu_vllm_refuses_bf16() is False
+
+
+def _loader_family_gate():
+ """FastModel.from_pretrained's FORCE_FLOAT32 loop through the vLLM gate after it."""
+ tree = ast.parse((MODELS / "loader.py").read_text(encoding = "utf-8"))
+ for node in ast.walk(tree):
+ body = getattr(node, "body", None)
+ if not isinstance(body, list):
+ continue
+ for i, stmt in enumerate(body):
+ if isinstance(stmt, ast.For) and ast.unparse(stmt.iter) == "FORCE_FLOAT32":
+ for j in range(i + 1, len(body)):
+ if isinstance(body[j], ast.If) and "xpu_vllm_refuses_bf16()" in ast.unparse(
+ body[j].test
+ ):
+ module = ast.Module(body = body[i : j + 1], type_ignores = [])
+ return compile(module, "loader.py", "exec")
+ raise AssertionError("FORCE_FLOAT32 family gate not found in loader.py")
+
+
+def _load_family(
+ arch,
+ dtype,
+ supports_bf16,
+ refuses,
+ device_type = "xpu",
+ fast_inference = True,
+):
+ env = {}
+ namespace = {
+ "torch": torch,
+ "os": types.SimpleNamespace(environ = env),
+ "dtype": dtype,
+ "model_type_arch": arch,
+ "model_types_all": arch + ",",
+ "FORCE_FLOAT32": ["gemma3,", "qwen3_5"],
+ "SUPPORTS_BFLOAT16": supports_bf16,
+ "do_forced_float32": False,
+ "fast_inference": fast_inference,
+ "DEVICE_TYPE": device_type,
+ "is_vLLM_available": lambda: True,
+ "xpu_vllm_refuses_bf16": lambda: refuses,
+ }
+ exec(_loader_family_gate(), namespace)
+ return namespace["dtype"], env.get("UNSLOTH_FORCE_FLOAT32")
+
+
+ "dtype,supports_bf16",
+ [(torch.bfloat16, False), (torch.bfloat16, True), (None, True)],
+ ids = ["explicit-bf16-emulated", "explicit-bf16-native", "auto-native"],
+)
+def test_a_fp16_unsafe_family_refuses_vllm_fp16_when_bf16_is_not_forced(dtype, supports_bf16):
+ # These loads skip forced float32, so the FastBaseModel gate alone would drop Gemma 3 to fp16.
+ with pytest.raises(RuntimeError, match = "fast_inference = False"):
+ _load_family("gemma3", dtype, supports_bf16, refuses = True)
+ assert _load_family("gemma3", dtype, supports_bf16, refuses = False)[0] is dtype
+ assert _load_family("gemma3", dtype, supports_bf16, True, fast_inference = False)[0] is dtype
+ assert _load_family("gemma3", dtype, supports_bf16, True, device_type = "cuda")[0] is dtype
+ # Families that run in fp16 still switch quietly in FastBaseModel.
+ assert _load_family("llama", dtype, supports_bf16, refuses = True)[0] is dtype
+
+
+def test_forced_float32_family_is_left_to_the_fast_base_model_gate():
+ assert _load_family("gemma3", torch.float16, True, refuses = True) == (torch.bfloat16, "1")
+ assert _load_family("qwen3_5", None, False, refuses = True) == (torch.bfloat16, "1")
diff --git a/unsloth/device_type.py b/unsloth/device_type.py
index 6a60f96183d..7eb62fbdb80 100644
--- a/unsloth/device_type.py
+++ b/unsloth/device_type.py
@@ -339,6 +339,20 @@ def xpu_supports_native_bf16(device = None):
return not any(_xpu_device_lacks_native_bf16(index) for index in indices)
+def xpu_vllm_refuses_bf16():
+ """vLLM refuses bf16 on this XPU (Arc A770); an older unsloth_zoo without the check refuses nothing."""
+ if DEVICE_TYPE != "xpu":
+ return False
+ try:
+ from unsloth_zoo.device_type import _xpu_vllm_refuses_bf16
+ except Exception:
+ return False
+ try:
+ return bool(_xpu_vllm_refuses_bf16())
+ except Exception:
+ return False
+
+
def xpu_keeps_explicit_bf16():
"""An explicit bf16 request on XPU stays bf16 (emulated if need be) only beside an unsloth_zoo
that does the same for vLLM, so the engine and the HF weights it shares agree on one dtype."""
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 3fa400b9030..f7f872e6d60 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -120,6 +120,7 @@ except ImportError:
detect_logit_transforms = None
from ..device_type import (
xpu_keeps_explicit_bf16,
+ xpu_vllm_refuses_bf16,
is_hip,
get_device_type,
DEVICE_TYPE,
@@ -3607,6 +3608,18 @@ class FastLlamaModel:
elif dtype == torch.bfloat16 and not SUPPORTS_BFLOAT16 and not xpu_keeps_explicit_bf16():
logger.warning_once("Device does not support bfloat16. Will change to float16.")
dtype = torch.float16
+ if (
+ dtype == torch.bfloat16
+ and DEVICE_TYPE == "xpu"
+ and _vllm_will_load_weights(fast_inference, num_labels)
+ and xpu_vllm_refuses_bf16()
+ ):
+ # No forced-float32 check here: this path never sets UNSLOTH_FORCE_FLOAT32, so the env
+ # var only holds what an earlier FastModel load left behind.
+ logger.warning_once(
+ "Unsloth: vLLM does not accept bfloat16 on this Intel GPU. Will change to float16."
+ )
+ dtype = torch.float16
assert dtype == torch.float16 or dtype == torch.bfloat16 or dtype == torch.float32
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index fcd5554ae04..1901d5865ad 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -85,6 +85,7 @@ except:
import importlib.util
from ..device_type import (
xpu_keeps_explicit_bf16,
+ xpu_vllm_refuses_bf16,
is_hip,
get_device_type,
DEVICE_TYPE,
@@ -2983,6 +2984,24 @@ class FastModel(FastBaseModel):
do_forced_float32 = True
dtype = torch.bfloat16 # Change to bfloat16 loading
break
+ # A bf16 load of this family would otherwise drop to fp16 when vLLM refuses bf16 (forced float32 is caught in FastBaseModel).
+ if (
+ not do_forced_float32
+ and fast_inference
+ and DEVICE_TYPE == "xpu"
+ and (dtype == torch.bfloat16 or (dtype is None and SUPPORTS_BFLOAT16))
+ and any(
+ name.lower() == model_type_arch.lower().replace("-", "").replace("_", "")
+ or name.lower() in model_types_all
+ for name in FORCE_FLOAT32
+ )
+ and is_vLLM_available()
+ and xpu_vllm_refuses_bf16()
+ ):
+ raise RuntimeError(
+ "Unsloth: vLLM does not accept bfloat16 on this Intel GPU, and this model cannot "
+ "run in float16. Load it with fast_inference = False."
+ )
use_gradient_checkpointing = apply_unsloth_gradient_checkpointing(
use_gradient_checkpointing, max_seq_length, dtype
)
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 6eddc45e0b6..e3f893f655f 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -2681,6 +2681,13 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
"if full_finetuning:\n"
" if bfloat16 and use_fp16: use_fp16 = False\n"
" if float16 and use_bf16: use_bf16 = False\n"
+ # XPU keeps an explicit bf16 load in bf16 although the card has no native bf16, so `fp16 = not is_bfloat16_supported()` asks float16: follow the model.
+ "if not force_float32 and bfloat16 and use_fp16 and _unsloth_device_type == 'xpu' and not _bf16_supported():\n"
+ " print('Unsloth: The model was loaded in bfloat16 on purpose, so training uses bfloat16 mixed precision instead of float16.')\n"
+ " use_fp16 = False\n"
+ " use_bf16 = True\n"
+ " args.fp16 = False\n"
+ " args.bf16 = True\n"
"if not force_float32 and (float16 and use_bf16): raise TypeError('Unsloth: Model is in float16 precision but you want to use bfloat16 precision. Set fp16 to `True` and bf16 to `False`')\n"
"if not force_float32 and (bfloat16 and use_fp16): raise TypeError('Unsloth: Model is in bfloat16 precision but you want to use float16 precision. Set fp16 to `False` and bf16 to `True`')\n"
"if force_float32:\n"
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 9500b1a2d90..9bf558cc995 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -302,6 +302,7 @@ except:
from huggingface_hub.utils._token import get_token
from ..device_type import (
xpu_keeps_explicit_bf16,
+ xpu_vllm_refuses_bf16,
get_device_stats,
clean_gpu_cache,
is_hip,
@@ -3561,6 +3562,23 @@ class FastBaseModel:
elif dtype == torch.bfloat16 and not SUPPORTS_BFLOAT16 and not xpu_keeps_explicit_bf16():
logger.warning_once("Device does not support bfloat16. Will change to float16.")
dtype = torch.float16
+ if (
+ dtype == torch.bfloat16
+ and DEVICE_TYPE == "xpu"
+ and fast_inference
+ and is_vLLM_available()
+ and xpu_vllm_refuses_bf16()
+ ):
+ if os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1":
+ # This model needs bf16 or float32 (float16 gives NaN gradients): fail before loading.
+ raise RuntimeError(
+ "Unsloth: vLLM does not accept bfloat16 on this Intel GPU, and this model cannot "
+ "run in float16. Load it with fast_inference = False."
+ )
+ logger.warning_once(
+ "Unsloth: vLLM does not accept bfloat16 on this Intel GPU. Will change to float16."
+ )
+ dtype = torch.float16
assert dtype in (torch.float16, torch.bfloat16, torch.float32)
bnb_compute_dtype = dtype