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.

Mixed NVIDIA hosts: bf16 and compile follow the current device; check where the weights landed after loading (#14622)

Daniel Han8d5200de272e
diff --git a/tests/conftest.py b/tests/conftest.py
index b72402cd9b5..5565d47bc31 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -173,6 +173,12 @@ def _install_device_type_stub(name: str) -> None:
stub.hip_visible_archs = lambda: []
stub.cuda_visible_capabilities = lambda *a, **k: []
stub.cuda_gate_capabilities = lambda: []
+ stub.cuda_current_capability = lambda: None
+ stub.cuda_bf16_capability = lambda: None
+ stub.distributed_launch = lambda: False
+ stub.apply_pre_volta_compile_workaround = lambda *a, **k: False
+ stub.hip_current_arch = lambda: ""
+ stub.arch_breaks_compile = lambda arch: False
stub.cuda_order_mismatch_names = lambda: []
stub.xpu_supports_native_bf16 = lambda: True
stub.zoo_shares_xpu_bf16 = lambda: False
diff --git a/tests/test_mixed_nvidia_capabilities.py b/tests/test_mixed_nvidia_capabilities.py
index 491aff1f978..db92cc4a124 100644
--- a/tests/test_mixed_nvidia_capabilities.py
+++ b/tests/test_mixed_nvidia_capabilities.py
@@ -1,9 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""bf16 and the torch.compile kill switches are process-wide, so on a mixed host (e.g. RTX 3090 +
-T4 with device_map="auto") they must hold on the weakest visible card, not on device 0. The
-capability cache must also follow torch.cuda.set_device."""
+"""bf16 and the torch.compile kill switches answer for the current device, as torch does: an idle
+older card beside it (e.g. RTX 4090 + GTX 1080) must not take bf16 or compile from a model that runs
+on the 4090. A load that places layers on the older card is checked after loading. The capability
+cache must also follow torch.cuda.set_device."""
import functools
import inspect
@@ -28,12 +29,15 @@ if not hasattr(dt, "torch"):
SM80, SM86, SM75, SM90, SM61 = (8, 0), (8, 6), (7, 5), (9, 0), (6, 1)
+# (visible caps, current device): bf16 and the pre-Volta floor follow the current device only.
CASES = [
- pytest.param([SM80, SM80], True, None, id = "sm80x2"),
- pytest.param([SM86, SM75], False, None, id = "sm86+sm75"),
- pytest.param([SM75, SM86], False, None, id = "sm75+sm86"),
- pytest.param([SM90, SM61], False, 6, id = "sm90+sm61"),
- pytest.param([SM61], False, 6, id = "sm61"),
+ pytest.param([SM80, SM80], 0, id = "sm80x2"),
+ pytest.param([SM86, SM75], 0, id = "sm86+sm75"),
+ pytest.param([SM86, SM75], 1, id = "sm86+sm75@1"),
+ pytest.param([SM75, SM86], 0, id = "sm75+sm86"),
+ pytest.param([SM90, SM61], 0, id = "sm90+sm61"),
+ pytest.param([SM90, SM61], 1, id = "sm90+sm61@1"),
+ pytest.param([SM61], 0, id = "sm61"),
]
@@ -115,31 +119,57 @@ def _run_model_utils_chain(fake, monkeypatch):
return namespace
[email protected]("caps,bf16,_floor", CASES)
-def test_gpu_init_bf16_needs_every_visible_card(monkeypatch, caps, bf16, _floor):
[email protected]("caps,current", CASES)
+def test_gpu_init_bf16_follows_the_current_device(monkeypatch, capsys, caps, current):
fake = _fake_torch(caps)
+ fake.cuda.set_device(current)
namespace = _run_gpu_init_chain(fake, monkeypatch)
+ bf16 = caps[current][0] >= 8
assert namespace["SUPPORTS_BFLOAT16"] is bf16
assert bool(fake.cuda.is_bf16_supported(False)) is bf16
- assert bool(fake.cuda.is_bf16_supported()) is bf16
# Emulation is torch's own per-device answer and stays untouched.
assert fake.cuda.is_bf16_supported(including_emulation = True) is True
+ # An idle older card is no reason to print anything at import.
+ assert "bfloat16" not in capsys.readouterr().out
[email protected]("caps,bf16,_floor", CASES)
-def test_mixed_host_says_why_bf16_is_off(monkeypatch, capsys, caps, bf16, _floor):
- _run_gpu_init_chain(_fake_torch(caps), monkeypatch)
- out = capsys.readouterr().out
- mixed = any(c[0] >= 8 for c in caps) and any(c[0] < 8 for c in caps)
- assert ("lack bfloat16" in out) is mixed
- if mixed:
- assert str([i for i, c in enumerate(caps) if c[0] < 8]) in out
[email protected]("caps,current", CASES)
+def test_model_utils_bf16_follows_the_current_device(monkeypatch, caps, current):
+ fake = _fake_torch(caps)
+ fake.cuda.set_device(current)
+ namespace = _run_model_utils_chain(fake, monkeypatch)
+ assert namespace["SUPPORTS_BFLOAT16"] is (caps[current][0] >= 8)
[email protected]("caps,bf16,_floor", CASES)
-def test_model_utils_bf16_needs_every_visible_card(monkeypatch, caps, bf16, _floor):
- namespace = _run_model_utils_chain(_fake_torch(caps), monkeypatch)
- assert namespace["SUPPORTS_BFLOAT16"] is bf16
[email protected]("chain", ["gpu_init", "model_utils"])
[email protected]("world_size,bf16", [("2", False), ("1", True), ("", True)])
+def test_a_distributed_launch_keeps_the_weakest_card_for_bf16(monkeypatch, chain, world_size, bf16):
+ # DDP ranks import before set_device and must agree on one dtype: the weakest visible card decides.
+ monkeypatch.setenv("WORLD_SIZE", world_size)
+ fake = _fake_torch([SM86, SM75])
+ run = _run_gpu_init_chain if chain == "gpu_init" else _run_model_utils_chain
+ assert run(fake, monkeypatch)["SUPPORTS_BFLOAT16"] is bf16
+
+
[email protected]("current", [0, 1])
+def test_a_distributed_launch_keeps_the_public_bf16_probe_on_the_weakest_card(monkeypatch, current):
+ # save.py reads torch.cuda.is_bf16_supported() for merged 16-bit saves: every rank must agree.
+ monkeypatch.setenv("WORLD_SIZE", "2")
+ fake = _fake_torch([SM90, SM75])
+ fake.cuda.set_device(current)
+ namespace = _run_gpu_init_chain(fake, monkeypatch)
+ assert namespace["SUPPORTS_BFLOAT16"] is False
+ assert fake.cuda.is_bf16_supported(False) is False
+ fake.cuda.set_device(1 - current)
+ assert fake.cuda.is_bf16_supported(False) is False
+ assert fake.cuda.is_bf16_supported(including_emulation = True) is True
+
+ monkeypatch.setenv("WORLD_SIZE", "1")
+ fake = _fake_torch([SM90, SM75])
+ _run_gpu_init_chain(fake, monkeypatch)
+ assert fake.cuda.is_bf16_supported(False) is True
+ fake.cuda.set_device(1)
+ assert fake.cuda.is_bf16_supported(False) is False
def test_capability_cache_follows_set_device(monkeypatch):
@@ -177,7 +207,7 @@ def test_capability_cache_resolves_device_spellings(monkeypatch):
assert cached(torch.device("cuda", 1)) == SM75
assert cached() == SM86
assert cached("cuda") == SM86
- assert calls == [1, 0] # one real probe per index
+ assert calls == [0, 1] # one real probe per card, read once while wrapping
with pytest.raises(KeyError):
cached("cpu") # not a CUDA device: passed through uncached, as torch would reject it
assert model_utils._cache_device_capability(cached) is cached # re-import does not stack
@@ -201,6 +231,15 @@ def test_capability_cache_single_device_keeps_the_plain_cache(monkeypatch):
assert model_utils._cache_device_capability(cached) is cached
+def test_capability_cache_identical_cards_keep_the_plain_cache(monkeypatch):
+ import unsloth.models._utils as model_utils
+
+ monkeypatch.setattr(model_utils, "torch", _fake_torch([SM90, SM90, SM90]))
+ cached = model_utils._cache_device_capability(lambda device = None: SM90)
+ assert hasattr(cached, "cache_info") # every spelling of every card gets one answer
+ assert cached() == cached(2) == SM90
+
+
def _run_pre_volta(fake, monkeypatch, capsys):
applied = []
@@ -218,11 +257,13 @@ def _run_pre_volta(fake, monkeypatch, capsys):
return applied, capsys.readouterr().out
[email protected]("caps,_bf16,floor", CASES)
-def test_pre_volta_switch_reads_the_weakest_visible_card(monkeypatch, capsys, caps, _bf16, floor):
- applied, out = _run_pre_volta(_fake_torch(caps), monkeypatch, capsys)
- assert applied == [min(c[0] for c in caps)]
- if floor is None:
[email protected]("caps,current", CASES)
+def test_pre_volta_switch_reads_the_current_device(monkeypatch, capsys, caps, current):
+ fake = _fake_torch(caps)
+ fake.cuda.set_device(current)
+ applied, out = _run_pre_volta(fake, monkeypatch, capsys)
+ assert applied == [caps[current][0]]
+ if caps[current][0] >= 7:
assert out == ""
else:
assert out == (
@@ -231,6 +272,17 @@ def test_pre_volta_switch_reads_the_weakest_visible_card(monkeypatch, capsys, ca
)
[email protected]("world_size,major", [("2", 6), ("1", 9)])
+def test_a_distributed_launch_keeps_the_weakest_card_for_the_compile_switch(
+ monkeypatch, capsys, world_size, major
+):
+ # A rank may be placed on the GTX 1080 after import: keep the weakest card, as for bf16.
+ monkeypatch.setenv("WORLD_SIZE", world_size)
+ fake = _fake_torch([SM90, SM61])
+ applied, _ = _run_pre_volta(fake, monkeypatch, capsys)
+ assert applied == [major]
+
+
def test_pre_volta_switch_skips_an_unreadable_card(monkeypatch, capsys):
fake = _fake_torch([SM61, SM90])
real = fake.cuda.get_device_capability
@@ -249,12 +301,13 @@ def test_pre_volta_switch_skips_an_unreadable_card(monkeypatch, capsys):
"archs,applied",
[
(["gfx906:sramecc+:xnack-"], True),
- (["gfx1100", "gfx906:sramecc+:xnack-"], True),
+ # An idle gfx906 beside the current card is checked after loading, not here.
+ (["gfx1100", "gfx906:sramecc+:xnack-"], False),
(["gfx906", "gfx1100"], True),
(["gfx90a", "gfx942"], False),
],
)
-def test_gfx906_switch_reads_every_visible_card(monkeypatch, capsys, archs, applied):
+def test_gfx906_switch_reads_the_current_device(monkeypatch, capsys, archs, applied):
fake = _fake_torch([SM90] * len(archs), archs = archs)
environ = {}
dynamo_config = types.SimpleNamespace(disable = False)
@@ -341,14 +394,13 @@ def test_grpo_tma_options_need_every_visible_card(caps, unreadable, expected):
@pytest.mark.parametrize(
"caps,current,bf16",
[
- ([(9, 0), (9, 0), (7, 5)], 0, False), # a known old card still counts
+ ([(9, 0), (9, 0), (7, 5)], 0, True),
([(9, 0), (9, 0), (7, 5)], 2, False),
- ([(9, 0), (9, 0), (9, 0)], 0, True), # current device is sm90, as on main
+ ([(9, 0), (9, 0), (9, 0)], 0, True),
],
)
-def test_a_partial_scan_judges_every_card_it_read(monkeypatch, capsys, caps, current, bf16):
- # Card 1 unreadable: the gate judges the readable cards, which include the current device,
- # so it is never less strict than main's current-device rule.
+def test_an_unreadable_card_does_not_matter(monkeypatch, capsys, caps, current, bf16):
+ # Card 1 unreadable: only the current device is read.
fake = _fake_torch(caps)
real_cap = fake.cuda.get_device_capability
@@ -359,34 +411,505 @@ def test_a_partial_scan_judges_every_card_it_read(monkeypatch, capsys, caps, cur
fake.cuda.get_device_capability = get_device_capability
fake.cuda.set_device(current)
- namespace = _run_gpu_init_chain(fake, monkeypatch)
- assert namespace["SUPPORTS_BFLOAT16"] is bf16
- out = capsys.readouterr().out
- assert ("[2]" in out) is (not bf16) and "[1]" not in out
+ assert _run_gpu_init_chain(fake, monkeypatch)["SUPPORTS_BFLOAT16"] is bf16
assert _run_model_utils_chain(fake, monkeypatch)["SUPPORTS_BFLOAT16"] is bf16
-def test_bf16_notice_names_real_device_indices(monkeypatch, capsys):
- # Device 2 is the pre-Ampere card while device 0 is current: the notice names 2.
- _run_gpu_init_chain(_fake_torch([(9, 0), (8, 6), (7, 5)]), monkeypatch)
[email protected]("world_size,applied", [("2", True), ("1", False)])
+def test_a_distributed_launch_keeps_every_card_for_the_gfx906_switch(
+ monkeypatch, capsys, world_size, applied
+):
+ monkeypatch.setenv("WORLD_SIZE", world_size)
+ archs = ["gfx1100", "gfx906:sramecc+:xnack-"]
+ fake = _fake_torch([SM90] * len(archs), archs = archs)
+ environ = {}
+ dynamo_config = types.SimpleNamespace(disable = False)
+ body = _block(
+ DEVICE_TYPE_PY,
+ "# gfx906 (MI50",
+ '\n\nif DEVICE_TYPE == "cuda" and torch.cuda.is_available():',
+ )
+ namespace = _module_namespace(
+ dt,
+ fake,
+ monkeypatch,
+ DEVICE_TYPE = "hip",
+ os = types.SimpleNamespace(environ = environ),
+ apply_pre_volta_compile_workaround = lambda major: dt.apply_pre_volta_compile_workaround(
+ major, environ = environ, dynamo_config = dynamo_config
+ ),
+ )
+ exec(compile(body, str(DEVICE_TYPE_PY), "exec"), namespace)
+ capsys.readouterr()
+ assert dynamo_config.disable is applied
+
+
+class _Placed:
+ def __init__(self, device_map):
+ self.hf_device_map = device_map
+
+
+def _check_placement(
+ monkeypatch,
+ caps,
+ device_map,
+ dtype,
+ current = 0,
+ model = None,
+ at_train_start = False,
+):
+ import torch
+
+ import unsloth.models._utils as model_utils
+
+ fake = _fake_torch(caps)
+ fake.cuda.set_device(current)
+ fake.cuda.get_device_name = lambda i: f"card{i}"
+ fake.device = torch.device
+ fake.bfloat16, fake.float16 = torch.bfloat16, torch.float16
+ disabled = []
+ monkeypatch.setattr(model_utils, "torch", fake)
+ monkeypatch.setattr(model_utils, "DEVICE_TYPE", "cuda")
+ monkeypatch.setattr(model_utils, "DEVICE_COUNT", len(caps))
+ monkeypatch.setattr(
+ model_utils,
+ "apply_pre_volta_compile_workaround",
+ lambda major: disabled.append(major) or True,
+ )
+ model = _Placed(device_map) if model is None else model
+ if at_train_start:
+ # The once-per-train() hook every Unsloth trainer path runs (plain Trainer loop, SFT, RL).
+ model_utils._unsloth_reset_stray_compile_cache(types.SimpleNamespace(model = model))
+ else:
+ model_utils.check_mixed_gpu_placement(model, dtype)
+ return disabled
+
+
+def test_layers_on_a_pre_volta_card_turn_compile_off(monkeypatch, capsys):
+ import torch
+
+ disabled = _check_placement(
+ monkeypatch, [SM90, SM61], {"model.layers.0": 0, "model.layers.1": 1}, torch.float16
+ )
out = capsys.readouterr().out
- assert "[2]" in out and "[0]" not in out and "[1]" not in out
+ assert disabled == [0]
+ assert "GPU 1 (card1)" in out and "torch.compile" in out
+
+
+def test_bf16_layers_on_a_card_without_bf16_warn(monkeypatch, capsys):
+ import torch
+
+ disabled = _check_placement(
+ monkeypatch, [SM86, SM75], {"model.layers.0": 0, "lm_head": 1}, torch.bfloat16
+ )
+ out = capsys.readouterr().out
+ assert disabled == []
+ assert "bfloat16 layers on GPU 1 (card1)" in out
+
+
+ "caps,device_map",
+ [
+ ([SM86, SM61], {"": 0}), # everything on the current card: nothing to check
+ ([SM90, SM90], {"model.layers.0": 0, "model.layers.1": 1}), # identical cards
+ ([SM86, SM75], {"model": "cpu", "lm_head": 0}),
+ ],
+)
+def test_placement_on_capable_cards_changes_nothing(monkeypatch, capsys, caps, device_map):
+ import torch
+ assert _check_placement(monkeypatch, caps, device_map, torch.bfloat16) == []
+ assert capsys.readouterr().out == ""
[email protected](not __import__("torch").cuda.is_available(), reason = "needs a CUDA device")
[email protected]("spelling", [None, 0, "cuda:0", "device", "tensor"])
-def test_capability_cache_traces_in_fullgraph(spelling):
- # Attention helpers call get_device_capability(Q.device) inside compiled regions.
+def test_set_device_to_a_pre_volta_card_turns_compile_off(monkeypatch, capsys):
+ # Imported on the H100, then torch.cuda.set_device(1) and the whole model loads on the GTX 1080.
+ import torch
+
+ disabled = _check_placement(monkeypatch, [SM90, SM61], {"": 1}, torch.float16, current = 1)
+ out = capsys.readouterr().out
+ assert disabled == [0]
+ assert "GPU 1 (card1)" in out and "torch.compile" in out
+
+
+def test_bf16_load_on_a_current_card_without_bf16_warns(monkeypatch, capsys):
+ # SUPPORTS_BFLOAT16 stays the import-time answer; the post-load check covers a set_device later.
+ import torch
+
+ disabled = _check_placement(monkeypatch, [SM86, SM75], {"": 1}, torch.bfloat16, current = 1)
+ out = capsys.readouterr().out
+ assert disabled == []
+ assert "bfloat16 layers on GPU 1 (card1)" in out
+
+
+def test_one_gpu_hosts_never_walk_the_placement(monkeypatch, capsys):
import torch
import unsloth.models._utils as model_utils
- cached = model_utils._cache_device_capability(inspect.unwrap(torch.cuda.get_device_capability))
+ class _Untouchable:
+ @property
+ def hf_device_map(self):
+ raise AssertionError("one-GPU hosts must not walk the placement")
+
+ fake = _fake_torch([SM61])
+ monkeypatch.setattr(model_utils, "torch", fake)
+ monkeypatch.setattr(model_utils, "DEVICE_TYPE", "cuda")
+ monkeypatch.setattr(model_utils, "DEVICE_COUNT", 1)
+ monkeypatch.setattr(
+ model_utils,
+ "apply_pre_volta_compile_workaround",
+ lambda major: pytest.fail("one-GPU hosts keep the import-time switch"),
+ )
+ model_utils.check_mixed_gpu_placement(_Untouchable(), torch.bfloat16)
+ assert capsys.readouterr().out == ""
+
+
+def test_diffusion_loader_checks_the_placement():
+ import ast
+
+ tree = ast.parse(
+ (REPO_ROOT / "unsloth" / "models" / "diffusion.py").read_text(encoding = "utf-8")
+ )
+ calls = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "check_mixed_gpu_placement"
+ ]
+ assert calls, "FastDiffusionModel.from_pretrained must check where device_map put the weights"
+ assert [ast.unparse(a) for a in calls[0].args] == ["model", "dtype"]
+
+
+def test_both_llama_load_branches_check_the_placement():
+ """num_labels loads go through AutoModelForSequenceClassification; they must check device_map too."""
+ import ast
+
+ tree = ast.parse((REPO_ROOT / "unsloth" / "models" / "llama.py").read_text(encoding = "utf-8"))
+
+ def checks(nodes):
+ return any(
+ isinstance(n, ast.Call) and getattr(n.func, "id", None) == "check_mixed_gpu_placement"
+ for stmt in nodes
+ for n in ast.walk(stmt)
+ )
+
+ branches = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.If)
+ and ast.unparse(n.test) == "num_labels is not None"
+ and any(
+ "AutoModelForSequenceClassification.from_pretrained" in ast.unparse(s) for s in n.body
+ )
+ ]
+ assert branches, "sequence-classification load branch not found"
+ for branch in branches:
+ assert checks(
+ branch.body
+ ), "the num_labels branch must check where device_map put the weights"
+ assert branch.orelse and checks(
+ branch.orelse
+ ), "the causal LM branch must check the placement"
+
+
+def test_sentence_transformer_direct_loads_check_the_placement():
+ """FastSentenceTransformer's direct SentenceTransformer(model_name, ...) loads (incl. the compiled
+ fast encoder path) bypass the other loaders, so each must check where the weights landed."""
+ import ast
+
+ tree = ast.parse(
+ (REPO_ROOT / "unsloth" / "models" / "sentence_transformer.py").read_text(encoding = "utf-8")
+ )
+ found = 0
+ for block in ast.walk(tree):
+ body = getattr(block, "body", None)
+ if not isinstance(body, list):
+ continue
+ for i, stmt in enumerate(body):
+ if not (
+ isinstance(stmt, ast.Assign)
+ and isinstance(stmt.value, ast.Call)
+ and getattr(stmt.value.func, "id", None) == "SentenceTransformer"
+ and stmt.value.args
+ and getattr(stmt.value.args[0], "id", None) == "model_name"
+ ):
+ continue
+ found += 1
+ assert any(
+ isinstance(n, ast.Call)
+ and getattr(n.func, "id", None) == "check_mixed_gpu_placement"
+ for later in body[i + 1 :]
+ for n in ast.walk(later)
+ ), f"SentenceTransformer load at line {stmt.lineno} must check the placement"
+ assert found >= 2
+
+
+class _ParamsOn:
+ """A model with no hf_device_map (an extracted text core) whose parameters sit on these devices."""
+
+ def __init__(
+ self,
+ *devices,
+ dtype = None,
+ ):
+ import torch
+ dtype = torch.float16 if dtype is None else dtype
+ self._params = [types.SimpleNamespace(device = torch.device(d), dtype = dtype) for d in devices]
+
+ def parameters(self):
+ return iter(self._params)
+
+
+def test_a_core_without_a_device_map_is_checked_on_every_card_it_spans(monkeypatch, capsys):
+ import torch
- def f(x):
- arg = {"device": torch.device("cuda"), "tensor": x.device}.get(spelling, spelling)
- return x * (cached() if arg is None else cached(arg))[0]
+ model = _ParamsOn("cuda:0", "cuda:0", "cuda:1", "cpu")
+ disabled = _check_placement(monkeypatch, [SM90, SM61], None, torch.float16, model = model)
+ assert disabled == [0]
+ assert "GPU 1 (card1)" in capsys.readouterr().out
- torch._dynamo.reset()
- x = torch.ones(2, device = "cuda")
- assert torch.compile(f, fullgraph = True)(x)[0].item() == torch.cuda.get_device_capability(0)[0]
+
+def test_a_core_on_capable_cards_only_changes_nothing(monkeypatch, capsys):
+ import torch
+
+ # The discarded sibling's card (GPU 1) is no longer among the retained parameters.
+ model = _ParamsOn("cuda:0", "cuda:0")
+ assert _check_placement(monkeypatch, [SM90, SM61], None, torch.bfloat16, model = model) == []
+ assert capsys.readouterr().out == ""
+
+
+def test_text_only_composite_loads_check_the_retained_core():
+ """The placement check runs after _text_trainable_core drops the vision / audio siblings."""
+ import ast
+
+ tree = ast.parse((REPO_ROOT / "unsloth" / "models" / "vision.py").read_text(encoding = "utf-8"))
+ checked = 0
+ for block in ast.walk(tree):
+ body = getattr(block, "body", None)
+ if not isinstance(body, list):
+ continue
+ calls = [
+ (i, getattr(n.func, "id", None))
+ for i, stmt in enumerate(body)
+ for n in ast.walk(stmt)
+ if isinstance(n, ast.Call)
+ and getattr(n.func, "id", None) in ("_text_trainable_core", "check_mixed_gpu_placement")
+ ]
+ core = [i for i, name in calls if name == "_text_trainable_core"]
+ check = [i for i, name in calls if name == "check_mixed_gpu_placement"]
+ # Outer blocks hold both inside one statement; the block that lists them as siblings decides.
+ if core and check and min(core) != min(check):
+ checked += 1
+ assert min(check) > min(
+ core
+ ), "check the placement of the retained core, not the composite"
+ assert checked
+
+
+class _MovedAfterLoad(_ParamsOn):
+ """Loaded with device_map = {"": 0} on the H100, then moved with .to("cuda:1"): the stale
+ hf_device_map still names GPU 0."""
+
+ hf_device_map = {"": 0}
+
+
[email protected]("model_cls", [_ParamsOn, _MovedAfterLoad], ids = ["cpu_load", "to_after"])
+def test_a_model_moved_onto_a_pre_volta_card_after_loading_is_checked_at_train_start(
+ monkeypatch, capsys, model_cls
+):
+ import torch
+
+ model = model_cls("cuda:1", "cuda:1")
+ disabled = _check_placement(
+ monkeypatch, [SM90, SM61], None, torch.float16, model = model, at_train_start = True
+ )
+ assert disabled == [0]
+ assert "GPU 1 (card1)" in capsys.readouterr().out
+
+
+def test_train_start_on_capable_cards_changes_nothing(monkeypatch, capsys):
+ import torch
+
+ model = _MovedAfterLoad("cuda:0", "cpu")
+ disabled = _check_placement(
+ monkeypatch, [SM90, SM61], None, torch.float16, model = model, at_train_start = True
+ )
+ assert disabled == []
+ assert capsys.readouterr().out == ""
+
+
+def test_bf16_weights_placed_on_a_card_without_bf16_warn_at_train_start(monkeypatch, capsys):
+ # Loaded in bf16 on CPU, then the Trainer put it on the T4: the live check infers the dtype.
+ import torch
+
+ model = _ParamsOn("cuda:1", "cuda:1", dtype = torch.bfloat16)
+ disabled = _check_placement(
+ monkeypatch, [SM86, SM75], None, None, model = model, at_train_start = True
+ )
+ assert disabled == []
+ assert "bfloat16 layers on GPU 1 (card1)" in capsys.readouterr().out
+
+
+def test_bf16_weights_only_on_the_bf16_card_do_not_warn_at_train_start(monkeypatch, capsys):
+ import torch
+
+ model = _ParamsOn("cuda:0", dtype = torch.bfloat16)
+ model._params += _ParamsOn("cuda:1", dtype = torch.float16)._params
+ disabled = _check_placement(
+ monkeypatch, [SM86, SM75], None, None, model = model, at_train_start = True
+ )
+ assert disabled == []
+ assert capsys.readouterr().out == ""
+
+
+class _PlacedByTrainer(_ParamsOn):
+ """A FastSentenceTransformer loaded with device_map = "cpu" whose LoRA compile is pending."""
+
+ _compile_pending = True
+ _compile_mode = "default"
+
+ def place(self, device):
+ import torch
+ for p in self._params:
+ p.device = torch.device(device)
+
+
[email protected]("moved", ["trainer_init", "before_train"])
+def test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile(
+ monkeypatch, capsys, moved
+):
+ import sys
+
+ import unsloth.models.sentence_transformer as st
+
+ model = _PlacedByTrainer("cpu", "cpu")
+ # Load time: everything on CPU, so nothing to check yet.
+ disabled = _check_placement(monkeypatch, [SM90, SM61], None, None, model = model)
+ assert disabled == []
+ model.place("cuda:0") # loaded on CPU, the user picks the GTX 1080 via the current device
+ compiled = []
+
+ class SentenceTransformerTrainer:
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ ):
+ self.model = model
+ if moved == "trainer_init":
+ model.place("cuda:1") # Trainer moves the model to args.device
+
+ def train(self):
+ return list(disabled)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "sentence_transformers",
+ types.SimpleNamespace(SentenceTransformerTrainer = SentenceTransformerTrainer),
+ )
+ monkeypatch.setattr(
+ st.FastSentenceTransformer, "_estimate_compile_threshold", staticmethod(lambda *a, **k: 1)
+ )
+ monkeypatch.setattr(
+ st.FastSentenceTransformer,
+ "_apply_torch_compile",
+ staticmethod(lambda m, mode = "default": compiled.append(mode)),
+ )
+ st._patch_sentence_transformer_trainer()
+ trainer = SentenceTransformerTrainer(
+ model = model, args = types.SimpleNamespace(max_steps = 100, fp16 = False, bf16 = False)
+ )
+ assert compiled == ["default"]
+ if moved == "before_train":
+ model.place("cuda:1")
+ # The stubbed switch leaves Dynamo on, so the train() re-check may fire again after __init__'s.
+ assert set(trainer.train()) == {0}
+ assert "GPU 1 (card1)" in capsys.readouterr().out
+
+
+def _public_bf16_helper(
+ fake,
+ monkeypatch,
+ world_size = "1",
+):
+ """The import-time chain of models/_utils.py, then its public is_bfloat16_supported, both from
+ the real source, so the helper reads exactly the state that chain leaves behind."""
+ monkeypatch.setenv("WORLD_SIZE", world_size)
+ namespace = _run_model_utils_chain(fake, monkeypatch)
+ body = _block(MODEL_UTILS, "def is_bfloat16_supported(", "\n\n\ndef ")
+ exec(compile(body, str(MODEL_UTILS), "exec"), namespace)
+ return namespace["is_bfloat16_supported"]
+
+
[email protected]("caps,start", [([SM61, SM86], 0), ([SM90, SM75], 0), ([SM75, SM86], 1)])
+def test_public_bf16_helper_follows_set_device_after_import(monkeypatch, caps, start):
+ # set_device after import: notebooks' fp16 = not is_bfloat16_supported() must match the new card.
+ fake = _fake_torch(caps)
+ fake.cuda.set_device(start)
+ helper = _public_bf16_helper(fake, monkeypatch)
+ assert helper() is (caps[start][0] >= 8)
+ other = 1 - start
+ fake.cuda.set_device(other)
+ assert helper() is (caps[other][0] >= 8)
+ assert helper() is bool(fake.cuda.is_bf16_supported(False))
+ fake.cuda.set_device(start)
+ assert helper() is (caps[start][0] >= 8)
+
+
[email protected]("current", [0, 1])
+def test_public_bf16_helper_keeps_the_weakest_card_on_a_distributed_launch(monkeypatch, current):
+ # Every rank must pick one dtype: set_device onto the rank's own card changes nothing.
+ fake = _fake_torch([SM90, SM75])
+ helper = _public_bf16_helper(fake, monkeypatch, world_size = "2")
+ fake.cuda.set_device(current)
+ assert helper() is False
+
+
[email protected]("caps", [[SM86], [SM90, SM90, SM90]], ids = ["one_gpu", "same_cards"])
+def test_public_bf16_helper_is_the_constant_on_homogeneous_hosts(monkeypatch, caps):
+ fake = _fake_torch(caps)
+ helper = _public_bf16_helper(fake, monkeypatch)
+ calls = []
+ fake.cuda.current_device = lambda: calls.append(1) or 0
+ assert helper() is True
+ assert calls == []
+
+
+LOADER_FILES = [
+ REPO_ROOT / "unsloth" / "models" / name
+ for name in ("llama.py", "vision.py", "loader.py", "diffusion.py", "sentence_transformer.py")
+]
+
+
[email protected]("path", LOADER_FILES, ids = lambda p: p.name)
+def test_loader_dtype_choices_ask_the_helper_at_call_time(path):
+ # The module-level constant is the import-time answer, wrong after a set_device.
+ import ast
+
+ stale = []
+ for node in ast.walk(ast.parse(path.read_text(encoding = "utf-8"))):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ names = [
+ n for n in ast.walk(node) if isinstance(n, ast.Name) and n.id == "SUPPORTS_BFLOAT16"
+ ]
+ if any(isinstance(n.ctx, ast.Load) for n in names) and not any(
+ isinstance(n.ctx, ast.Store) for n in names
+ ):
+ stale.append(f"{node.name}:{node.lineno}")
+ assert stale == []
+
+
+def test_an_unreadable_peer_keeps_the_cards_that_were_read(monkeypatch):
+ # One card's capability query raising must not drop the per-device table for the others.
+ monkeypatch.delenv("WORLD_SIZE", raising = False)
+ fake = _fake_torch([SM90, None, SM75])
+ read = fake.cuda.get_device_capability
+
+ def get_device_capability(device = None):
+ if read(device) is None:
+ raise RuntimeError("capability query failed")
+ return read(device)
+
+ fake.cuda.get_device_capability = get_device_capability
+ namespace = _run_model_utils_chain(fake, monkeypatch)
+ assert namespace["_BF16_BY_DEVICE"] == {0: True, 2: False}
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index ab7f2ac6d53..5292e5967fe 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -335,9 +335,9 @@ try:
arch_lacks_bf16,
arch_lacks_buffer_ops,
apply_gfx101x_triton_workaround,
- cuda_gate_capabilities,
+ cuda_bf16_capability,
cuda_order_mismatch_names,
- cuda_visible_capabilities,
+ distributed_launch,
hip_visible_archs,
xpu_supports_native_bf16,
zoo_shares_xpu_bf16,
@@ -581,24 +581,21 @@ if DEVICE_TYPE == "cuda" and not torch.cuda.is_available():
SUPPORTS_BFLOAT16 = False
torch.cuda.is_bf16_supported = lambda *args, **kwargs: False
elif DEVICE_TYPE == "cuda":
- # SUPPORTS_BFLOAT16 is process-wide, so one pre-Ampere card in the visible set disables it for all.
- _cuda_caps = cuda_gate_capabilities()
- SUPPORTS_BFLOAT16 = bool(_cuda_caps) and all(major >= 8 for major, _ in _cuda_caps)
- if not SUPPORTS_BFLOAT16 and any(major >= 8 for major, _ in _cuda_caps):
- _old = [i for i, (major, _) in cuda_visible_capabilities(with_index = True) if major < 8]
- print(
- f"Unsloth: visible GPU(s) {_old} lack bfloat16, so float16 is used on every GPU. "
- "Hide them with CUDA_VISIBLE_DEVICES to train in bfloat16."
- )
- del _old
- del _cuda_caps
+ # Current device, as torch answers; distributed launches keep the weakest card so ranks agree.
+ _cuda_cap = cuda_bf16_capability()
+ SUPPORTS_BFLOAT16 = _cuda_cap is not None and _cuda_cap[0] >= 8
+ del _cuda_cap
+ # Same rule for the public probe, else a merged 16-bit save picks bf16 for an fp16 distributed run.
+ _bf16_from_weakest = distributed_launch()
old_is_bf16_supported = torch.cuda.is_bf16_supported
if "including_emulation" in str(inspect.signature(old_is_bf16_supported)):
def is_bf16_supported(including_emulation = False):
supported = old_is_bf16_supported(including_emulation)
- return supported if including_emulation else (supported and SUPPORTS_BFLOAT16)
+ if including_emulation or not _bf16_from_weakest:
+ return supported
+ return supported and SUPPORTS_BFLOAT16
torch.cuda.is_bf16_supported = is_bf16_supported
else:
diff --git a/unsloth/device_type.py b/unsloth/device_type.py
index 7eb62fbdb80..cffe6298ef3 100644
--- a/unsloth/device_type.py
+++ b/unsloth/device_type.py
@@ -238,6 +238,48 @@ def cuda_gate_capabilities():
return []
+def cuda_current_capability():
+ """(major, minor) of the current CUDA device, or None when it cannot be read. bf16 and the
+ compile switches answer for it, as torch does: an idle older card beside it changes nothing,
+ and a load that places layers on one is checked after loading."""
+ try:
+ return tuple(torch.cuda.get_device_capability())
+ except Exception:
+ return None
+
+
+def distributed_launch():
+ """True under a distributed launcher (WORLD_SIZE > 1): ranks import before set_device, so the
+ current device is not yet the rank's own card and process-wide gates keep the weakest one."""
+ try:
+ return int(os.environ.get("WORLD_SIZE", "1") or "1") > 1
+ except ValueError:
+ return False
+
+
+def cuda_bf16_capability():
+ """Capability the process-wide bf16 answer and the pre-Volta compile switch are judged on. One
+ process: the current device, as torch answers. A distributed launch: the weakest visible card,
+ as before, since every rank must pick the same dtype and a rank's own card is not current yet
+ at import (a rank later moved onto an older card would otherwise keep Dynamo on)."""
+ if distributed_launch():
+ caps = cuda_gate_capabilities()
+ return min(caps) if caps else None
+ return cuda_current_capability()
+
+
+def hip_current_arch():
+ """gcnArchName of the current HIP device, or "" when it cannot be read."""
+ try:
+ return str(
+ getattr(
+ torch.cuda.get_device_properties(torch.cuda.current_device()), "gcnArchName", ""
+ )
+ )
+ except Exception:
+ return ""
+
+
def cuda_order_mismatch_names():
"""Visible NVIDIA names when they differ and CUDA_DEVICE_ORDER is unset, else []."""
if is_hip() or os.environ.get("CUDA_DEVICE_ORDER", "").strip():
@@ -408,12 +450,18 @@ def apply_pre_volta_compile_workaround(
return True
-# gfx906 (MI50 / Radeon VII / Vega 20): Dynamo/Inductor codegen is broken on this legacy GCN arch
-# (ROCm dropped it after 6.3), so compiled graphs crash or miscompile while eager trains fine.
-# Any visible gfx906 counts: compile is process-wide and layers may land on it. Same switch as
+# gfx906 (MI50 / Radeon VII, dropped after ROCm 6.3): compiled graphs crash or miscompile, eager
+# trains. Current device (every card when distributed); loads recheck placement. Same switch as
# pre-Volta, so regions compiled while unsloth_zoo imported are turned off too.
+def arch_breaks_compile(arch):
+ return str(arch or "").split(":")[0].strip().lower() == "gfx906"
+
+
if DEVICE_TYPE == "hip":
- if any(arch.split(":")[0].strip().lower() == "gfx906" for arch in hip_visible_archs()):
+ if any(
+ arch_breaks_compile(arch)
+ for arch in (hip_visible_archs() if distributed_launch() else [hip_current_arch()])
+ ):
os.environ.setdefault("TORCHDYNAMO_DISABLE", "1")
os.environ.setdefault("TORCH_COMPILE_DISABLE", "1")
os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")
@@ -425,8 +473,8 @@ if DEVICE_TYPE == "hip":
if DEVICE_TYPE == "cuda" and torch.cuda.is_available():
- # Weakest visible card: compile is process-wide and layers may land on any of them.
- _cuda_major = min((cap[0] for cap in cuda_gate_capabilities()), default = None)
+ # Same rule as bf16; layers placed on an older card are caught by check_mixed_gpu_placement.
+ _cuda_major = (cuda_bf16_capability() or (None,))[0]
if apply_pre_volta_compile_workaround(_cuda_major):
print(
"Unsloth: GPUs older than Volta (compute capability < 7.0) cannot run "
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 1d69deb4187..2afbae2fa87 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -72,6 +72,7 @@ __all__ = [
"resolve_model_class",
"resolve_attention_implementation",
"fall_back_from_flash_attention_on_pre_ampere",
+ "check_mixed_gpu_placement",
"resolve_encoder_attention_implementation",
"_set_attn_impl",
"set_task_config_attr",
@@ -167,7 +168,10 @@ from ..device_type import (
DEVICE_COUNT,
ALLOW_PREQUANTIZED_MODELS,
apply_gfx101x_triton_workaround,
- cuda_gate_capabilities,
+ apply_pre_volta_compile_workaround,
+ arch_breaks_compile,
+ cuda_bf16_capability,
+ distributed_launch,
gfx101x_triton_workaround_applied,
xpu_supports_native_bf16,
zoo_shares_xpu_bf16,
@@ -437,6 +441,11 @@ def _unsloth_reset_stray_compile_cache(self):
model = getattr(self, "model", None)
if model is None:
return
+ # The model may have moved (.to(), Trainer placement) since the load-time check.
+ try:
+ check_mixed_gpu_placement(model, live = True)
+ except Exception:
+ pass
# The detector hook can sit on any wrapper in the chain, and the probe may have run on a different one than self.model, so walk the chain.
markers = []
seen = False
@@ -1836,6 +1845,109 @@ def _pre_ampere_cuda_devices(model):
return sorted({indices[k] for k in attention if indices.get(k) in pre_ampere})
+def _placed_gpu_indices(model, live = False):
+ """GPU indices a loaded model's weights sit on: its hf_device_map, else every parameter's device
+ (an extracted text core carries no hf_device_map but may still span cards). live: the map plus
+ the parameters, since a later .to() / Trainer placement moves weights without updating the map."""
+ indices = set()
+ device_map = getattr(model, "hf_device_map", None)
+ if isinstance(device_map, dict):
+ indices = {i for i in (_cuda_index(v) for v in device_map.values()) if i is not None}
+ if not live:
+ return indices
+ try:
+ devices = {p.device for p in model.parameters()}
+ except Exception:
+ return indices
+ current = None
+ for device in devices:
+ if device.type != "cuda":
+ continue
+ if device.index is None:
+ if current is None:
+ current = torch.cuda.current_device()
+ indices.add(current)
+ else:
+ indices.add(device.index)
+ return indices
+
+
+def _bf16_weights_on(model, indices):
+ """torch.bfloat16 when a parameter of that dtype sits on one of these GPU indices, else None. The
+ live check has no load-time dtype, and a Trainer may have placed a bf16 model on an older card."""
+ try:
+ current = None
+ for p in model.parameters():
+ if p.dtype != torch.bfloat16 or p.device.type != "cuda":
+ continue
+ index = p.device.index
+ if index is None:
+ if current is None:
+ current = torch.cuda.current_device()
+ index = current
+ if index in indices:
+ return torch.bfloat16
+ except Exception:
+ pass
+ return None
+
+
+def check_mixed_gpu_placement(
+ model,
+ dtype = None,
+ live = False,
+):
+ """bf16 and the compile switches answer for the current device; check where the load really
+ put the weights. A card that cannot compile turns Dynamo off before the first forward, and
+ bf16 weights on a card without bf16 get a warning. A sole current-device placement is checked
+ too: the current device may have changed since import. One-GPU hosts never walk anything; the
+ capability reads hit the per-device cache. live: called when training starts, after a later
+ .to() or Trainer placement, so the parameters are read too (see _placed_gpu_indices)."""
+ if DEVICE_TYPE not in ("cuda", "hip") or DEVICE_COUNT <= 1:
+ return
+ indices = sorted(_placed_gpu_indices(model, live = live))
+ if not indices:
+ return
+
+ def _name(i):
+ try:
+ return f"GPU {i} ({torch.cuda.get_device_name(i)})"
+ except Exception:
+ return f"GPU {i}"
+
+ try:
+ if DEVICE_TYPE == "hip":
+ no_compile = [
+ i
+ for i in indices
+ if arch_breaks_compile(
+ getattr(torch.cuda.get_device_properties(i), "gcnArchName", "")
+ )
+ ]
+ no_bf16 = []
+ else:
+ caps = {i: tuple(torch.cuda.get_device_capability(i)) for i in indices}
+ no_compile = [i for i in indices if caps[i][0] < 7]
+ no_bf16 = [i for i in indices if caps[i][0] < 8]
+ except Exception:
+ return
+ import torch._dynamo as torch_dynamo
+
+ if no_compile and not torch_dynamo.config.disable and apply_pre_volta_compile_workaround(0):
+ print(
+ f"Unsloth: the model has layers on {', '.join(map(_name, no_compile))}, which cannot run "
+ "torch.compile, so training runs without it."
+ )
+ if no_bf16 and dtype is None and live:
+ dtype = _bf16_weights_on(model, set(no_bf16))
+ if no_bf16 and dtype == torch.bfloat16:
+ print(
+ f"Unsloth: the model has bfloat16 layers on {', '.join(map(_name, no_bf16))}, which has "
+ "no native bfloat16, so they run slowly. Load with dtype = torch.float16, or keep the "
+ "model on bfloat16 GPUs with CUDA_VISIBLE_DEVICES."
+ )
+
+
def fall_back_from_flash_attention_on_pre_ampere(model):
"""Device 0 chose Flash Attention 2; switch to SDPA (or eager) when the device map also put attention
layers on a pre-Ampere card, where every flash call would raise. Same-generation hosts never change."""
@@ -4130,17 +4242,19 @@ def _cache_device_capability(get_device_capability):
if getattr(get_device_capability, "_unsloth_per_device_cache", False):
return get_device_capability
- # One visible device: every spelling names it, so the plain C-level cache is exact and fastest.
+ # One device, or several with one capability: every spelling gets the same answer.
try:
- single_device = torch.cuda.device_count() <= 1
+ count = torch.cuda.device_count()
+ scanned = {i: get_device_capability(i) for i in range(count)} if count > 1 else {}
+ uniform = count <= 1 or len({tuple(c) for c in scanned.values()}) == 1
except Exception:
- single_device = False
- if single_device:
+ scanned, uniform = {}, False
+ if uniform:
cached = functools.cache(get_device_capability)
cached._unsloth_per_device_cache = True
return cached
- cache = {}
+ cache = dict(scanned)
@functools.wraps(get_device_capability)
def cached_get_device_capability(device = None):
@@ -4167,6 +4281,8 @@ def _cache_device_capability(get_device_capability):
SUPPORTS_BFLOAT16 = False
+# {device index: bf16} on a one-process host whose NVIDIA cards differ, else None (SUPPORTS_BFLOAT16 holds).
+_BF16_BY_DEVICE = None
HAS_FLASH_ATTENTION = False
HAS_FLASH_ATTENTION_SOFTCAPPING = False
@@ -4178,10 +4294,25 @@ if DEVICE_TYPE == "cuda" and not torch.cuda.is_available():
elif DEVICE_TYPE == "cuda":
major_version, minor_version = torch.cuda.get_device_capability()
torch.cuda.get_device_capability = _cache_device_capability(torch.cuda.get_device_capability)
- # SUPPORTS_BFLOAT16 is process-wide, so one pre-Ampere card in the visible set disables it for all.
- _cuda_caps = cuda_gate_capabilities()
- SUPPORTS_BFLOAT16 = bool(_cuda_caps) and all(major >= 8 for major, _ in _cuda_caps)
- del _cuda_caps
+ _bf16_cap = cuda_bf16_capability()
+ SUPPORTS_BFLOAT16 = _bf16_cap is not None and _bf16_cap[0] >= 8
+ del _bf16_cap
+ # Cards that differ: is_bfloat16_supported() follows a set_device after import.
+ if not distributed_launch():
+ # Per card, so an unreadable peer drops out instead of discarding the rest.
+ _bf16_caps = {}
+ try:
+ _bf16_count = torch.cuda.device_count()
+ except Exception:
+ _bf16_count = 0
+ for _bf16_i in range(_bf16_count):
+ try:
+ _bf16_caps[_bf16_i] = tuple(torch.cuda.get_device_capability(_bf16_i))
+ except Exception:
+ pass
+ if len(set(_bf16_caps.values())) > 1:
+ _BF16_BY_DEVICE = {i: cap[0] >= 8 for i, cap in _bf16_caps.items()}
+ del _bf16_caps, _bf16_count
if major_version >= 8:
if _package_available("flash_attn"):
@@ -5111,7 +5242,12 @@ def is_bfloat16_supported():
# 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
+ if _BF16_BY_DEVICE is None:
+ return SUPPORTS_BFLOAT16
+ try:
+ return _BF16_BY_DEVICE.get(torch.cuda.current_device(), SUPPORTS_BFLOAT16)
+ except Exception:
+ return SUPPORTS_BFLOAT16
def _requested_float32(dtype):
diff --git a/unsloth/models/diffusion.py b/unsloth/models/diffusion.py
index 9134cfa8270..4e4a656db88 100644
--- a/unsloth/models/diffusion.py
+++ b/unsloth/models/diffusion.py
@@ -26,6 +26,7 @@ from unsloth_zoo.hf_utils import add_dtype_kwargs
from ._utils import (
_mark_requested_float32,
_requested_float32,
+ check_mixed_gpu_placement,
is_bfloat16_supported,
maybe_prefetch_hf_snapshot,
)
@@ -432,6 +433,7 @@ class FastDiffusionModel:
)
model = model_cls.from_pretrained(model_name, config = config, **load_kwargs).eval()
+ check_mixed_gpu_placement(model, dtype)
model._unsloth_full_finetuning = bool(full_finetuning)
if trust_remote_code:
# 4.x remote code builds RoPE inv_freq in __init__; transformers 5 leaves it uninitialised.
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 922b063ee14..100133cdee2 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -4156,6 +4156,7 @@ class FastLlamaModel:
warn_if_bitsandbytes_quantized_nothing(
model, kwargs.get("quantization_config", None), model_name
)
+ check_mixed_gpu_placement(model, dtype)
# Attach dispatch hooks for bnb multi-device loads. The hooks stand aside only when vLLM
# owns the weights, which it never does here: vLLM has no classification head, so this
# branch loaded the weights in-process even though the caller asked for fast_inference.
@@ -4242,6 +4243,7 @@ class FastLlamaModel:
warn_if_bitsandbytes_quantized_nothing(
model, kwargs.get("quantization_config", None), model_name
)
+ check_mixed_gpu_placement(model, dtype)
from unsloth.models.vision import _attach_bnb_multidevice_hooks
from unsloth.models._remote_code_buffers import (
restore_remote_code_non_persistent_buffers,
diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.py
index 1c1ccbcf760..e3f90edf197 100644
--- a/unsloth/models/sentence_transformer.py
+++ b/unsloth/models/sentence_transformer.py
@@ -23,11 +23,12 @@ from .loader_utils import (
from ..device_type import DEVICE_TYPE, xpu_keeps_explicit_bf16
from ._utils import (
config_return_dict,
- SUPPORTS_BFLOAT16,
+ is_bfloat16_supported,
resolve_model_class,
resolve_encoder_attention_implementation,
maybe_prefetch_hf_snapshot,
_mark_full_finetuning,
+ check_mixed_gpu_placement,
)
import inspect
import json
@@ -134,6 +135,7 @@ def _maybe_upcast_force_float32_inference(st_model):
if inner is None or not _is_force_float32_config(getattr(inner, "config", None)):
return False
params = list(st_model.parameters())
+ SUPPORTS_BFLOAT16 = is_bfloat16_supported()
if SUPPORTS_BFLOAT16:
if any(p.dtype == torch.float16 for p in params):
print(f"Unsloth: {inner.config.model_type} does not support float16. Using bfloat16.")
@@ -2516,6 +2518,7 @@ class FastSentenceTransformer(FastModel):
"Run `pip install sentence-transformers` to install it."
)
+ SUPPORTS_BFLOAT16 = is_bfloat16_supported()
# Remote-class probes must use this load's trust, revision and hub options.
_remote_class_probe_kwargs = dict(
trust_remote_code = trust_remote_code,
@@ -2617,6 +2620,7 @@ class FastSentenceTransformer(FastModel):
if _validated:
st_kwargs["revision"] = _validated
st_model = SentenceTransformer(model_name, **st_kwargs)
+ check_mixed_gpu_placement(getattr(st_model[0], "auto_model", st_model), dtype)
# unsupported GPUs emulate bfloat16 slowly; float16 can yield non-finite activations.
if (dtype is None and not SUPPORTS_BFLOAT16) or dtype == torch.float16:
_maybe_upcast_force_float32_inference(st_model)
@@ -2755,6 +2759,7 @@ class FastSentenceTransformer(FastModel):
**({"config_kwargs": config_kwargs} if config_kwargs else {}),
)
+ check_mixed_gpu_placement(getattr(st_model[0], "auto_model", st_model), dtype)
st_model._unsloth_fast_encoder = True
_apply_max_seq_length(st_model, max_seq_length)
_mark_full_finetuning(st_model[0].auto_model, full_finetuning)
@@ -3371,6 +3376,14 @@ def _patch_sentence_transformer_trainer():
from functools import wraps
_original_init = SentenceTransformerTrainer.__init__
+ _original_train = SentenceTransformerTrainer.train
+
+ def _check_live_placement(trainer):
+ # A CPU-loaded model reaches its card only here: check before the deferred compile's first forward.
+ try:
+ check_mixed_gpu_placement(getattr(trainer, "model", None), live = True)
+ except Exception:
+ pass
@wraps(_original_init)
def _patched_init(self, *args, **kwargs):
@@ -3418,6 +3431,7 @@ def _patch_sentence_transformer_trainer():
model._compile_pending = False
_original_init(self, *args, **kwargs)
+ _check_live_placement(self)
# Disable mixed precision when FORCE_FLOAT32 is active (matches rl.py behavior)
if os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1":
@@ -3440,7 +3454,13 @@ def _patch_sentence_transformer_trainer():
except Exception as exc:
print(f"Unsloth: could not enable MFU logging ({exc}).")
+ @wraps(_original_train)
+ def _patched_train(self, *args, **kwargs):
+ _check_live_placement(self)
+ return _original_train(self, *args, **kwargs)
+
SentenceTransformerTrainer.__init__ = _patched_init
+ SentenceTransformerTrainer.train = _patched_train
SentenceTransformerTrainer._unsloth_auto_compile_patched = True
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 9bf558cc995..f47066b8bdc 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -4152,6 +4152,8 @@ class FastBaseModel:
model = _text_trainable_core(
model, text_intent = bool(text_only) if text_intent is None else bool(text_intent)
)
+ # After extraction, so a discarded vision / audio tower on an older card does not count.
+ check_mixed_gpu_placement(model, dtype)
# Save the standalone decoder under its own names, not the composite prefix it was read from.
_drop_text_only_key_mapping(model, _text_key_mapping)
_inherit_gradient_checkpointing_support(model)