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
XPU bf16: judge the XPU in use, not every visible one (#14769)
Daniel Hanaeeab363206a
diff --git a/tests/test_xpu_native_bf16.py b/tests/test_xpu_native_bf16.pyindex 51d6601cc99..e70cfb2065a 100644--- a/tests/test_xpu_native_bf16.py+++ b/tests/test_xpu_native_bf16.py@@ -1,8 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""XPU bf16 must be native on every visible XPU, each judged by its own aspects (torch's default-probe counts emulation)."""+"""XPU bf16 must be native on the XPU in use (the current device, as torch.xpu.is_bf16_supported()+asks), judged by its own aspects (torch's default probe counts emulation). An unused sibling that+emulates bf16 never narrows it."""import reimport types@@ -36,22 +37,29 @@ CASES = [pytest.param(["old"], 0, True, id = "1dev-old-torch"),pytest.param([None], 0, True, id = "1dev-unreadable"),pytest.param([NATIVE, NATIVE], 0, True, id = "2dev-native"),- pytest.param([NATIVE, EMULATED], 0, False, id = "2dev-mixed"),- pytest.param([EMULATED, NATIVE], 1, False, id = "2dev-mixed-rev"),+ pytest.param([NATIVE, EMULATED], 0, True, id = "2dev-mixed"),+ pytest.param([EMULATED, NATIVE], 1, True, id = "2dev-mixed-rev"),pytest.param([NATIVE, EMULATED], 1, False, id = "2dev-mixed-current-emulated"),pytest.param([EMULATED, NATIVE], 0, False, id = "2dev-mixed-rev-current-emulated"),pytest.param([EMULATED, EMULATED], 0, False, id = "2dev-emulated"),pytest.param([EMULATED, EMULATED], 1, False, id = "2dev-emulated-dev1"),pytest.param([NO_OCLOC, NO_OCLOC], 0, True, id = "2dev-no-libocloc"),- pytest.param([EMULATED, NO_OCLOC], 1, False, id = "2dev-emulated+no-libocloc"),+ pytest.param([EMULATED, NO_OCLOC], 1, True, id = "2dev-emulated+no-libocloc"),pytest.param([NATIVE, NO_OCLOC], 0, True, id = "2dev-native+no-libocloc"),pytest.param([NO_OCLOC, NATIVE], 1, True, id = "2dev-no-libocloc+native"),pytest.param(["old", "old"], 0, True, id = "2dev-old-torch"),- pytest.param(["old", EMULATED], 0, False, id = "2dev-old-attr+emulated"),+ pytest.param(["old", EMULATED], 0, True, id = "2dev-old-attr+emulated"),+ pytest.param(["old", EMULATED], 1, False, id = "2dev-old-attr+emulated-current"),pytest.param([None, NO_OCLOC], 0, True, id = "2dev-unreadable+no-libocloc"),][email protected](autouse = True)+def _single_process(monkeypatch):+ for name in ("LOCAL_WORLD_SIZE", "WORLD_SIZE", "LOCAL_RANK", "RANK"):+ monkeypatch.delenv(name, raising = False)++def _fake_torch(devices, current = 0):def get_device_properties(device = None):spec = devices[current if device is None else device]@@ -104,7 +112,7 @@ def _run(@pytest.mark.parametrize("devices,current,bf16", CASES)-def test_gpu_init_xpu_bf16_is_native_on_every_device(monkeypatch, devices, current, bf16):+def test_gpu_init_xpu_bf16_is_native_on_the_current_device(monkeypatch, devices, current, bf16):import unsloth._gpu_init as gpu_initfake = _fake_torch(devices, current)@@ -114,12 +122,118 @@ def test_gpu_init_xpu_bf16_is_native_on_every_device(monkeypatch, devices, curre@pytest.mark.parametrize("devices,current,bf16", CASES)-def test_model_utils_xpu_bf16_is_native_on_every_device(monkeypatch, devices, current, bf16):+def test_model_utils_xpu_bf16_is_native_on_the_current_device(monkeypatch, devices, current, bf16):import unsloth.models._utils as model_utilsnamespace = _run(MODEL_UTILS, model_utils, _fake_torch(devices, current), monkeypatch)assert namespace["SUPPORTS_BFLOAT16"] is bf16+ "device, bf16",+ [+ (0, True),+ (1, False),+ ("xpu:1", False),+ ("xpu", True),+ ([0, 1], False),+ ("cpu", True),+ ],+)+def test_xpu_bf16_judges_the_devices_a_model_uses(monkeypatch, device, bf16):+ import torch++ fake = _fake_torch([NATIVE, EMULATED], 0)+ fake.device = torch.device+ monkeypatch.setattr(dt, "torch", fake)+ assert dt.xpu_supports_native_bf16(device) is bf16+++# torchrun imports unsloth before prepare_device_map selects the rank's XPU, so every rank reads+# current device 0 at import: judge the launch's XPUs together instead, one answer for all ranks.+LAUNCH_CASES = [+ pytest.param([NATIVE, EMULATED], {"LOCAL_WORLD_SIZE": "2", "WORLD_SIZE": "2"}, False, id = "2ranks-mixed"),+ pytest.param([EMULATED, NATIVE], {"LOCAL_WORLD_SIZE": "2", "WORLD_SIZE": "2"}, False, id = "2ranks-mixed-rev"),+ pytest.param([NATIVE, NATIVE], {"LOCAL_WORLD_SIZE": "2", "WORLD_SIZE": "2"}, True, id = "2ranks-native"),+ pytest.param([NATIVE, EMULATED], {"LOCAL_WORLD_SIZE": "1", "WORLD_SIZE": "2"}, True, id = "1rank-per-node"),+ pytest.param([NATIVE, EMULATED], {"WORLD_SIZE": "2"}, False, id = "no-local-world-all-visible"),+ pytest.param([NATIVE], {"LOCAL_WORLD_SIZE": "2", "WORLD_SIZE": "2"}, True, id = "affinity-mask-one-visible"),+ pytest.param([NATIVE, EMULATED], {"LOCAL_WORLD_SIZE": "1", "WORLD_SIZE": "1"}, True, id = "single-process"),+ pytest.param([NATIVE, EMULATED], {"LOCAL_WORLD_SIZE": "x", "WORLD_SIZE": "y"}, True, id = "garbage-env"),+]++[email protected]("devices,env,bf16", LAUNCH_CASES)[email protected]("path_name", ["GPU_INIT", "MODEL_UTILS"])+def test_xpu_bf16_under_a_launch_judges_every_rank_xpu(monkeypatch, devices, env, bf16, path_name):+ import unsloth._gpu_init as gpu_init+ import unsloth.models._utils as model_utils++ for name, value in env.items():+ monkeypatch.setenv(name, value)+ module = gpu_init if path_name == "GPU_INIT" else model_utils+ namespace = _run(globals()[path_name], module, _fake_torch(devices, 0), monkeypatch)+ assert namespace["SUPPORTS_BFLOAT16"] is bf16++[email protected]("devices,env,_bf16", LAUNCH_CASES)+def test_launch_answer_matches_zoo(monkeypatch, devices, env, _bf16):+ zoo_dt = pytest.importorskip("unsloth_zoo.device_type")+ if not hasattr(zoo_dt, "_xpu_launch_indices"):+ pytest.skip("installed unsloth_zoo predates _xpu_launch_indices")+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ fake = _fake_torch(devices, 0)+ monkeypatch.setattr(dt, "torch", fake)+ monkeypatch.setattr(zoo_dt, "torch", fake)+ assert dt.xpu_supports_native_bf16() is zoo_dt._xpu_bf16_supported()+++ "devices, bf16_after_switch",+ [+ pytest.param([NATIVE, EMULATED], False, id = "native-then-emulated"),+ pytest.param([EMULATED, NATIVE], True, id = "emulated-then-native"),+ ],+)+def test_is_bfloat16_supported_follows_set_device_after_import(monkeypatch, devices, bf16_after_switch):+ # unsloth#14622 on XPU: import on XPU 0, then torch.xpu.set_device(1) before loading. The loader+ # asks is_bfloat16_supported(); it must answer for XPU 1, as the trainer's zoo probe does.+ import unsloth.models._utils as model_utils++ state = {"current": 0}+ fake = _fake_torch(devices, 0)+ fake.xpu.current_device = lambda: state["current"]+ monkeypatch.setattr(dt, "torch", fake)+ monkeypatch.setattr(model_utils, "DEVICE_TYPE", "xpu")+ monkeypatch.setattr(model_utils, "zoo_shares_xpu_bf16", lambda: True)+ monkeypatch.setattr(model_utils, "SUPPORTS_BFLOAT16", not bf16_after_switch) # cached at import+ assert model_utils.is_bfloat16_supported() is (not bf16_after_switch)+ state["current"] = 1+ assert model_utils.is_bfloat16_supported() is bf16_after_switch+++def test_is_bfloat16_supported_keeps_the_cached_answer_off_xpu(monkeypatch):+ import unsloth.models._utils as model_utils++ for answer in (True, False):+ monkeypatch.setattr(model_utils, "DEVICE_TYPE", "cuda")+ monkeypatch.setattr(model_utils, "SUPPORTS_BFLOAT16", answer)+ assert model_utils.is_bfloat16_supported() is answer+ monkeypatch.setattr(model_utils, "DEVICE_TYPE", "xpu")+ monkeypatch.setattr(model_utils, "zoo_shares_xpu_bf16", lambda: False) # older zoo: old answer+ assert model_utils.is_bfloat16_supported() is False+++def test_xpu_unreadable_current_device_keeps_true(monkeypatch):+ def boom():+ raise RuntimeError("no context")++ fake = _fake_torch([EMULATED], 0)+ fake.xpu.current_device = boom+ monkeypatch.setattr(dt, "torch", fake)+ assert dt.xpu_supports_native_bf16() is True++def test_xpu_unreadable_count_keeps_true(monkeypatch):def boom():raise RuntimeError("no driver")diff --git a/unsloth/device_type.py b/unsloth/device_type.pyindex 78603e14ed5..5aa2feb3471 100644--- a/unsloth/device_type.py+++ b/unsloth/device_type.py@@ -236,11 +236,60 @@ def cuda_order_mismatch_names():return names if len(names) > 1 else []-def xpu_supports_native_bf16():- """Process-wide like CUDA: any visible XPU proven to lack native bf16 turns it off, since the- load target is not known here. Each device is judged by its own aspects: without libocloc- (absent in torch-xpu wheels) every aspect reads False, so trust the probe only once some- aspect reads True on that device. Must match unsloth_zoo.device_type._xpu_bf16_supported."""+def _xpu_launch_indices():+ """Under torchrun / accelerate, the XPUs this node's ranks use (LOCAL_WORLD_SIZE of them, clipped+ to the visible count), else None. Unsloth is imported before a rank selects its XPU, so the+ current device then reads XPU 0 on every rank; judging the ranks' devices together keeps every+ rank on one dtype and is never narrower than the all-visible rule."""+ def _env_int(name):+ try:+ return int(os.environ.get(name, ""))+ except ValueError:+ return None+ local_world = _env_int("LOCAL_WORLD_SIZE")+ world = _env_int("WORLD_SIZE")+ if (local_world or 1) <= 1 and (world or 1) <= 1:+ return None+ try:+ count = int(torch.xpu.device_count())+ except Exception:+ return None+ if count <= 0:+ return None+ return list(range(min(local_world, count) if local_world and local_world > 0 else count))+++def _xpu_selected_indices(device = None):+ """XPU indices to judge: `device` (an index, "xpu:N", a torch.device or several of them), else+ the XPUs of a distributed launch (_xpu_launch_indices), else the current device, which+ torch.xpu.is_bf16_supported() also asks. None when unreadable."""+ items = device if isinstance(device, (list, tuple, set, frozenset)) else [device]+ indices = []+ for item in items:+ try:+ if item is None:+ launch = _xpu_launch_indices()+ if launch is not None:+ indices.extend(i for i in launch if i not in indices)+ continue+ index = torch.xpu.current_device()+ elif isinstance(item, int) and not isinstance(item, bool):+ index = item+ else:+ item = torch.device(item)+ if item.type != "xpu":+ continue+ index = torch.xpu.current_device() if item.index is None else item.index+ except Exception:+ return None+ if index not in indices:+ indices.append(int(index))+ return indices+++def _xpu_device_lacks_native_bf16(index):+ """True only when this device is proven to emulate bf16. Its own aspects decide whether the probe+ can be trusted: without libocloc (absent in torch-xpu wheels) every SYCL aspect reads False."""aspects = ("has_bfloat16_conversions","has_subgroup_matrix_multiply_accumulate",@@ -248,18 +297,22 @@ def xpu_supports_native_bf16():"has_subgroup_2d_block_io",)try:- count = torch.xpu.device_count()+ props = torch.xpu.get_device_properties(index)except Exception:+ return False+ lacks_bf16 = getattr(props, "has_bfloat16_conversions", True) is False+ return lacks_bf16 and any(getattr(props, name, False) is True for name in aspects)+++def xpu_supports_native_bf16(device = None):+ """Native bf16 on the XPU(s) in use: `device`, else the current XPU, the one+ torch.xpu.is_bf16_supported() asks. An unused sibling never narrows it, and emulated bf16 still+ runs on any XPU a split model reaches. Unknown means True.+ Must match unsloth_zoo.device_type._xpu_bf16_supported."""+ indices = _xpu_selected_indices(device)+ if indices is None:return True- for index in range(count):- try:- props = torch.xpu.get_device_properties(index)- except Exception:- continue- lacks_bf16 = getattr(props, "has_bfloat16_conversions", True) is False- if lacks_bf16 and any(getattr(props, name, False) is True for name in aspects):- return False- return True+ return not any(_xpu_device_lacks_native_bf16(index) for index in indices)def xpu_keeps_explicit_bf16():diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 5c34011f495..f0ab8b221cc 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -4892,6 +4892,10 @@ def config_return_dict(config):def is_bfloat16_supported():+ # XPU: ask again, so a torch.xpu.set_device after import is seen, as the trainer's live+ # unsloth_zoo probe sees it. Cheap (device properties only).+ if DEVICE_TYPE == "xpu" and zoo_shares_xpu_bf16():+ return xpu_supports_native_bf16()return SUPPORTS_BFLOAT16