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.

Keep the real quantization skip list on save, and add an opt-in multi-GPU device map (#8968)

Daniel Hanac600e8bb85b
diff --git a/tests/python/test_grpo_ddp_model_config.py b/tests/python/test_grpo_ddp_model_config.py
index 23614d3adde..18d85a83855 100644
--- a/tests/python/test_grpo_ddp_model_config.py
+++ b/tests/python/test_grpo_ddp_model_config.py
@@ -29,3 +29,61 @@ def test_grpo_logit_scaling_uses_model_config_helper():
assert "inspect.getsource(_unsloth_get_model_config)" in src
# No direct model.config access remains in the RL logit path.
assert "model.config" not in src
+
+
+def test_detect_logit_transforms_reads_the_unwrapped_config():
+ """The shared helper must be handed model_config, never the bare model.
+
+ A DDP/Accelerate wrapper does not forward .config, so passing the model makes
+ the helper report zeros, silently dropping Gemma softcapping and
+ Cohere/Granite/Falcon-H1 scaling on multi-GPU runs.
+ """
+ src = _read_source()
+ assert "detect_logit_transforms(model)" not in src
+ assert src.count("detect_logit_transforms(model_config)") >= 2
+
+
+def test_detect_logit_transforms_zeroes_out_on_a_wrapped_model():
+ """Behavioural counterpart: the resolved config must yield the transforms.
+
+ Deliberately does not assert what the helper does with the *bare* wrapper: older
+ unsloth_zoo reported nothing, newer versions unwrap ``.module`` / ``._orig_mod``
+ themselves, and pinning either would make this test track the zoo's internals.
+ What holds on every version is that the config we resolve is the one the
+ transforms come back from, which is why the call sites pass model_config.
+ """
+ torch = __import__("importlib").import_module("torch")
+ transformers = __import__("importlib").import_module("transformers")
+ planner = __import__("importlib").import_module("unsloth_zoo.device_map_planner")
+ detect = getattr(planner, "detect_logit_transforms", None)
+ if detect is None:
+ return # older unsloth_zoo: the fallback branch is in use
+
+ class _Inner(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = transformers.Gemma2Config()
+
+ class _Wrapper(torch.nn.Module):
+ """Same shape as DistributedDataParallel: real model under .module."""
+
+ def __init__(self, module):
+ super().__init__()
+ self.module = module
+
+ inner = _Inner()
+ wrapped = _Wrapper(inner)
+ # No .config on the wrapper, which is why call sites resolve it first.
+ assert not hasattr(wrapped, "config")
+ config = _unsloth_get_model_config_reference(wrapped)
+ assert config is inner.config
+ assert detect(config)["logit_softcapping"] == inner.config.final_logit_softcapping
+
+
+def _unsloth_get_model_config_reference(model):
+ """Mirror of rl_replacements._unsloth_get_model_config, kept local to avoid
+ importing the heavyweight module."""
+ config = getattr(model, "config", None)
+ if config is None and hasattr(model, "module"):
+ config = getattr(model.module, "config", None)
+ return config
diff --git a/tests/python/test_grpo_logit_transform_families.py b/tests/python/test_grpo_logit_transform_families.py
new file mode 100644
index 00000000000..8d0f6447bd3
--- /dev/null
+++ b/tests/python/test_grpo_logit_transform_families.py
@@ -0,0 +1,130 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team.
+"""Pins the logit transforms the GRPO path applies, per model family.
+
+The GRPO loss recomputes log-probs from hidden states, so it has to reproduce what
+the model's own ``forward`` does to its logits. A wrong factor does not raise: it
+silently shifts every log-prob, and with it the importance ratio.
+
+``detect_logit_transforms`` owns the field names, this test owns the expected
+*values*, so a change in its coverage shows up here as a diff rather than a quiet
+numerics shift.
+
+The loss applies them in the order multiply, divide, soft cap
+(``unsloth_zoo/rl_replacements.py``), matching what each family's ``modeling_*.py``
+does on the line after ``lm_head``.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+detect = pytest.importorskip(
+ "unsloth_zoo.device_map_planner",
+ reason = "unsloth_zoo without the planner: the fallback branch is in use",
+).__dict__.get("detect_logit_transforms")
+
+pytestmark = pytest.mark.skipif(
+ detect is None,
+ reason = "installed unsloth_zoo predates detect_logit_transforms",
+)
+
+
+class _Cfg:
+ """Stand-in for a PretrainedConfig, built by hand because the newest families
+ here only exist on transformers 5.9+ and this test runs on the pinned version."""
+
+ def __init__(self, **fields):
+ for key, value in fields.items():
+ setattr(self, key, _Cfg(**value) if isinstance(value, dict) else value)
+
+
+def _grpo_transforms(config):
+ """Exactly what rl_replacements derives before handing off to the loss."""
+ t = detect(config)
+ return (
+ t["logit_softcapping"],
+ t["logit_scale_multiply"],
+ t["logit_scale_divide"],
+ )
+
+
+# (name, config, (softcapping, multiply, divide), why)
+_COVERED = [
+ (
+ "granite",
+ _Cfg(model_type = "granite", logits_scaling = 8.0),
+ (0.0, 0.0, 8.0),
+ "modeling_granite.py divides: logits = logits / config.logits_scaling",
+ ),
+ (
+ "cohere",
+ _Cfg(model_type = "cohere", logit_scale = 0.0625),
+ (0.0, 0.0625, 0.0),
+ "modeling_cohere.py multiplies: logits = logits * self.logit_scale",
+ ),
+ (
+ "falcon_h1",
+ _Cfg(model_type = "falcon_h1", lm_head_multiplier = 0.01953125),
+ (0.0, 0.01953125, 0.0),
+ "modeling_falcon_h1.py multiplies by model.lm_head_multiplier",
+ ),
+ (
+ "gemma2",
+ _Cfg(model_type = "gemma2", final_logit_softcapping = 30.0),
+ (30.0, 0.0, 0.0),
+ "Gemma-style tanh soft cap, no scale",
+ ),
+]
+
+
[email protected]("name, config, expected, why", _COVERED)
+def test_stable_families(name, config, expected, why):
+ assert _grpo_transforms(config) == expected, why
+
+
+# Families the helper only bucketed recently. Each entry records what the GRPO path
+# used to apply, so the behaviour change stays legible.
+_RECENT = [
+ (
+ "muse_glimmer",
+ _Cfg(
+ model_type = "muse_glimmer",
+ text_config = {
+ "final_logit_softcapping": 20.0,
+ "output_multiplier": 0.19611613513818404,
+ },
+ ),
+ (20.0, 0.19611613513818404, 0.0),
+ (20.0, 0.0, 0.0),
+ "transformers applies logits * output_multiplier before the soft cap",
+ ),
+ (
+ "hyperclovax",
+ _Cfg(model_type = "hyperclovax", logits_scaling = 8.0),
+ (0.0, 8.0, 0.0),
+ (0.0, 0.0, 8.0),
+ "MuP multiplies by logits_scaling, unlike Granite which divides",
+ ),
+ (
+ "minicpm3",
+ _Cfg(model_type = "minicpm3", logits_scaling = 8.0),
+ (0.0, 0.0, 0.0),
+ (0.0, 0.0, 8.0),
+ "logits_scaling scales hidden states before the head, not the logits",
+ ),
+]
+
+
[email protected]("name, config, expected, previously, why", _RECENT)
+def test_recently_rebucketed_families(name, config, expected, previously, why):
+ """These three changed what the GRPO path applies. Deliberate, see the PR body.
+
+ Skips rather than fails on an unsloth_zoo predating the coverage, so the suite
+ stays green across the version window instead of pinning one release.
+ """
+ got = _grpo_transforms(config)
+ if got == previously:
+ pytest.skip(f"installed unsloth_zoo predates {name} coverage")
+ assert got == expected, why
diff --git a/tests/studio/test_hardware_dispatch_matrix.py b/tests/studio/test_hardware_dispatch_matrix.py
index cd2173f587a..701e00b7c99 100644
--- a/tests/studio/test_hardware_dispatch_matrix.py
+++ b/tests/studio/test_hardware_dispatch_matrix.py
@@ -362,3 +362,122 @@ def test_xpu_takes_priority_over_mlx_when_both_available(spoof_hardware):
spoof_hardware(profile)
hw = _import_studio_hardware_module()
assert hw.detect_hardware() == hw.DeviceType.XPU
+
+
+# Studio's placement, against the loader's opt-in device map.
+#
+# unsloth's loader upgrades a "sequential" device_map to the "unsloth" planning sentinel
+# when UNSLOTH_AUTO_DEVICE_MAP=1. Studio does not pass the sentinel and never sets that
+# variable, but an operator can set it process-wide, and Studio's "sequential" is not a
+# default it forgot to change: it is get_device_map() saying "one device". These pin the
+# two facts that keep that safe on every profile above -- Studio's multi-GPU answer is
+# "balanced", which is never upgraded, and its single-GPU answer is reached only inside a
+# worker that has already narrowed the visible devices to the selection.
+
+
+def _loader_device_map_helpers():
+ """The two loader functions, rebuilt over a fabricated torch.
+
+ ast rather than an import: `unsloth.models.loader_utils` pulls in the whole CUDA
+ import chain, which is exactly what the spoofs in this file are pretending about.
+ """
+ import ast as _ast
+
+ source = (REPO_ROOT / "unsloth" / "models" / "loader_utils.py").read_text(encoding = "utf-8")
+
+ class _Cuda:
+ def __init__(self, count):
+ self._count = count
+
+ def device_count(self):
+ return self._count
+
+ def mem_get_info(self, index):
+ return (8 * 2**30, 16 * 2**30)
+
+ def build(visible_devices):
+ import os as _os
+
+ namespace = {
+ "os": _os,
+ "torch": types.SimpleNamespace(cuda = _Cuda(visible_devices)),
+ "DEVICE_TYPE_TORCH": "cuda",
+ "is_distributed": lambda: False,
+ }
+ for node in _ast.parse(source).body:
+ if isinstance(node, _ast.FunctionDef) and node.name in (
+ "requested_device_map",
+ "resolve_unsloth_device_map",
+ "_as_bytes",
+ ):
+ exec(_ast.get_source_segment(source, node), namespace)
+ elif isinstance(node, _ast.ClassDef) and node.name == "_DefaultDeviceMap":
+ exec(_ast.get_source_segment(source, node), namespace)
+ elif isinstance(node, _ast.Assign) and getattr(node.targets[0], "id", None) in (
+ "UNSLOTH_DEVICE_MAP",
+ "DEFAULT_DEVICE_MAP",
+ "_SIZE_UNITS",
+ ):
+ exec(_ast.get_source_segment(source, node), namespace)
+ # No planner installed: the fallback is what a decline looks like from here.
+ sys.modules.pop("unsloth_zoo.device_map_planner", None)
+ sys.modules["unsloth_zoo.device_map_planner"] = types.ModuleType(
+ "unsloth_zoo.device_map_planner"
+ )
+ return namespace
+
+ return build
+
+
[email protected]("profile", PROFILES, ids = PROFILE_IDS)
[email protected]("gpu_ids", [None, [], [0], [0, 1], [2, 3, 5]], ids = repr)
[email protected]("opt_in", ["unset", "0", "1"])
+def test_studio_placement_survives_the_loader_opt_in(
+ profile, gpu_ids, opt_in, spoof_hardware, monkeypatch
+):
+ """Whatever Studio decided, the loader hands the same thing to transformers.
+
+ The one value the opt-in can rewrite is "sequential", and Studio only produces that
+ when it selected a single device -- at which point the worker has already narrowed the
+ visible set, the planner sees one GPU and declines back to "sequential".
+ """
+ spoof_hardware(profile)
+ hw = _import_studio_hardware_module()
+
+ if gpu_ids and hw.get_device() not in (hw.DeviceType.CUDA, hw.DeviceType.XPU):
+ pytest.skip(f"{profile.name} does not take an explicit gpu_ids")
+
+ device_map = hw.get_device_map(gpu_ids)
+ assert device_map in ("balanced", "sequential")
+
+ if opt_in == "unset":
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ else:
+ monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", opt_in)
+
+ # The worker narrows CUDA_VISIBLE_DEVICES to the selection before torch initialises,
+ # so the loader counts the selected devices, not the machine's.
+ visible = len(gpu_ids) if gpu_ids else 1
+ loader = _loader_device_map_helpers()(visible)
+
+ resolved = loader["resolve_unsloth_device_map"](
+ loader["requested_device_map"](device_map), "unsloth/Qwen3-0.6B"
+ )
+ assert resolved == device_map, (
+ f"profile {profile.name}, gpu_ids={gpu_ids}, UNSLOTH_AUTO_DEVICE_MAP={opt_in}: "
+ f"Studio asked for {device_map!r} and the loader produced {resolved!r}"
+ )
+
+
[email protected]("profile", PROFILES, ids = PROFILE_IDS)
+def test_studio_never_speaks_the_planning_sentinel(profile, spoof_hardware):
+ """get_device_map is the only thing that names a placement for Studio's loads, and
+ "unsloth" is not one of its answers on any backend. If it ever becomes one, the
+ Studio-side reasoning above stops holding and this fails first."""
+ spoof_hardware(profile)
+ hw = _import_studio_hardware_module()
+ answers = {hw.get_device_map(None), hw.get_device_map([])}
+ if hw.get_device() in (hw.DeviceType.CUDA, hw.DeviceType.XPU):
+ answers |= {hw.get_device_map([0]), hw.get_device_map([0, 1])}
+ assert "unsloth" not in answers
+ assert answers <= {"balanced", "sequential"}
diff --git a/tests/test_bnb_checkpoint_skip_modules.py b/tests/test_bnb_checkpoint_skip_modules.py
new file mode 100644
index 00000000000..f29a6983bfd
--- /dev/null
+++ b/tests/test_bnb_checkpoint_skip_modules.py
@@ -0,0 +1,170 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Pins the two rules a pre-quantized bitsandbytes load depends on. No GPU needed.
+
+Rule one: a pre-quantized checkpoint's own ``llm_int8_skip_modules`` is the authority and
+Unsloth must not add to it. The list describes how the tensors were actually packed, so
+adding a name makes transformers build a dense ``Linear`` for packed weights and the load
+dies in ``load_state_dict``:
+
+ size mismatch for weight: copying a param with shape torch.Size([15728640, 1])
+ from checkpoint, the shape in current model is torch.Size([4096, 7680])
+
+A real failure, observed on ``unsloth/Llama-3.2-11B-Vision-Instruct-bnb-4bit``, whose
+config ships ``llm_int8_skip_modules: null`` because it quantized everything. ``None``
+there is an instruction ("skip nothing"), not an absence, and replacing it with Unsloth's
+generic list broke the two ``test_save_merged_*`` cases for that model.
+
+Rule two: what the load used is what gets saved. ``loader.py`` used to stamp ``None`` over
+the real list, which for a dynamic-quant repo like ``unsloth/Qwen3-0.6B-unsloth-bnb-4bit``
+threw away every per-layer entry and saved a config describing a layout that never existed.
+
+Extracted with ast so nothing in loader.py has to import.
+"""
+
+import ast
+import os
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MODELS = os.path.join(HERE, "unsloth", "models")
+LOADER = os.path.join(MODELS, "loader.py")
+VISION = os.path.join(MODELS, "vision.py")
+
+
+def _load(path, *names):
+ source = open(path, encoding = "utf-8").read()
+ ns, wanted = {}, set(names)
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.FunctionDef) and node.name in wanted:
+ exec(ast.get_source_segment(source, node), ns)
+ wanted.discard(node.name)
+ if wanted:
+ raise AssertionError(f"not found in {os.path.basename(path)}: {sorted(wanted)}")
+ return ns
+
+
+loaded_skip = _load(LOADER, "_config_get", "_loaded_skip_modules")["_loaded_skip_modules"]
+
+# What unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit's config.json actually carries.
+GLIMMER = [
+ "model.language_model.embed_tokens",
+ "lm_head",
+ "model.vision_tower",
+ "model.vision_adapter",
+ "model.vision_projection",
+]
+
+
+class _Config:
+ """A BitsAndBytesConfig stands in as a plain attribute holder."""
+
+ def __init__(self, **fields):
+ self.__dict__.update(fields)
+
+
+# ------------------------------- rule one: nobody rewrites the checkpoint's own list
+
+
+def test_the_vision_loader_does_not_touch_the_checkpoint_skip_list():
+ """The regression this file exists for.
+
+ Transformers already prefers a pre-quantized checkpoint's `quantization_config` over
+ the runtime one, so there is nothing for the loader to fix. Writing into that config is
+ the only way to get it wrong, and it did: on Llama-3.2-11B-Vision-bnb-4bit it turned a
+ `null` skip list into Unsloth's generic one and broke the load outright.
+ """
+ source = open(VISION, encoding = "utf-8").read()
+ assert "merge_checkpoint_skip_modules" not in source
+ # It may still build its own runtime list (the next test pins that); what it must
+ # never do is assign into the config that came off the checkpoint.
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.Assign):
+ continue
+ for target in node.targets:
+ written = ast.unparse(target)
+ assert not (
+ "quantization_config" in written and "llm_int8_skip_modules" in written
+ ), f"vision.py writes the checkpoint's skip list at line {node.lineno}: {written}"
+ if isinstance(node.targets[0], ast.Subscript):
+ written = ast.unparse(node.targets[0])
+ assert (
+ "llm_int8_skip_modules" not in written
+ ), f"vision.py writes a skip list by subscript at line {node.lineno}"
+
+
+def test_the_runtime_skip_list_is_still_built_for_on_the_fly_quantization():
+ """The other half: a full-precision checkpoint has no config to defer to, so Unsloth's
+ own list keeps heads, routers and towers in compute dtype. Hence the fix was to remove
+ a write, not to stop building the list."""
+ source = open(VISION, encoding = "utf-8").read()
+ assert "_skip_modules = SKIP_QUANTIZATION_MODULES.copy()" in source
+ assert "llm_int8_skip_modules = _skip_modules" in source
+
+
+def test_the_bnb_config_chain_is_still_one_piece():
+ """The merge used to sit inside this four-branch if/elif, where a statement dropped in
+ the middle silently re-parents the last branch and the "Switching to 16bit LoRA" notice
+ fires on every 16-bit load."""
+ source = open(VISION, encoding = "utf-8").read()
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.If) or ast.unparse(node.test) != "load_in_4bit":
+ continue
+ if "BitsAndBytesConfig" not in ast.unparse(node):
+ continue
+ tests, current = [], node
+ while True:
+ tests.append(ast.unparse(current.test))
+ if len(current.orelse) == 1 and isinstance(current.orelse[0], ast.If):
+ current = current.orelse[0]
+ else:
+ break
+ assert "load_in_8bit" in tests and "load_in_16bit" in tests, tests
+ assert any(
+ "full_finetuning" in test for test in tests
+ ), f"the 16bit-LoRA notice fell out of the chain: {tests}"
+ return
+ raise AssertionError("could not find the bnb_config if/elif chain in vision.py")
+
+
+# ------------------------------------ rule two: the saved config matches the load
+
+
+def test_the_stamp_keeps_the_list_the_load_actually_used():
+ """A dynamic-quant repo's per-layer entries have to survive into the saved config, or
+ the adapter records a base topology that cannot be rebuilt."""
+ real = GLIMMER + ["model.layers.27.mlp.up_proj"]
+ config = _Config(quantization_config = {"llm_int8_skip_modules": real})
+ assert loaded_skip(config) == real
+
+
+def test_the_stamp_still_reports_none_when_there_was_no_list():
+ """None is the instruction Llama-3.2-11B-Vision-bnb-4bit ships: quantize everything.
+ Inventing a list here is the same mistake in a different place."""
+ for config in (
+ _Config(quantization_config = {}),
+ _Config(quantization_config = {"llm_int8_skip_modules": None}),
+ _Config(quantization_config = None),
+ _Config(),
+ ):
+ assert loaded_skip(config) is None
+
+
+def test_the_stamp_preserves_an_explicit_empty_list():
+ """[] and None are not interchangeable: None lets transformers pick the output head
+ itself, [] says it was told to exclude nothing."""
+ config = _Config(quantization_config = {"llm_int8_skip_modules": []})
+ assert loaded_skip(config) == []
+
+
+def test_the_stamp_reads_an_object_config_too():
+ config = _Config(quantization_config = _Config(llm_int8_skip_modules = list(GLIMMER)))
+ assert loaded_skip(config) == GLIMMER
+
+
+def test_the_stamp_is_applied_at_every_site_that_writes_a_synthetic_config():
+ """There are two of these, one per loader class. Fixing one and not the other leaves
+ half the models still saving a config that describes nothing."""
+ source = open(LOADER, encoding = "utf-8").read()
+ assert source.count('"llm_int8_skip_modules": _loaded_skip_modules(model.config)') == 2
+ assert '"llm_int8_skip_modules": None' not in source
diff --git a/tests/test_unsloth_device_map_leaks.py b/tests/test_unsloth_device_map_leaks.py
new file mode 100644
index 00000000000..8faa6e29071
--- /dev/null
+++ b/tests/test_unsloth_device_map_leaks.py
@@ -0,0 +1,178 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Every leaf loader must resolve `device_map = "unsloth"` before transformers sees it.
+
+`"unsloth"` is not a placement strategy transformers knows: `modeling_utils.py` turns any
+string outside {auto, balanced, balanced_low_0, sequential} into `torch.device(...)`, so
+an unresolved one raises:
+
+ ValueError: When passing device_map as a string, the value needs to be a device name
+ (e.g. cpu, cuda:0) or 'auto', 'balanced', 'balanced_low_0', 'sequential' but found unsloth
+
+`FastModel.from_pretrained` converts the default to "unsloth" under
+`UNSLOTH_AUTO_DEVICE_MAP=1` and then returns through `_dispatch_diffusion()` before
+`FastBaseModel` can resolve it, so the text-diffusion slow path needs its own call. And
+the planner needs the same repository ref as the real load, or it plans the default branch.
+
+Extracted with ast so nothing has to import torch's CUDA stack.
+"""
+
+import ast
+import os
+
+import pytest
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MODELS = os.path.join(HERE, "unsloth", "models")
+
+
+def _source(name):
+ return open(os.path.join(MODELS, name), encoding = "utf-8").read()
+
+
+def _resolve_calls(source):
+ return [
+ node
+ for node in ast.walk(ast.parse(source))
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "resolve_unsloth_device_map"
+ ]
+
+
+def test_unsloth_is_not_a_device_map_transformers_accepts():
+ """The premise. If transformers ever learns the string, the rest of this file is moot."""
+ import torch
+ with pytest.raises(RuntimeError):
+ torch.device("unsloth")
+
+
[email protected]("name", ["llama.py", "vision.py", "diffusion.py"])
+def test_every_leaf_loader_resolves_before_it_loads(name):
+ """loader.py only routes; these three are what actually call transformers, and each
+ one is reachable holding "unsloth" (diffusion via `_dispatch_diffusion`)."""
+ assert _resolve_calls(_source(name)), f"{name} forwards device_map unresolved"
+
+
+def test_the_diffusion_dispatch_hands_over_the_planner_hints():
+ """`_dispatch_diffusion` forwards **kwargs, but `device_map_planner_kwargs` is a named
+ parameter of `FastModel.from_pretrained`, so it is not in **kwargs and would be lost."""
+ source = _source("loader.py")
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.Call):
+ continue
+ if ast.unparse(node.func) != "FastDiffusionModel.from_pretrained":
+ continue
+ passed = {kw.arg for kw in node.keywords}
+ assert "device_map_planner_kwargs" in passed
+ return
+ raise AssertionError("no FastDiffusionModel.from_pretrained call in loader.py")
+
+
+ "name,expected",
+ [("llama.py", "revision"), ("vision.py", "_revision"), ("diffusion.py", "revision")],
+)
+def test_the_planner_gets_the_same_ref_the_weights_do(name, expected):
+ """A plan built from the default branch's config can name modules the pinned revision
+ does not have, and accelerate then refuses the map outright:
+
+ ValueError: The device_map provided does not give any device for the following
+ parameters: ...
+ """
+ for call in _resolve_calls(_source(name)):
+ revisions = [kw for kw in call.keywords if kw.arg == "revision"]
+ assert revisions, f"{name}:{call.lineno} plans without a revision"
+ for keyword in revisions:
+ assert ast.unparse(keyword.value) == expected, (
+ f"{name}:{call.lineno} passes "
+ f"{ast.unparse(keyword.value)}, not the ref the load uses"
+ )
+
+
+def test_sentence_transformer_never_hands_the_sentinel_to_sentence_transformers():
+ """`FastSentenceTransformer.from_pretrained` has its own public `device_map`, and its
+ `st_device` blocks pass it to `SentenceTransformer(device = ...)` -> `self.to(device)`:
+
+ RuntimeError: Expected one of cpu, cuda, ... device type at start of device string:
+ unsloth
+
+ It cannot plan either -- that same `.to()` would pull a split model back onto one card
+ -- so the sentinel has to be spent before the `st_device` blocks read it.
+ """
+ tree = ast.parse(_source("sentence_transformer.py"))
+ function = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "from_pretrained"
+ )
+ assert any(
+ kw.arg == "device_map" for kw in function.args.kwonlyargs + function.args.args
+ ), "from_pretrained no longer takes device_map"
+
+ spends = [
+ node
+ for node in ast.walk(function)
+ if isinstance(node, ast.Compare)
+ and ast.unparse(node.left) == "device_map"
+ and any(ast.unparse(c) == "UNSLOTH_DEVICE_MAP" for c in node.comparators)
+ ]
+ assert spends, "the 'unsloth' sentinel reaches SentenceTransformer(device = ...) unresolved"
+
+ first_st_device = min(
+ node.lineno
+ for node in ast.walk(function)
+ if isinstance(node, ast.Assign)
+ and any(getattr(t, "id", None) == "st_device" for t in node.targets)
+ )
+ assert (
+ min(node.lineno for node in spends) < first_st_device
+ ), "the sentinel is spent after st_device is derived from device_map"
+
+
+def test_sentence_transformer_decline_survives_the_env_var():
+ """The decline has to outlive the re-entry into `FastModel.from_pretrained`.
+
+ That nested call runs `requested_device_map` again, so a still-marked default is
+ upgraded back to "unsloth" and planned as a split while `st_device` reads "sequential"
+ and pulls the model onto one card. The guard is stripping the marker -- and only the
+ marker, since `str()` over everything flattens an explicit dict placement into text.
+
+ The absence of the process-wide pin is asserted too: `os.environ` is shared, so pinning
+ it around the call reached unrelated loads on other threads.
+ """
+ source = _source("sentence_transformer.py")
+ tree = ast.parse(source)
+ function = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "from_pretrained"
+ )
+
+ # The decline itself must read the env var, not the raw argument.
+ assert any(
+ isinstance(node, ast.Call) and getattr(node.func, "id", None) == "requested_device_map"
+ for node in ast.walk(function)
+ ), "the decline reads device_map raw, so UNSLOTH_AUTO_DEVICE_MAP=1 walks past it"
+
+ strips = [
+ node
+ for node in ast.walk(function)
+ if isinstance(node, ast.Assign)
+ and any(getattr(t, "id", None) == "device_map" for t in node.targets)
+ and ast.unparse(node.value) == "unmarked_device_map(device_map)"
+ ]
+ assert strips, "the nested load still gets the marked default, which it will re-upgrade"
+
+ fastmodel_call = min(
+ node.lineno
+ for node in ast.walk(function)
+ if isinstance(node, ast.Call) and ast.unparse(node.func) == "FastModel.from_pretrained"
+ )
+ assert (
+ min(node.lineno for node in strips) < fastmodel_call
+ ), "the marker is stripped after FastModel has already planned"
+
+ assert "os.environ['UNSLOTH_AUTO_DEVICE_MAP']" not in ast.unparse(
+ function
+ ), "the process-wide pin is back; every other thread sees it"
diff --git a/tests/test_unsloth_device_map_optin.py b/tests/test_unsloth_device_map_optin.py
new file mode 100644
index 00000000000..9772d2952c8
--- /dev/null
+++ b/tests/test_unsloth_device_map_optin.py
@@ -0,0 +1,618 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Tests the opt-in multi-GPU planning in loader_utils.py. No GPU needed.
+
+`device_map = "unsloth"` asks unsloth_zoo's planner for a head-aware placement instead of
+accelerate's `"sequential"`. The Muse Glimmer GRPO notebook does this by hand today, in
+about 25 lines of mem_get_info arithmetic.
+
+It is opt-in because the alternative is not safe: an existing multi-GPU caller who never
+asked for planning must keep the placement they have. So most of this file is about what
+must NOT change, and only the last group is about planning working.
+
+Extracted with ast so nothing has to import torch's CUDA stack.
+"""
+
+import ast
+import os
+import sys
+import types
+
+import pytest
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+LOADER_UTILS = os.path.join(HERE, "unsloth", "models", "loader_utils.py")
+_SRC = open(LOADER_UTILS, encoding = "utf-8").read()
+_SKIP_MODULES = ["lm_head", "vision_tower", "audio_tower"]
+
+
+class _FakeCuda:
+ def __init__(
+ self,
+ count,
+ free = None,
+ ):
+ self._count = count
+ self._free = free or {}
+
+ def device_count(self):
+ return self._count
+
+ def mem_get_info(self, index):
+ # (free, total). The planner must read the first, not the second.
+ return (self._free.get(index, 8 * 2**30), 16 * 2**30)
+
+
+def _load(
+ *,
+ devices = 2,
+ device_type = "cuda",
+ free = None,
+ planner = None,
+ distributed = False,
+):
+ """Rebuild the two functions over a fabricated CUDA and unsloth_zoo."""
+ ns = {
+ "os": os,
+ "torch": types.SimpleNamespace(cuda = _FakeCuda(devices, free)),
+ "DEVICE_TYPE_TORCH": device_type,
+ "is_distributed": lambda: distributed,
+ }
+ for node in ast.parse(_SRC).body:
+ if isinstance(node, ast.FunctionDef) and node.name in (
+ "requested_device_map",
+ "resolve_unsloth_device_map",
+ "planner_quantization_kwargs",
+ "planner_class_mismatch_reason",
+ "_as_bytes",
+ ):
+ exec(ast.get_source_segment(_SRC, node), ns)
+ elif isinstance(node, ast.ClassDef) and node.name == "_DefaultDeviceMap":
+ exec(ast.get_source_segment(_SRC, node), ns)
+ elif isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) in (
+ "UNSLOTH_DEVICE_MAP",
+ "DEFAULT_DEVICE_MAP",
+ "_SIZE_UNITS",
+ ):
+ exec(ast.get_source_segment(_SRC, node), ns)
+
+ # planner_quantization_kwargs reads the shared skip list; stub it so the test never
+ # imports the real unsloth_zoo (and so the assertions do not track its contents).
+ peft_utils = types.ModuleType("unsloth_zoo.peft_utils")
+ peft_utils.SKIP_QUANTIZATION_MODULES = list(_SKIP_MODULES)
+ sys.modules["unsloth_zoo.peft_utils"] = peft_utils
+
+ if planner is not None:
+ module = types.ModuleType("unsloth_zoo.device_map_planner")
+ module.plan_device_map_for_pretrained = planner
+ sys.modules["unsloth_zoo.device_map_planner"] = module
+ return ns
+
+
+class _Plan:
+ def __init__(self, device_map):
+ self.device_map = device_map
+
+ def describe(self):
+ return " (fabricated plan)"
+
+
+# ------------------------------------------------- what an existing caller still gets
+
+
+ "device_map",
+ [
+ "sequential", # today's default
+ "auto", # accelerate's, which this must never reinterpret
+ "balanced", # what Unsloth Studio passes
+ "balanced_low_0",
+ None, # a single device
+ ],
+)
+def test_every_existing_device_map_is_returned_untouched(device_map):
+ """The whole opt-in claim in one test. If any of these changed, every multi-GPU user
+ who never asked for planning would silently get a different placement."""
+ ns = _load(planner = lambda *a, **k: pytest.fail("the planner must not run"))
+ assert ns["resolve_unsloth_device_map"](device_map, "some/model") is device_map
+
+
+def test_an_explicit_dict_is_returned_untouched():
+ explicit = {"": 0, "model.vision_tower": 1}
+ ns = _load(planner = lambda *a, **k: pytest.fail("the planner must not run"))
+ assert ns["resolve_unsloth_device_map"](explicit, "some/model") is explicit
+
+
+def test_the_env_var_only_upgrades_the_default(monkeypatch):
+ """UNSLOTH_AUTO_DEVICE_MAP is an operator switch, not a licence to override a
+ placement the caller chose. "auto" and a dict must survive it.
+
+ So must a "sequential" the caller typed out, which is why the default carries a marker:
+ the two are the same string, and the switch is only entitled to the one nobody chose.
+ """
+ ns = _load()
+ monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", "1")
+ assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == "unsloth"
+ assert ns["requested_device_map"]("sequential") == "sequential"
+ assert ns["requested_device_map"]("auto") == "auto"
+ assert ns["requested_device_map"]("balanced") == "balanced"
+ assert ns["requested_device_map"]({"": 0}) == {"": 0}
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP")
+ assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == "sequential"
+
+
+# ------------------------------------------------------- where planning cannot apply
+
+
+ "kwargs,why",
+ [
+ ({"fast_inference": True}, "vLLM places its own weights"),
+ ({"full_finetuning": True}, "no bnb layout to plan"),
+ ],
+)
+def test_planning_is_declined_where_something_else_owns_placement(kwargs, why):
+ ns = _load(planner = lambda *a, **k: pytest.fail(f"must not plan: {why}"))
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m", **kwargs) == "sequential"
+
+
+def test_a_caller_that_vetoes_planning_is_obeyed():
+ """Only the leaf knows when the config it is about to load is not the one the planner
+ would rebuild from the repo, so it needs a way to say so."""
+ ns = _load(planner = lambda *a, **k: pytest.fail("planned despite the veto"))
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m", skip_reason = "text_only") == "sequential"
+ # A veto is not a licence to reinterpret a placement the caller chose.
+ assert ns["resolve_unsloth_device_map"]("auto", "m", skip_reason = "text_only") == "auto"
+
+
+def test_a_text_only_decoder_is_never_planned_against_the_full_vlm():
+ """`text_only = True` loads a VLM's standalone decoder, so Gemma 3 builds
+ Gemma3ForCausalLM (`model.layers.0`). The planner only gets `model_name`, rebuilds the
+ repo's multimodal config and plans Gemma3ForConditionalGeneration
+ (`model.language_model.layers.0`, plus a vision tower this load never creates). Not one
+ decoder weight matches a key of that map, and transformers raises
+ "model.embed_tokens.weight doesn't have any device set" for the first of them.
+ """
+ models = os.path.join(HERE, "unsloth", "models")
+
+ vision = open(os.path.join(models, "vision.py"), encoding = "utf-8").read()
+ tree = ast.parse(vision)
+ signature = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef)
+ and node.name == "from_pretrained"
+ and any(a.arg == "text_only" for a in node.args.args + node.args.kwonlyargs)
+ ]
+ assert signature, "vision.py no longer takes text_only"
+ for node in signature:
+ args = {a.arg for a in node.args.args + node.args.kwonlyargs}
+ assert "text_only_decoder" in args, f"vision.py:{node.lineno}"
+ # The direct-call path resolves the text config itself, so it has to raise the flag.
+ assert "text_only_decoder = True" in vision
+
+ # The veto reaches the planner call, and whatever it is spelled as is decided by the flag.
+ assignments = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign):
+ continue
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ assignments[target.id] = assignments.get(target.id, "") + ast.unparse(node.value)
+ for call in _resolve_calls(vision):
+ passed = {kw.arg: ast.unparse(kw.value) for kw in call.keywords}
+ assert "skip_reason" in passed, f"vision.py:{call.lineno} plans a text-only decoder"
+ source = passed["skip_reason"] + assignments.get(passed["skip_reason"], "")
+ assert "text_only_decoder" in source, f"vision.py:{call.lineno}"
+ # The other way the load can diverge from the plan; see the task-head test.
+ assert "planner_class_mismatch_reason" in source, f"vision.py:{call.lineno}"
+
+ # loader.py does the swap for FastModel/FastLanguageModel, so it has to say so too.
+ loader = open(os.path.join(models, "loader.py"), encoding = "utf-8").read()
+ assert "text_only_decoder = True" in loader
+ forwarded = [
+ node
+ for node in ast.walk(ast.parse(loader))
+ if isinstance(node, ast.Call) and any(kw.arg == "text_only_decoder" for kw in node.keywords)
+ ]
+ assert forwarded, "loader.py swaps the config but never tells the leaf"
+
+
+def test_a_task_head_the_planner_cannot_see_declines_planning():
+ """`num_labels` makes the load AutoModelForSequenceClassification, whose `score`
+ replaces `lm_head`. The planner sees only `model_name`, reads the repo's own
+ `LlamaForCausalLM` and emits units ending in `lm_head`, so dispatch refuses the map:
+ "does not give any device for ... score.weight".
+
+ Compared as model classes, since AutoModelForVision2Seq and AutoModelForImageTextToText
+ are different objects building the same VLM and would decline planning for every VLM.
+ """
+ ns = _load()
+ mismatch = ns["planner_class_mismatch_reason"]
+
+ class LlamaForCausalLM:
+ pass
+
+ class LlamaForSequenceClassification:
+ pass
+
+ reason = mismatch(LlamaForSequenceClassification, LlamaForCausalLM)
+ assert reason and "LlamaForSequenceClassification" in reason
+ assert mismatch(LlamaForCausalLM, LlamaForCausalLM) is None
+ # Unknown is not mismatched: an unsloth_zoo too old to name the class has no planner.
+ assert mismatch(LlamaForCausalLM, None) is None
+ assert mismatch(None, LlamaForCausalLM) is None
+
+ ns = _load(planner = lambda *a, **k: pytest.fail("planned a head the plan does not name"))
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m", skip_reason = reason) == "sequential"
+
+
+def test_the_optimized_llama_path_also_declines_a_classification_load():
+ """The same veto has to live on llama.py's own planner call, not just vision.py's.
+
+ loader.py delegates to FastModel only for 8bit / full finetuning / QAT, so
+ `FastLanguageModel.from_pretrained(..., num_labels = 2, device_map = "unsloth")` on a
+ llama/mistral/gemma/qwen repo dispatches to FastLlamaModel, plans the repo's causal LM,
+ then loads AutoModelForSequenceClassification a few lines later. That model has `score`
+ and no `lm_head`, so `dispatch_model` -> `check_device_map` raises.
+ """
+ llama = open(os.path.join(HERE, "unsloth", "models", "llama.py"), encoding = "utf-8").read()
+ tree = ast.parse(llama)
+
+ assignments = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign):
+ continue
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ assignments[target.id] = assignments.get(target.id, "") + ast.unparse(node.value)
+
+ calls = _resolve_calls(llama)
+ assert calls, "llama.py no longer plans a device map"
+ for call in calls:
+ passed = {kw.arg: ast.unparse(kw.value) for kw in call.keywords}
+ assert "skip_reason" in passed, f"llama.py:{call.lineno} plans a classification load"
+ source = passed["skip_reason"] + assignments.get(passed["skip_reason"], "")
+ assert "num_labels" in source, f"llama.py:{call.lineno}"
+ assert "planner_class_mismatch_reason" in source, f"llama.py:{call.lineno}"
+
+ # The veto must be decided before the call, or it is a NameError on every load.
+ veto_line = min(
+ node.lineno
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Assign)
+ and any(getattr(t, "id", None) == "_planner_skip_reason" for t in node.targets)
+ )
+ assert veto_line < min(call.lineno for call in calls)
+
+
+def test_a_distributed_launch_never_gets_an_intra_model_split():
+ """torchrun/DDP/FSDP already put one whole model per rank; splitting a model across the
+ cards on top of that puts every rank on every card, which OOMs rather than fits.
+
+ prepare_device_map() in loader.py converts the string to a rank-local dict first, but
+ only when the load is quantized, so a 16-bit distributed run still arrives here holding
+ "unsloth". Hence the gate lives here too.
+ """
+ ns = _load(
+ distributed = True, planner = lambda *a, **k: pytest.fail("planned inside a distributed launch")
+ )
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == "sequential"
+
+
[email protected]("device_type", ["xpu", "mps", "cpu", "hpu"])
+def test_a_non_cuda_backend_never_reaches_the_cuda_planner(device_type):
+ """The planner sizes cards through torch.cuda. On XPU or MPS that is either absent or
+ lying, so falling back beats planning against numbers from the wrong device."""
+ ns = _load(
+ device_type = device_type,
+ planner = lambda *a, **k: pytest.fail("CUDA planner on a non-CUDA backend"),
+ )
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == "sequential"
+
+
[email protected]("devices", [0, 1])
+def test_one_gpu_or_none_falls_back_silently(devices):
+ """Not a failure, just nothing to split across, so it prints nothing."""
+ ns = _load(devices = devices, planner = lambda *a, **k: pytest.fail("nothing to plan across"))
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == "sequential"
+
+
+def test_a_planner_that_declines_falls_back():
+ ns = _load(planner = lambda *a, **k: None)
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == "sequential"
+
+
+def test_a_planner_that_raises_falls_back_rather_than_failing_the_load():
+ """A model that loads the old way beats one that will not load at all."""
+
+ def _boom(*a, **k):
+ raise RuntimeError("hub unreachable")
+
+ ns = _load(planner = _boom)
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == "sequential"
+
+
+def test_an_infeasible_plan_is_raised_not_swallowed():
+ """The planner raises this instead of spilling a bitsandbytes model to CPU. Turning it
+ back into "sequential" would hand the user an OOM in place of the diagnosis."""
+
+ class DeviceMapInfeasible(RuntimeError):
+ pass
+
+ def _infeasible(*a, **k):
+ raise DeviceMapInfeasible("needs 7.57 GiB free on cuda:0, has 4.10 GiB")
+
+ ns = _load(planner = _infeasible)
+ with pytest.raises(DeviceMapInfeasible):
+ ns["resolve_unsloth_device_map"]("unsloth", "m")
+
+
+# ------------------------------------------------------------- when it does plan
+
+
+def test_the_plan_is_returned_and_the_model_name_reaches_the_planner():
+ seen = {}
+
+ def _planner(model_name, **kwargs):
+ seen.update(kwargs, model_name = model_name)
+ return _Plan({"": 0, "model.vision_tower": 1})
+
+ ns = _load(planner = _planner)
+ result = ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit",
+ load_in_4bit = True,
+ )
+ assert result == {"": 0, "model.vision_tower": 1}
+ assert seen["model_name"] == "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit"
+ assert seen["load_in_4bit"] is True
+
+
+def test_free_memory_is_planned_against_not_total():
+ """Two 16 GB cards with a CUDA context already resident have far less than 16 GB to
+ give. Planning against total is what made the notebook's first attempt OOM
+ (unsloth-zoo#1048)."""
+ seen = {}
+ ns = _load(
+ free = {0: 4 * 2**30, 1: 15 * 2**30},
+ planner = lambda name, **kw: seen.update(kw) or _Plan({"": 0}),
+ )
+ ns["resolve_unsloth_device_map"]("unsloth", "m")
+ assert seen["max_memory"] == {0: 4 * 2**30, 1: 15 * 2**30}
+ assert 16 * 2**30 not in seen["max_memory"].values(), "that is the total, not the free"
+
+
+def test_planning_happens_only_where_the_model_name_is_final():
+ """loader.py remaps model_name (a -bnb-4bit repo can resolve to its 16-bit twin, and
+ BAD_MAPPINGS rewrites several Qwen3 repos outright) well after its device_map block.
+ A plan built up there is sized for a repo that is not the one loaded, so the call
+ belongs in llama.py and vision.py, where the name has stopped moving.
+ """
+ models = os.path.join(HERE, "unsloth", "models")
+ loader = open(os.path.join(models, "loader.py"), encoding = "utf-8").read()
+ assert (
+ "resolve_unsloth_device_map(" not in loader
+ ), "loader.py plans before get_model_name has had its say"
+ for name in ("llama.py", "vision.py"):
+ source = open(os.path.join(models, name), encoding = "utf-8").read()
+ assert "resolve_unsloth_device_map(" in source, name
+
+
+def test_every_entry_point_accepts_the_planner_kwargs():
+ """FastLanguageModel and FastModel only forward what they were given, so a signature
+ that quietly lacks the parameter turns the notebook's hint into a TypeError."""
+ import ast as _ast
+
+ models = os.path.join(HERE, "unsloth", "models")
+ for name in ("loader.py", "llama.py", "vision.py"):
+ source = open(os.path.join(models, name), encoding = "utf-8").read()
+ found = [
+ node
+ for node in _ast.walk(_ast.parse(source))
+ if isinstance(node, _ast.FunctionDef)
+ and node.name == "from_pretrained"
+ and any(a.arg == "device_map" for a in node.args.args + node.args.kwonlyargs)
+ ]
+ assert found, f"no from_pretrained taking device_map in {name}"
+ for node in found:
+ args = {a.arg for a in node.args.args + node.args.kwonlyargs}
+ assert "device_map_planner_kwargs" in args, f"{name}:{node.lineno}"
+
+
+def test_planner_kwargs_reach_the_planner():
+ """A GRPO backward retains rows the planner's inference-shaped default (0) does not
+ reserve for, so the notebook has to be able to say so."""
+ seen = {}
+ ns = _load(planner = lambda name, **kw: seen.update(kw) or _Plan({"": 0}))
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "m",
+ planner_kwargs = {"rows_per_chunk": 128, "retained_rows": 6144, "softcapped": True},
+ )
+ assert seen["rows_per_chunk"] == 128
+ assert seen["retained_rows"] == 6144
+ assert seen["softcapped"] is True
+
+
+def test_a_user_quantization_config_replaces_the_flags_for_the_planner():
+ """loader.py forwards a caller's `quantization_config` through `**kwargs` and clears
+ `load_in_4bit` / `load_in_8bit`, because transformers refuses both at once. The cleared
+ flags describe a full-precision load, so a 70B QLoRA gets sized at bf16 and
+ `DeviceMapInfeasible` kills a load that would have fit.
+ """
+ ns = _load()
+ config = types.SimpleNamespace(load_in_4bit = True, load_in_8bit = False)
+ kwargs = ns["planner_quantization_kwargs"](
+ load_in_4bit = False,
+ load_in_8bit = False,
+ quantization_config = config,
+ )
+ assert kwargs == {"quantization_config": config}
+ # Both at once is exactly what transformers and the planner reject.
+ assert "load_in_4bit" not in kwargs
+ assert "load_in_8bit" not in kwargs
+
+
[email protected]("four_bit, eight_bit", [(True, False), (False, True)])
+def test_the_flags_are_used_when_no_config_was_given(four_bit, eight_bit):
+ ns = _load()
+ assert ns["planner_quantization_kwargs"](
+ load_in_4bit = four_bit,
+ load_in_8bit = eight_bit,
+ ) == {
+ "load_in_4bit": four_bit,
+ "load_in_8bit": eight_bit,
+ "llm_int8_skip_modules": _SKIP_MODULES,
+ }
+
+
+def test_a_16bit_load_is_planned_without_a_skip_list():
+ """Nothing is being quantized, so there is nothing to keep out of it. A stray
+ llm_int8_skip_modules would reach AutoConfig as an attribute of the model config."""
+ ns = _load()
+ assert ns["planner_quantization_kwargs"]() == {"load_in_4bit": False, "load_in_8bit": False}
+
+
+def test_the_modules_unsloth_keeps_in_compute_dtype_are_sized_that_way():
+ """On-the-fly quantization keeps SKIP_QUANTIZATION_MODULES out of bnb, and transformers
+ reads llm_int8_skip_modules as `modules_to_not_convert`. Planning them at 4bit
+ understates the head device by GiBs on a large-vocab VLM (`lm_head` plus a whole
+ `vision_tower`), the number this plan exists to get right.
+ """
+ seen = {}
+ ns = _load(planner = lambda name, **kw: seen.update(kw) or _Plan({"": 0}))
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "m",
+ **ns["planner_quantization_kwargs"](
+ load_in_4bit = True,
+ extra_skip_modules = ["out_proj"],
+ ),
+ )
+ assert seen["load_in_4bit"] is True
+ assert seen["llm_int8_skip_modules"] == _SKIP_MODULES + ["out_proj"]
+
+
+def test_the_skip_list_is_not_sent_alongside_a_user_config():
+ """The config already carries its own; sending both is what transformers refuses."""
+ ns = _load()
+ kwargs = ns["planner_quantization_kwargs"](
+ quantization_config = types.SimpleNamespace(load_in_4bit = True),
+ extra_skip_modules = ["out_proj"],
+ )
+ assert kwargs == {"quantization_config": kwargs["quantization_config"]}
+
+
+def test_the_config_is_what_reaches_the_planner():
+ seen = {}
+ ns = _load(planner = lambda name, **kw: seen.update(kw) or _Plan({"": 0}))
+ config = types.SimpleNamespace(load_in_4bit = True, load_in_8bit = False)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "m",
+ **ns["planner_quantization_kwargs"](quantization_config = config),
+ )
+ assert seen["quantization_config"] is config
+ assert "load_in_4bit" not in seen
+
+
+def test_the_leaf_loaders_derive_the_planner_quantization_from_the_config():
+ """A bare `load_in_4bit = load_in_4bit` at the call site is the bug above: the leaf
+ receives the flag already cleared by loader.py."""
+ models = os.path.join(HERE, "unsloth", "models")
+ for name in ("llama.py", "vision.py", "diffusion.py"):
+ source = open(os.path.join(models, name), encoding = "utf-8").read()
+ for node in ast.walk(ast.parse(source)):
+ if not (
+ isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "resolve_unsloth_device_map"
+ ):
+ continue
+ keywords = {kw.arg for kw in node.keywords}
+ assert "load_in_4bit" not in keywords, f"{name}:{node.lineno} plans on the cleared flag"
+ assert "load_in_8bit" not in keywords, f"{name}:{node.lineno} plans on the cleared flag"
+ unpacked = [
+ kw.value
+ for kw in node.keywords
+ if kw.arg is None and isinstance(kw.value, ast.Call)
+ ]
+ assert any(
+ getattr(call.func, "id", None) == "planner_quantization_kwargs" for call in unpacked
+ ), f"{name}:{node.lineno}"
+
+
+def _resolve_calls(source):
+ return [
+ node
+ for node in ast.walk(ast.parse(source))
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "resolve_unsloth_device_map"
+ ]
+
+
[email protected]("name", ["llama.py", "vision.py", "diffusion.py"])
+def test_the_planner_sizes_the_dtype_the_load_will_really_use(name):
+ """`from_pretrained`'s dtype overrides the one config.json declares, and the planner
+ only ever sees the config. So a float32 load of a bfloat16 checkpoint is sized at half
+ its real weight bytes, the map is accepted, and materializing it OOMs; the reverse is
+ the same error the other way, raising DeviceMapInfeasible on a load that would have fit.
+
+ `add_dtype_kwargs` rather than a literal keyword: transformers renamed `torch_dtype` to
+ `dtype`, and the planner hands these straight to AutoConfig, which only honours the
+ name its own version knows.
+ """
+ source = open(os.path.join(HERE, "unsloth", "models", name), encoding = "utf-8").read()
+ calls = _resolve_calls(source)
+ assert calls, f"{name} never resolves a device map"
+ for call in calls:
+ unpacked = [
+ kw.value for kw in call.keywords if kw.arg is None and isinstance(kw.value, ast.Call)
+ ]
+ assert any(
+ getattr(unpack.func, "id", None) == "add_dtype_kwargs" for unpack in unpacked
+ ), f"{name}:{call.lineno} plans against the checkpoint's dtype, not the load's"
+
+
+def test_the_diffusion_plan_is_sized_against_the_config_the_load_applies():
+ """diffusion.py keeps `lm_head`, `embed_tokens`, `experts`, `self_conditioning` and
+ `router` out of bnb, most of an MoE checkpoint's parameters. Planning on the bare flags
+ sizes all of them at 4 bits while the load materializes them in compute dtype, so the
+ one config object is built before the plan and reused by the load.
+ """
+ path = os.path.join(HERE, "unsloth", "models", "diffusion.py")
+ source = open(path, encoding = "utf-8").read()
+ tree = ast.parse(source)
+
+ built = [
+ node.lineno
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Assign)
+ and getattr(node.value, "func", None) is not None
+ and getattr(node.value.func, "id", None) == "BitsAndBytesConfig"
+ and any(getattr(target, "id", None) == "qcfg" for target in node.targets)
+ ]
+ assert built, "diffusion.py no longer builds its own BitsAndBytesConfig"
+
+ calls = _resolve_calls(source)
+ assert calls, "diffusion.py never resolves a device map"
+ for call in calls:
+ assert (
+ max(built) < call.lineno
+ ), f"diffusion.py:{call.lineno} plans before the quantization config exists"
+ forwarded = [
+ unpack
+ for unpack in (
+ kw.value
+ for kw in call.keywords
+ if kw.arg is None and isinstance(kw.value, ast.Call)
+ )
+ if getattr(unpack.func, "id", None) == "planner_quantization_kwargs"
+ ]
+ assert forwarded, f"diffusion.py:{call.lineno} plans without the load's quantization"
+ for unpack in forwarded:
+ passed = {kw.arg: ast.unparse(kw.value) for kw in unpack.keywords}
+ assert (
+ passed.get("quantization_config") == "qcfg"
+ ), f"diffusion.py:{call.lineno} plans without the skip list the load applies"
diff --git a/tests/test_unsloth_device_map_platform_matrix.py b/tests/test_unsloth_device_map_platform_matrix.py
new file mode 100644
index 00000000000..c9cdecf1634
--- /dev/null
+++ b/tests/test_unsloth_device_map_platform_matrix.py
@@ -0,0 +1,452 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The opt-in device map, over the whole product of host and accelerator.
+
+test_unsloth_device_map_optin.py checks each decline path once. This file checks that the
+three properties that make the change safe hold across every combination of them at once,
+because the risk is not one path being wrong, it is one *combination* being wrong on a
+machine none of us has:
+
+ 1. Nothing that is not the sentinel is touched. Every device_map an existing caller can
+ pass comes back identical, whatever the host and whatever the accelerator.
+ 2. The sentinel never escapes. `resolve_unsloth_device_map` never returns "unsloth" --
+ transformers turns an unknown device_map string into `torch.device("unsloth")` and
+ raises, so a leak is a hard load failure rather than a bad placement.
+ 3. The planner is called only where a plan can apply, and never otherwise.
+
+The host axis is Linux / Windows / WSL / macOS and the accelerator axis is NVIDIA (cuda),
+AMD (cuda, since torch's ROCm build reports itself as cuda), Intel (xpu), Apple (mps) and
+CPU. `resolve_unsloth_device_map` does not read the platform itself, which is the point:
+these spoofs exist to prove no platform-specific branch grew in underneath it.
+
+Extracted with ast so nothing has to import torch's CUDA stack.
+"""
+
+import ast
+import itertools
+import os
+import sys
+import types
+
+import pytest
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+LOADER_UTILS = os.path.join(HERE, "unsloth", "models", "loader_utils.py")
+_SRC = open(LOADER_UTILS, encoding = "utf-8").read()
+
+# (label, sys.platform, os.name, an /proc/version marker for the WSL case)
+HOSTS = [
+ ("linux", "linux", "posix", "Linux version 6.8.0-generic"),
+ ("windows", "win32", "nt", None),
+ ("wsl", "linux", "posix", "Linux version 5.15.0-microsoft-standard-WSL2"),
+ ("macos", "darwin", "posix", None),
+]
+
+# (label, DEVICE_TYPE_TORCH). A ROCm torch build reports "cuda", so AMD is not a separate
+# branch in the resolver -- it is here so a future one cannot be added unnoticed.
+ACCELERATORS = [
+ ("nvidia", "cuda"),
+ ("amd", "cuda"),
+ ("intel", "xpu"),
+ ("apple", "mps"),
+ ("cpu", "cpu"),
+]
+
+DEVICE_COUNTS = [0, 1, 2, 8]
+
+# Everything a caller can hand the loader today. None is included because
+# `FastDiffusionModel.from_pretrained` lets the caller clear it.
+UNTOUCHED_DEVICE_MAPS = [
+ "sequential",
+ "auto",
+ "balanced",
+ "balanced_low_0",
+ "cuda:0",
+ "cuda:1",
+ "cpu",
+ "mps",
+ "xpu:0",
+ None,
+ 0,
+ {"": 0},
+ {"": "cuda:0"},
+ {"model.embed_tokens": 0, "lm_head": 1},
+]
+
+
+class _FakeCuda:
+ def __init__(
+ self,
+ count,
+ count_raises = None,
+ mem_raises = None,
+ ):
+ self._count = count
+ self._count_raises = count_raises
+ self._mem_raises = mem_raises
+
+ def device_count(self):
+ if self._count_raises is not None:
+ raise self._count_raises
+ return self._count
+
+ def mem_get_info(self, index):
+ if self._mem_raises is not None:
+ raise self._mem_raises
+ return (8 * 2**30, 16 * 2**30)
+
+
+class _Recorder:
+ """Stands in for unsloth_zoo's planner and records whether it was consulted."""
+
+ def __init__(
+ self,
+ plan = None,
+ raises = None,
+ ):
+ self.calls = []
+ self._plan = plan
+ self._raises = raises
+
+ def __call__(self, model_name, **kwargs):
+ self.calls.append((model_name, kwargs))
+ if self._raises is not None:
+ raise self._raises
+ return self._plan
+
+
+class _Plan:
+ device_map = {"model.embed_tokens": 0, "lm_head": 1}
+
+ def describe(self):
+ return "<plan>"
+
+
+def _build(
+ *,
+ device_type,
+ devices,
+ distributed,
+ planner,
+ planner_available = True,
+ count_raises = None,
+ mem_raises = None,
+):
+ """Rebuild the resolver over a fabricated torch, unsloth_zoo and host."""
+ ns = {
+ "os": os,
+ "torch": types.SimpleNamespace(
+ cuda = _FakeCuda(devices, count_raises = count_raises, mem_raises = mem_raises)
+ ),
+ "DEVICE_TYPE_TORCH": device_type,
+ "is_distributed": lambda: distributed,
+ }
+ for node in ast.parse(_SRC).body:
+ if isinstance(node, ast.FunctionDef) and node.name in (
+ "requested_device_map",
+ "resolve_unsloth_device_map",
+ "_as_bytes",
+ ):
+ exec(ast.get_source_segment(_SRC, node), ns)
+ elif isinstance(node, ast.ClassDef) and node.name == "_DefaultDeviceMap":
+ exec(ast.get_source_segment(_SRC, node), ns)
+ elif isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) in (
+ "UNSLOTH_DEVICE_MAP",
+ "DEFAULT_DEVICE_MAP",
+ "_SIZE_UNITS",
+ ):
+ exec(ast.get_source_segment(_SRC, node), ns)
+
+ planner_module = types.ModuleType("unsloth_zoo.device_map_planner")
+ if planner_available:
+ planner_module.plan_device_map_for_pretrained = planner
+ sys.modules["unsloth_zoo.device_map_planner"] = planner_module
+ return ns
+
+
+def host(request, monkeypatch):
+ """Spoof the operating system around a case, so a platform branch cannot hide."""
+ label, platform_name, os_name, proc_version = request.param
+ monkeypatch.setattr(sys, "platform", platform_name, raising = False)
+ monkeypatch.setattr(os, "name", os_name, raising = False)
+ monkeypatch.setenv("UNSLOTH_TEST_HOST", label)
+ if proc_version is not None:
+ monkeypatch.setenv("UNSLOTH_TEST_PROC_VERSION", proc_version)
+ return label
+
+
+_HOST_IDS = [h[0] for h in HOSTS]
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
[email protected]("accelerator,device_type", ACCELERATORS, ids = [a[0] for a in ACCELERATORS])
[email protected]("devices", DEVICE_COUNTS)
[email protected]("device_map", UNTOUCHED_DEVICE_MAPS, ids = repr)
+def test_an_existing_device_map_is_identical_on_every_host(
+ host, accelerator, device_type, devices, device_map, monkeypatch
+):
+ """Property 1. 4 hosts x 5 accelerators x 4 GPU counts x 14 placements = 1120 cases,
+ none of which may differ by so much as an object identity from what main returns."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ planner = _Recorder(plan = _Plan())
+ ns = _build(device_type = device_type, devices = devices, distributed = False, planner = planner)
+ resolved = ns["resolve_unsloth_device_map"](
+ ns["requested_device_map"](device_map), "unsloth/Qwen3-0.6B"
+ )
+ assert resolved is device_map
+ assert planner.calls == []
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
[email protected]("accelerator,device_type", ACCELERATORS, ids = [a[0] for a in ACCELERATORS])
[email protected]("devices", DEVICE_COUNTS)
[email protected]("distributed", [False, True])
[email protected]("fast_inference", [False, True])
[email protected]("full_finetuning", [False, True])
[email protected]("planner_available", [False, True])
+def test_the_sentinel_never_reaches_transformers(
+ host,
+ accelerator,
+ device_type,
+ devices,
+ distributed,
+ fast_inference,
+ full_finetuning,
+ planner_available,
+ monkeypatch,
+):
+ """Property 2, the one that decides whether this can break a load anywhere.
+
+ Whatever the host, the accelerator, the GPU count, the launcher, the vLLM/full-finetune
+ flags, and whether unsloth_zoo is new enough to have a planner at all, the resolved
+ value is either a placement transformers understands or a plan dict. Never "unsloth".
+ """
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ device_type = device_type,
+ devices = devices,
+ distributed = distributed,
+ planner = planner,
+ planner_available = planner_available,
+ )
+ resolved = ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ fast_inference = fast_inference,
+ full_finetuning = full_finetuning,
+ )
+ assert resolved != "unsloth"
+ assert resolved == "sequential" or isinstance(resolved, dict)
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
[email protected]("accelerator,device_type", ACCELERATORS, ids = [a[0] for a in ACCELERATORS])
[email protected]("devices", DEVICE_COUNTS)
[email protected]("distributed", [False, True])
+def test_the_planner_runs_exactly_where_a_plan_can_apply(
+ host, accelerator, device_type, devices, distributed, monkeypatch
+):
+ """Property 3, stated as the whole truth table rather than one path at a time."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ device_type = device_type,
+ devices = devices,
+ distributed = distributed,
+ planner = planner,
+ )
+ resolved = ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B")
+
+ should_plan = device_type == "cuda" and devices >= 2 and not distributed
+ assert bool(planner.calls) is should_plan
+ if should_plan:
+ assert resolved == _Plan.device_map
+ else:
+ assert resolved == "sequential"
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
[email protected]("accelerator,device_type", ACCELERATORS, ids = [a[0] for a in ACCELERATORS])
[email protected]("devices", DEVICE_COUNTS)
[email protected]("value", ["0", "", "false", "no", "true", "1"])
+def test_the_env_var_opts_in_on_1_and_nothing_else(
+ host, accelerator, device_type, devices, value, monkeypatch
+):
+ """`UNSLOTH_AUTO_DEVICE_MAP` is an operator switch, so a half-set one must be off, not
+ ambiguous. Only the literal "1" upgrades, on every host -- and only the default, never
+ the same string handed over by a caller who meant it."""
+ monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", value)
+ planner = _Recorder(plan = _Plan())
+ ns = _build(device_type = device_type, devices = devices, distributed = False, planner = planner)
+ requested = ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"])
+ assert requested == ("unsloth" if value == "1" else "sequential")
+ assert ns["resolve_unsloth_device_map"](requested, "unsloth/Qwen3-0.6B") != "unsloth"
+ assert ns["requested_device_map"]("sequential") == "sequential"
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
+def test_an_old_unsloth_zoo_without_a_planner_still_loads(host, monkeypatch):
+ """An install that predates unsloth_zoo's planner must degrade, not fail: the whole
+ point of the fallback is that a model which loads the old way beats one that will not
+ load. Two shapes of old: the module is missing, and the module exists without the
+ entry point."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+
+ # Shape one: the module is there but predates the entry point.
+ ns = _build(
+ device_type = "cuda", devices = 4, distributed = False, planner = None, planner_available = False
+ )
+ assert ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B") == "sequential"
+
+ # Shape two: no such module. Block the import rather than deleting it from sys.modules,
+ # which on a machine that has the real planner installed just imports it again.
+ class _Blocked:
+ def find_module(
+ self,
+ name,
+ path = None,
+ ):
+ return None
+
+ def find_spec(
+ self,
+ name,
+ path = None,
+ target = None,
+ ):
+ if name == "unsloth_zoo.device_map_planner":
+ raise ModuleNotFoundError(f"No module named {name!r}")
+ return None
+
+ ns = _build(device_type = "cuda", devices = 4, distributed = False, planner = None)
+ sys.modules.pop("unsloth_zoo.device_map_planner", None)
+ blocker = _Blocked()
+ sys.meta_path.insert(0, blocker)
+ try:
+ assert ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B") == "sequential"
+ finally:
+ sys.meta_path.remove(blocker)
+ sys.modules.pop("unsloth_zoo.device_map_planner", None)
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
+ "error",
+ [
+ RuntimeError("planner blew up"),
+ ValueError("bad config"),
+ OSError("no network"),
+ KeyError("lm_head"),
+ ],
+ ids = ["runtime", "value", "os", "key"],
+)
+def test_a_planner_that_raises_anything_but_infeasible_falls_back(host, error, monkeypatch):
+ """Everything except the deliberate refusal degrades to the old placement."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ planner = _Recorder(raises = error)
+ ns = _build(device_type = "cuda", devices = 2, distributed = False, planner = planner)
+ assert ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B") == "sequential"
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
+def test_the_deliberate_refusal_is_not_swallowed(host, monkeypatch):
+ """`DeviceMapInfeasible` is the planner declining to place a model that would OOM.
+ Turning it into "sequential" would hand the user the OOM instead of the diagnosis.
+ Matched by name, because an old unsloth_zoo may not export the class."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+
+ class DeviceMapInfeasible(RuntimeError):
+ pass
+
+ planner = _Recorder(raises = DeviceMapInfeasible("2 x 8 GiB is not enough"))
+ ns = _build(device_type = "cuda", devices = 2, distributed = False, planner = planner)
+ with pytest.raises(DeviceMapInfeasible):
+ ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B")
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
+ "error",
+ [
+ RuntimeError("CUDA error: uncorrectable ECC error encountered"),
+ RuntimeError("CUDA error: all CUDA-capable devices are busy or unavailable"),
+ RuntimeError("CUDA driver initialization failed"),
+ ],
+ ids = ["ecc", "exclusive-process", "driver"],
+)
+def test_a_card_that_refuses_to_report_memory_does_not_fail_the_load(host, error, monkeypatch):
+ """Reading free memory is itself a CUDA call on every visible device, and it is the
+ first thing this function does that can touch a broken one: an ECC-fenced card, a MIG
+ parent handle, or a GPU another process holds in Exclusive_Process mode. That must
+ degrade to the placement the caller would have had anyway, for the same reason a
+ planner exception does. Nothing here is the deliberate refusal, which still raises."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ device_type = "cuda",
+ devices = 4,
+ distributed = False,
+ planner = planner,
+ mem_raises = error,
+ )
+ assert ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B") == "sequential"
+ assert planner.calls == []
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
+def test_a_device_count_that_raises_does_not_fail_the_load(host, monkeypatch):
+ """Same reasoning one call earlier. `device_count()` swallows most driver faults and
+ answers 0, but not all of them, and a load with a working `sequential` placement should
+ not die because the count could not be taken."""
+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ device_type = "cuda",
+ devices = 4,
+ distributed = False,
+ planner = planner,
+ count_raises = RuntimeError("CUDA unknown error"),
+ )
+ assert ns["resolve_unsloth_device_map"]("unsloth", "unsloth/Qwen3-0.6B") == "sequential"
+ assert planner.calls == []
+
+
+def _planner_quantization_kwargs():
+ ns = {"os": os}
+ for node in ast.parse(_SRC).body:
+ if isinstance(node, ast.FunctionDef) and node.name == "planner_quantization_kwargs":
+ exec(ast.get_source_segment(_SRC, node), ns)
+ return ns["planner_quantization_kwargs"]
+
+
[email protected]("host", HOSTS, ids = _HOST_IDS, indirect = True)
[email protected]("four_bit,eight_bit", [(True, False), (False, True)], ids = ["4bit", "8bit"])
+def test_a_zoo_without_the_shared_skip_list_still_loads_in_4bit(host, four_bit, eight_bit):
+ """The leaf loaders evaluate these arguments on every quantized load, whether or not
+ anything is going to be planned. So the one import in here is on the hot path of every
+ 4bit load in the library, and an unsloth_zoo below our pin has to degrade to "no skip
+ list" rather than take the load down with an ImportError."""
+ build = _planner_quantization_kwargs()
+
+ peft_utils = types.ModuleType("unsloth_zoo.peft_utils") # no SKIP_QUANTIZATION_MODULES
+ saved = sys.modules.get("unsloth_zoo.peft_utils")
+ sys.modules["unsloth_zoo.peft_utils"] = peft_utils
+ try:
+ kwargs = build(load_in_4bit = four_bit, load_in_8bit = eight_bit)
+ finally:
+ if saved is None:
+ sys.modules.pop("unsloth_zoo.peft_utils", None)
+ else:
+ sys.modules["unsloth_zoo.peft_utils"] = saved
+
+ assert kwargs == {"load_in_4bit": four_bit, "load_in_8bit": eight_bit}
+
+
+def test_the_matrix_is_actually_the_product_we_claim():
+ """A guard on the guard: if someone trims a list above, the coverage claim in the
+ docstrings should stop being true loudly rather than quietly."""
+ assert len(list(itertools.product(HOSTS, ACCELERATORS, DEVICE_COUNTS))) == 80
+ assert len(UNTOUCHED_DEVICE_MAPS) == 14
diff --git a/tests/test_unsloth_device_map_review_fixes.py b/tests/test_unsloth_device_map_review_fixes.py
new file mode 100644
index 00000000000..d27034296fc
--- /dev/null
+++ b/tests/test_unsloth_device_map_review_fixes.py
@@ -0,0 +1,548 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Four review findings on the opt-in device map, each pinned by the failure it caused.
+
+Kept apart from the other two device-map files because these are regressions, not the
+feature's own contract: every test here fails on the code as it was reviewed.
+
+Extracted with ast so nothing has to import torch's CUDA stack.
+"""
+
+import ast
+import os
+import sys
+import types
+
+import pytest
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MODELS = os.path.join(HERE, "unsloth", "models")
+LOADER_UTILS = os.path.join(MODELS, "loader_utils.py")
+_SRC = open(LOADER_UTILS, encoding = "utf-8").read()
+
+
+class _FakeCuda:
+ def __init__(
+ self,
+ count,
+ free,
+ refuses = (),
+ ):
+ self._count = count
+ self._free = free
+ self._refuses = set(refuses)
+ self.probed = []
+
+ def device_count(self):
+ return self._count
+
+ def mem_get_info(self, index):
+ self.probed.append(index)
+ if index in self._refuses:
+ raise RuntimeError(f"CUDA error: device {index} is in Exclusive_Process mode")
+ return (self._free.get(index, 8 * 2**30), 16 * 2**30)
+
+
+class _Recorder:
+ def __init__(self, plan = None):
+ self.calls = []
+ self._plan = plan
+
+ def __call__(self, model_name, **kwargs):
+ self.calls.append((model_name, kwargs))
+ return self._plan
+
+
+class _Plan:
+ device_map = {"model.embed_tokens": 0, "lm_head": 1}
+
+ def describe(self):
+ return "<plan>"
+
+
+def _build(
+ *,
+ devices = 2,
+ free = None,
+ planner = None,
+ refuses = (),
+):
+ cuda = _FakeCuda(devices, free or {}, refuses = refuses)
+ ns = {
+ "os": os,
+ "torch": types.SimpleNamespace(cuda = cuda),
+ "DEVICE_TYPE_TORCH": "cuda",
+ "is_distributed": lambda: False,
+ }
+ for node in ast.parse(_SRC).body:
+ keep = (
+ (
+ isinstance(node, ast.FunctionDef)
+ and node.name
+ in (
+ "requested_device_map",
+ "resolve_unsloth_device_map",
+ "_as_bytes",
+ "unmarked_device_map",
+ )
+ )
+ or (isinstance(node, ast.ClassDef) and node.name == "_DefaultDeviceMap")
+ or (
+ isinstance(node, ast.Assign)
+ and getattr(node.targets[0], "id", None)
+ in ("UNSLOTH_DEVICE_MAP", "DEFAULT_DEVICE_MAP", "_SIZE_UNITS")
+ )
+ )
+ if keep:
+ exec(ast.get_source_segment(_SRC, node), ns)
+ module = types.ModuleType("unsloth_zoo.device_map_planner")
+ module.plan_device_map_for_pretrained = planner
+ sys.modules["unsloth_zoo.device_map_planner"] = module
+ ns["_cuda"] = cuda
+ return ns
+
+
+# --------------------------------------------------------------------------------------
+# 1. An explicit "sequential" is a placement, not the default.
+# --------------------------------------------------------------------------------------
+
+
+def test_the_env_opt_in_leaves_an_explicitly_requested_sequential_alone(monkeypatch):
+ """`UNSLOTH_AUTO_DEVICE_MAP=1` upgraded every "sequential", including one the caller
+ typed out, so a caller who needs accelerate's greedy fill got a head-aware split."""
+ monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", "1")
+ ns = _build()
+ assert ns["requested_device_map"]("sequential") == "sequential"
+ assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == "unsloth"
+
+
+def test_the_default_is_indistinguishable_from_sequential_to_everyone_else():
+ """The marker may not change what the value IS: it is the documented default, it is
+ handed to transformers, and it is printed in signatures and docs."""
+ ns = _build()
+ default = ns["DEFAULT_DEVICE_MAP"]
+ assert default == "sequential"
+ assert str(default) == "sequential"
+ assert isinstance(default, str)
+ assert hash(default) == hash("sequential")
+ assert {default: 1}["sequential"] == 1
+ assert f"{default}" == "sequential"
+
+
[email protected]("name", ["loader.py", "llama.py", "vision.py", "sentence_transformer.py"])
+def test_every_entry_point_defaults_to_the_marked_value(name):
+ """A signature left on the bare string cannot be told from an explicit request, so the
+ fix above would silently not apply to whichever loader was missed."""
+ source = open(os.path.join(MODELS, name), encoding = "utf-8").read()
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.FunctionDef) or node.name != "from_pretrained":
+ continue
+ args = node.args
+ defaults = (
+ dict(zip([a.arg for a in args.args][-len(args.defaults) :], args.defaults))
+ if args.defaults
+ else {}
+ )
+ defaults.update(
+ {a.arg: d for a, d in zip(args.kwonlyargs, args.kw_defaults) if d is not None}
+ )
+ if "device_map" not in defaults:
+ continue
+ rendered = ast.unparse(defaults["device_map"])
+ assert rendered != "'sequential'", (
+ f"{name}:{node.lineno} defaults device_map to the bare string, so the env "
+ f"opt-in cannot tell it from a caller who asked for sequential"
+ )
+
+
+def test_sentence_transformers_hands_the_nested_load_a_plain_value():
+ """It declines planning for itself, then calls FastModel. Passing the marked default on
+ would let that nested load re-upgrade it and split a model ST then pulls onto one card.
+
+ Asserted as the absence of the old process-wide pin as well: os.environ is shared, so
+ that fix reached unrelated loads on other threads.
+ """
+ source = open(os.path.join(MODELS, "sentence_transformer.py"), encoding = "utf-8").read()
+ assert "device_map = unmarked_device_map(device_map)" in source
+ assert (
+ "device_map = str(device_map)" not in source
+ ), "a bare str() also stringifies an explicit dict placement into \"{'': 0}\""
+ assert (
+ 'os.environ["UNSLOTH_AUTO_DEVICE_MAP"]' not in source
+ ), "the process-wide pin is back; it is visible to every other thread"
+
+
+# --------------------------------------------------------------------------------------
+# 2. max_memory arrived twice.
+# --------------------------------------------------------------------------------------
+
+
+def test_a_caller_supplied_max_memory_does_not_collide_with_the_measured_one():
+ """`max_memory` is a named parameter of the planner, so leaving the caller's copy in
+ the forwarded kwargs raised `TypeError: got multiple values for keyword argument
+ 'max_memory'` -- caught by the handler and turned into a silent "sequential", losing
+ both the cap and the plan."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 10 * 2**30, 1: 10 * 2**30}, planner = planner)
+ resolved = ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: 4 * 2**30, 1: 10 * 2**30}, "retained_rows": 128},
+ )
+ assert resolved == _Plan.device_map, "the plan was lost to a TypeError"
+ assert len(planner.calls) == 1
+ _, kwargs = planner.calls[0]
+ assert kwargs["retained_rows"] == 128
+ assert kwargs["max_memory"][0] == 4 * 2**30
+
+
+def test_a_cap_above_free_memory_does_not_raise_the_budget():
+ """A caller can reserve room we cannot measure, but cannot conjure memory the card has
+ not got, and planning above free is how a plan OOMs on dispatch."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 2 * 2**30, 1: 2 * 2**30}, planner = planner)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: 99 * 2**30, 1: 99 * 2**30}},
+ )
+ assert planner.calls[0][1]["max_memory"][0] == 2 * 2**30
+
+
+ "written,expected",
+ [(4 * 2**30, 4 * 2**30), ("4GiB", 4 * 2**30), ("2MiB", 2 * 2**20)],
+ ids = ["int", "GiB", "MiB"],
+)
+def test_the_cap_is_read_the_way_accelerate_reads_it(written, expected):
+ """accelerate takes `"10GiB"` as readily as an int, so a caller writes what the loader
+ would have taken. Comparing a string against measured bytes would be meaningless."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 8 * 2**30, 1: 8 * 2**30}, planner = planner)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: written, 1: written}},
+ )
+ assert planner.calls[0][1]["max_memory"][0] == min(expected, 8 * 2**30)
+
+
+def test_the_cap_is_read_without_needing_accelerate_importable():
+ """Reading the budget through `accelerate.utils.modeling.convert_file_size_to_int` made
+ the cap conditional on an import that runs while placement is still being decided: on an
+ install without accelerate, or one that moves the symbol, every budget came back
+ unreadable and the caller's cap was dropped in silence. Found by the cross-platform run,
+ whose runners carry pytest and the Studio requirements but no accelerate."""
+ import builtins
+
+ as_bytes = _build()["_as_bytes"]
+ real_import = builtins.__import__
+
+ def no_accelerate(name, *args, **kwargs):
+ if name.split(".")[0] == "accelerate":
+ raise ImportError("No module named 'accelerate'")
+ return real_import(name, *args, **kwargs)
+
+ builtins.__import__ = no_accelerate
+ try:
+ assert as_bytes("4GiB") == 4 * 2**30
+ assert as_bytes(4 * 2**30) == 4 * 2**30
+ finally:
+ builtins.__import__ = real_import
+
+
+ "written",
+ [
+ 0,
+ 1,
+ 4 * 2**30,
+ "0GiB",
+ "4GiB",
+ "2MiB",
+ "512KiB",
+ "1.5GiB",
+ "0.5MiB",
+ "4gib",
+ "4GIB",
+ "4Gib",
+ "10GB",
+ "10gb",
+ "10Gb",
+ "8MB",
+ "8Mb",
+ "900KB",
+ "900Kb",
+ "1.5GB",
+ ".5GB",
+ "1e3MB",
+ "not a size",
+ "",
+ "GiB",
+ "-4GiB",
+ -1,
+ "4 GiB",
+ "4GiBs",
+ "4G",
+ "4B",
+ "4",
+ None,
+ 3.5,
+ (),
+ {"0": 1},
+ ],
+)
+def test_the_local_size_parser_agrees_with_accelerate(written):
+ """The rules are reproduced rather than imported, so something has to hold the copy in
+ step with the original wherever the original is in fact installed. accelerate raises on
+ what it cannot read and we return None, which is the same answer to the one caller."""
+ accelerate_modeling = pytest.importorskip("accelerate.utils.modeling")
+ try:
+ theirs = accelerate_modeling.convert_file_size_to_int(written)
+ except Exception:
+ theirs = None
+ assert _build()["_as_bytes"](written) == theirs
+
+
+def test_an_unreadable_cap_leaves_the_measured_value_rather_than_dropping_the_device():
+ """A device missing from `max_memory` is a device the planner may not use at all, which
+ is a worse answer than ignoring one unparseable entry."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 8 * 2**30, 1: 8 * 2**30}, planner = planner)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: "not a size", 1: "not a size"}},
+ )
+ assert planner.calls[0][1]["max_memory"][0] == 8 * 2**30
+
+
+def test_the_callers_kwargs_dict_is_not_mutated():
+ """`device_map_planner_kwargs` is the caller's object, and a loader that empties it
+ would change what a second load in the same script asks for."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 8 * 2**30, 1: 8 * 2**30}, planner = planner)
+ caller_kwargs = {"max_memory": {0: 4 * 2**30, 1: 4 * 2**30}, "retained_rows": 8}
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = caller_kwargs,
+ )
+ assert caller_kwargs == {"max_memory": {0: 4 * 2**30, 1: 4 * 2**30}, "retained_rows": 8}
+
+
+# --------------------------------------------------------------------------------------
+# 3. The legacy diffusion checkpoint the planner cannot rebuild.
+# --------------------------------------------------------------------------------------
+
+
+def test_the_legacy_diffusion_alias_declines_planning_with_its_own_reason():
+ """`diffusion_gemma` loads only because `_load_diffusion_config` catches AutoConfig's
+ unknown-model error and rewrites the type in memory. The planner is given a name, not a
+ config, so it rebuilds from the checkpoint and hits the same error -- reported as a
+ generic planning failure. It has to say what actually happened."""
+ source = open(os.path.join(MODELS, "diffusion.py"), encoding = "utf-8").read()
+ tree = ast.parse(source)
+
+ assert (
+ "_unsloth_legacy_alias = True" in source
+ ), "nothing records that the alias was applied, so the planner call cannot know"
+
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ if getattr(node.func, "id", None) != "resolve_unsloth_device_map":
+ continue
+ reasons = [kw for kw in node.keywords if kw.arg == "skip_reason"]
+ assert reasons, f"diffusion.py:{node.lineno} plans without vetoing the legacy alias"
+ rendered = ast.unparse(reasons[0].value)
+ assert "_unsloth_legacy_alias" in rendered
+ assert "diffusion_gemma" in rendered
+ return
+ raise AssertionError("no resolve_unsloth_device_map call in diffusion.py")
+
+
+# --------------------------------------------------------------------------------------
+# 4. Second round: the caller's device set, the marker, and the prequantized skip list.
+# --------------------------------------------------------------------------------------
+
+
+def test_the_caller_max_memory_keys_are_the_devices_the_load_may_use():
+ """A caller who writes `{0: ..., 1: ...}` on a four-GPU host is reserving GPUs 2 and 3
+ for something else. accelerate reads a supplied mapping that way -- its
+ `_init_infer_auto_device_map` takes `devices = list(max_memory.keys())` and
+ `get_max_memory` never widens the mapping back out -- so overlaying the caps onto every
+ visible card left the planner free to place weights on the two they had withheld."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ devices = 4,
+ free = {i: 16 * 2**30 for i in range(4)},
+ planner = planner,
+ )
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: "12GiB", 1: "12GiB"}},
+ )
+ assert sorted(planner.calls[0][1]["max_memory"]) == [0, 1]
+
+
+def test_a_device_the_caller_names_but_we_cannot_measure_survives():
+ """`cpu` and `disk` are legitimate `max_memory` keys and there is no `mem_get_info` for
+ them, so an intersection that kept only measured devices would silently delete the
+ offload targets the caller set up."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 8 * 2**30, 1: 8 * 2**30}, planner = planner)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {
+ "max_memory": {0: "4GiB", 1: "4GiB", "cpu": "30GiB", "disk": "unreadable"},
+ },
+ )
+ budgets = planner.calls[0][1]["max_memory"]
+ assert budgets[0] == 4 * 2**30
+ assert budgets["cpu"] == 30 * 2**30
+ # Unreadable and unmeasured: theirs, verbatim, for the planner to make sense of.
+ assert budgets["disk"] == "unreadable"
+
+
+def test_an_empty_max_memory_is_not_a_request_to_use_no_devices():
+ """`{}` carries no device set to honour, and reading it as one would leave the planner
+ with nothing to place on."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(free = {0: 8 * 2**30, 1: 8 * 2**30}, planner = planner)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {}},
+ )
+ assert sorted(planner.calls[0][1]["max_memory"]) == [0, 1]
+
+
+ "placement",
+ [
+ {"": 0, "model": 1},
+ {"": "cuda:0"},
+ "auto",
+ "balanced",
+ "cuda:0",
+ None,
+ ],
+)
+def test_only_the_marker_is_stringified_on_the_way_to_the_nested_load(placement):
+ """`str()` on the marked default is the point; `str()` on a dict turns an explicit
+ placement into the text `"{'': 0, 'model': 1}"`, which transformers reads as a device
+ name and rejects."""
+ ns = _build()
+ assert ns["unmarked_device_map"](placement) is placement
+
+
+def test_the_marker_still_arrives_at_the_nested_load_as_a_plain_string():
+ ns = _build()
+ plain = ns["unmarked_device_map"](ns["DEFAULT_DEVICE_MAP"])
+ assert plain == "sequential"
+ assert type(plain) is str
+
+
+def test_a_prequantized_hybrid_checkpoint_declines_rather_than_mis_sizing_mamba():
+ """`merge_quantization_configs` overlays loading attributes for GPTQ/AWQ/... but never
+ for bitsandbytes, so a prequantized checkpoint is sized by the list in its own
+ config.json no matter what the loader passes. The mamba exclusions the load adds
+ afterwards would then be charged at 4bit while the load keeps them dense."""
+ source = open(os.path.join(MODELS, "llama.py"), encoding = "utf-8").read()
+ tree = ast.parse(source)
+
+ guard_line = None
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If):
+ continue
+ rendered = ast.unparse(node)
+ if "IS_FALCON_H1" in rendered and "llm_int8_skip_modules" in rendered:
+ guard_line = node.lineno
+ break
+ assert guard_line is not None, "nothing guards the plan against the unbundled exclusions"
+
+ plan_line = None
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "resolve_unsloth_device_map"
+ ):
+ plan_line = node.lineno
+ break
+ assert plan_line is not None
+ assert guard_line < plan_line, (
+ f"llama.py:{guard_line} decides the skip-list gap after llama.py:{plan_line} has "
+ f"already planned, so the plan is built before the veto exists"
+ )
+
+
+# --------------------------------------------------------------------------------------
+# 5. Probing is not free: a withheld card must not be touched.
+# --------------------------------------------------------------------------------------
+
+
+def test_gpus_the_caller_withheld_are_never_probed():
+ """`mem_get_info` initialises a CUDA context on each device it touches, and a card the
+ caller withheld is very likely busy with the workload they withheld it for."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(devices = 4, free = {i: 16 * 2**30 for i in range(4)}, planner = planner)
+ ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: "12GiB", 1: "12GiB"}},
+ )
+ assert sorted(ns["_cuda"].probed) == [0, 1]
+
+
+def test_a_refusing_card_outside_the_requested_set_does_not_cost_the_plan():
+ """Dropping to "sequential" because GPU 3 is in Exclusive_Process mode is the wrong
+ answer when the caller asked for GPUs 0 and 1 -- and "sequential" is the placement that
+ then OOMs."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ devices = 4,
+ free = {i: 16 * 2**30 for i in range(4)},
+ planner = planner,
+ refuses = (2, 3),
+ )
+ resolved = ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: "12GiB", 1: "12GiB"}},
+ )
+ assert resolved == _Plan.device_map
+
+
+def test_a_refusing_card_inside_the_requested_set_still_falls_back():
+ """The guard is still needed for the cards the caller did ask for."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(
+ devices = 4,
+ free = {i: 16 * 2**30 for i in range(4)},
+ planner = planner,
+ refuses = (1,),
+ )
+ resolved = ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: "12GiB", 1: "12GiB"}},
+ )
+ assert resolved == "sequential"
+
+
+def test_restricting_to_one_gpu_is_not_a_multi_gpu_plan():
+ """A single-card device set has nothing to split across, and the planner is not asked."""
+ planner = _Recorder(plan = _Plan())
+ ns = _build(devices = 4, free = {i: 16 * 2**30 for i in range(4)}, planner = planner)
+ resolved = ns["resolve_unsloth_device_map"](
+ "unsloth",
+ "unsloth/Qwen3-0.6B",
+ planner_kwargs = {"max_memory": {0: "12GiB"}},
+ )
+ assert resolved == "sequential"
+ assert planner.calls == []
+ assert ns["_cuda"].probed == []
diff --git a/unsloth/models/diffusion.py b/unsloth/models/diffusion.py
index 85026802d87..e2bdcd597d4 100644
--- a/unsloth/models/diffusion.py
+++ b/unsloth/models/diffusion.py
@@ -23,9 +23,15 @@ bit-identical to transformers), keeping only the safe conveniences: 4bit/8bit lo
import os
import torch
from transformers import AutoConfig, AutoProcessor, AutoTokenizer
+from unsloth_zoo.hf_utils import add_dtype_kwargs
from ._utils import is_bfloat16_supported, maybe_prefetch_hf_snapshot
from .llama import logger
+from .loader_utils import (
+ planner_quantization_kwargs,
+ requested_device_map,
+ resolve_unsloth_device_map,
+)
__all__ = ["FastDiffusionModel", "DIFFUSION_MODEL_TYPES", "is_diffusion_model_type"]
@@ -123,7 +129,12 @@ def _load_diffusion_config(
cd["vision_config"]["model_type"] = "diffusion_gemma4_vision"
from transformers import DiffusionGemma4Config
- return DiffusionGemma4Config.from_dict(cd)
+ aliased = DiffusionGemma4Config.from_dict(cd)
+ # Only this object knows the rewrite happened; the checkpoint on disk still says
+ # `diffusion_gemma`, so anything rebuilding the config from `model_name` -- the
+ # planner -- hits the AutoConfig failure just caught here.
+ aliased._unsloth_legacy_alias = True
+ return aliased
class FastDiffusionModel:
@@ -140,6 +151,8 @@ class FastDiffusionModel:
full_finetuning = False,
token = None,
device_map = "auto",
+ # Planner hints for device_map = "unsloth"; see resolve_unsloth_device_map.
+ device_map_planner_kwargs = None,
trust_remote_code = False,
attn_implementation = "eager", # exact match with the reference golden logits
revision = None,
@@ -196,25 +209,11 @@ class FastDiffusionModel:
variant = kwargs.get("variant"),
)
- load_kwargs = dict(
- dtype = dtype,
- device_map = device_map,
- token = token,
- trust_remote_code = trust_remote_code,
- attn_implementation = attn_implementation,
- revision = revision,
- local_files_only = local_files_only,
- cache_dir = cache_dir,
- )
- # Match the load's weight format to the warm (None/auto already matches).
- if kwargs.get("use_safetensors") is not None:
- load_kwargs["use_safetensors"] = kwargs["use_safetensors"]
- # Forward variant to the real load so it reads the warmed variant weights.
- if kwargs.get("variant") is not None:
- load_kwargs["variant"] = kwargs["variant"]
-
# Optional bitsandbytes quant. The MoE experts (3D Parameters) are not nn.Linear so bnb skips
# them; only attention + dense MLP Linears quantize, lm_head/embeddings stay full precision.
+ # Before the plan: the skip list becomes `modules_to_not_convert`, and sizing
+ # those at 4 bits while they load in compute dtype OOMs a tight map.
+ qcfg = None
if load_in_4bit or load_in_8bit:
from transformers import BitsAndBytesConfig
if load_in_4bit:
@@ -233,6 +232,55 @@ class FastDiffusionModel:
)
else:
qcfg = BitsAndBytesConfig(load_in_8bit = True)
+
+ # Same leaf-level resolution as llama.py and vision.py: an unresolved "unsloth"
+ # becomes torch.device("unsloth") in transformers and raises instead of loading.
+ #
+ # A legacy `diffusion_gemma` checkpoint loads only because the config above rewrites
+ # the type in memory. The planner takes a name and rebuilds from the checkpoint, so
+ # it hits the same error and would report it as a generic planning failure.
+ device_map = resolve_unsloth_device_map(
+ requested_device_map(device_map),
+ model_name,
+ full_finetuning = full_finetuning,
+ skip_reason = (
+ "this checkpoint declares the legacy `diffusion_gemma` type, which only "
+ "loads through an in-memory rewrite the planner cannot see"
+ if getattr(config, "_unsloth_legacy_alias", False)
+ else None
+ ),
+ planner_kwargs = device_map_planner_kwargs,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ revision = revision,
+ # The dtype the load below uses, which overrides the checkpoint's own.
+ **add_dtype_kwargs(dtype),
+ **planner_quantization_kwargs(
+ load_in_4bit = load_in_4bit,
+ load_in_8bit = load_in_8bit,
+ quantization_config = qcfg,
+ ),
+ )
+
+ load_kwargs = dict(
+ dtype = dtype,
+ device_map = device_map,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ attn_implementation = attn_implementation,
+ revision = revision,
+ local_files_only = local_files_only,
+ cache_dir = cache_dir,
+ )
+ # Match the load's weight format to the warm (None/auto already matches).
+ if kwargs.get("use_safetensors") is not None:
+ load_kwargs["use_safetensors"] = kwargs["use_safetensors"]
+ # Forward variant to the real load so it reads the warmed variant weights.
+ if kwargs.get("variant") is not None:
+ load_kwargs["variant"] = kwargs["variant"]
+
+ # The same config the plan above was sized against.
+ if qcfg is not None:
load_kwargs["quantization_config"] = qcfg
print(f"==(( Unsloth: FastDiffusionModel (slow / transformers-only path) ))==")
diff --git a/unsloth/models/falcon_h1.py b/unsloth/models/falcon_h1.py
index 02260b25a19..d0c9e09b23f 100644
--- a/unsloth/models/falcon_h1.py
+++ b/unsloth/models/falcon_h1.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from .loader_utils import DEFAULT_DEVICE_MAP
from .llama import *
import os
from ._utils import __version__
@@ -732,7 +733,7 @@ class FastFalconH1Model(FastLlamaModel):
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None,
fix_tokenizer = True,
model_patcher = None,
diff --git a/unsloth/models/glm4_moe.py b/unsloth/models/glm4_moe.py
index 793a1beb06f..503afbce4b6 100644
--- a/unsloth/models/glm4_moe.py
+++ b/unsloth/models/glm4_moe.py
@@ -23,6 +23,7 @@ Key architecture differences from Qwen3 MoE:
- Uses MLA (Multi-head Latent Attention)
"""
+from .loader_utils import DEFAULT_DEVICE_MAP
from .llama import *
import os
from ._utils import __version__
@@ -388,7 +389,7 @@ class FastGLM47Model(FastLlamaModel):
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None,
fix_tokenizer = True,
model_patcher = None,
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index fecc78c0393..cbddb4eaada 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -27,11 +27,18 @@ from ._utils import (
_prepare_model_for_qat,
is_bfloat16_supported,
get_quant_type,
+ resolve_model_class,
)
from .loader_utils import (
+ DEFAULT_DEVICE_MAP,
_exclude_rope_inv_freq_from_ddp,
_get_fp8_mode_and_check_settings,
_restore_dropped_fp8_scales,
+ planner_class_mismatch_reason,
+ planner_model_class,
+ planner_quantization_kwargs,
+ requested_device_map,
+ resolve_unsloth_device_map,
)
from ..utils.packing import (
get_packed_info_from_kwargs,
@@ -56,6 +63,12 @@ from unsloth_zoo.hf_utils import (
fix_lora_auto_mapping,
)
from unsloth_zoo.peft_utils import SKIP_QUANTIZATION_MODULES
+
+try:
+ from unsloth_zoo.device_map_planner import detect_logit_transforms
+except ImportError:
+ # Older unsloth_zoo: fall back to reading the config fields directly.
+ detect_logit_transforms = None
from ..device_type import (
is_hip,
get_device_type,
@@ -1526,15 +1539,25 @@ def CausalLM_fast_forward(fast_forward_inference):
logits = logits.to(_get_dtype(dtype_from_config(self.config)))
loss = None
- logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)
- logit_scaling = getattr(self.config, "logit_scale", 0)
- if self.config.model_type == "granite":
- # granite divides by logits_scaling (16) unlike cohere which multiplies by 0.125.
- # granite: https://github.com/huggingface/transformers/blob/4d1d0f29a493098e6bc6b904b82e29cb331827f5/src/transformers/models/granite/modeling_granite.py#L1103
- # cohere: https://github.com/huggingface/transformers/blob/4d1d0f29a493098e6bc6b904b82e29cb331827f5/src/transformers/models/cohere/modeling_cohere.py#L1176
- logit_scaling = 1 / getattr(self.config, "logits_scaling", 1)
- elif self.config.model_type == "falcon_h1":
- logit_scaling = self.config.lm_head_multiplier
+ # Which field carries the scale is per family (cohere multiplies by logit_scale,
+ # granite divides by logits_scaling, falcon_h1 multiplies by lm_head_multiplier).
+ # The planner sizes the head's card from the same answer, so a new family is taught
+ # once, not twice.
+ # granite: https://github.com/huggingface/transformers/blob/4d1d0f29a493098e6bc6b904b82e29cb331827f5/src/transformers/models/granite/modeling_granite.py#L1103
+ # cohere: https://github.com/huggingface/transformers/blob/4d1d0f29a493098e6bc6b904b82e29cb331827f5/src/transformers/models/cohere/modeling_cohere.py#L1176
+ if detect_logit_transforms is not None:
+ _transforms = detect_logit_transforms(self.config)
+ logit_softcapping = _transforms["logit_softcapping"]
+ logit_scaling = _transforms["logit_scale_multiply"]
+ if not logit_scaling and _transforms["logit_scale_divide"]:
+ logit_scaling = 1 / _transforms["logit_scale_divide"]
+ else:
+ logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)
+ logit_scaling = getattr(self.config, "logit_scale", 0)
+ if self.config.model_type == "granite":
+ logit_scaling = 1 / getattr(self.config, "logits_scaling", 1)
+ elif self.config.model_type == "falcon_h1":
+ logit_scaling = self.config.lm_head_multiplier
if labels is not None:
shift_logits = logits
@@ -2326,7 +2349,9 @@ class FastLlamaModel:
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
+ # Planner hints for device_map = "unsloth"; see resolve_unsloth_device_map.
+ device_map_planner_kwargs = None,
rope_scaling = None,
fix_tokenizer = True,
model_patcher = None,
@@ -2609,6 +2634,67 @@ class FastLlamaModel:
# (the per-load env was built before remap/disable). gpt-oss only; no-op otherwise.
sync_unsloth_model_name_bnb_flags(load_in_4bit, load_in_8bit)
+ # `num_labels` sends the load to AutoModelForSequenceClassification, whose `score`
+ # replaces the `lm_head` the planner named off the repo's config, so `dispatch_model`
+ # refuses the map: "does not give any device for ... score.weight".
+ _planner_skip_reason = None
+ if num_labels is not None:
+ _planner_skip_reason = (
+ planner_class_mismatch_reason(
+ resolve_model_class(AutoModelForSequenceClassification, model_config),
+ planner_model_class(model_config, trust_remote_code = trust_remote_code),
+ )
+ or "num_labels loads a task head the repo config does not describe"
+ )
+
+ # A prequantized checkpoint is always sized by the list in its own config.json:
+ # `merge_quantization_configs` overlays loading attributes for GPTQ / AWQ /
+ # AutoRound / FbgemmFp8 / CompressedTensors / Mxfp4 and never for bitsandbytes, so
+ # neither the merge below (#5027) nor any argument here reaches the plan. Modules
+ # the load then keeps dense are charged at 4bit, budgeting the head device short.
+ #
+ # Worth refusing over only for mamba, whose `out_proj` stacks are GiBs of error. The
+ # other reachable gap is MoE routers, ~70 MiB even on Qwen3-235B-A22B (4096 x 128
+ # experts x 94 layers), inside the planner's own 256 MiB safety margin.
+ if _planner_skip_reason is None and IS_FALCON_H1 and _ckpt_quant_method == "bitsandbytes":
+ _bundled = getattr(model_config, "quantization_config", None)
+ _bundled_skip = (
+ _bundled.get("llm_int8_skip_modules")
+ if isinstance(_bundled, dict)
+ else getattr(_bundled, "llm_int8_skip_modules", None)
+ ) or []
+ if not all(_m in _bundled_skip for _m in ("mamba", "out_proj")):
+ _planner_skip_reason = (
+ "this prequantized checkpoint does not bundle the mamba exclusions the "
+ "load adds, so the plan would size dense weights at 4bit"
+ )
+
+ # Here, not in loader.py: the mapper up there can still substitute the repo (a
+ # -bnb-4bit name resolving to its 16-bit twin), so a plan sized for the name the
+ # caller gave is the wrong plan for the one actually loaded.
+ device_map = resolve_unsloth_device_map(
+ requested_device_map(device_map),
+ model_name,
+ fast_inference = fast_inference,
+ planner_kwargs = device_map_planner_kwargs,
+ skip_reason = _planner_skip_reason,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ revision = revision,
+ # The dtype the load gets, not the checkpoint's: `from_pretrained` overrides
+ # config.json, and planning the wrong one mis-sizes weights 2x either way.
+ **add_dtype_kwargs(dtype),
+ # The caller's own config, still untouched in kwargs here, overrides the
+ # flags: loader.py clears them whenever it forwards one.
+ **planner_quantization_kwargs(
+ load_in_4bit = load_in_4bit,
+ load_in_8bit = load_in_8bit,
+ quantization_config = kwargs.get("quantization_config", None),
+ # The same extra the bnb config below adds.
+ extra_skip_modules = ["out_proj"] if IS_FALCON_H1 else None,
+ ),
+ )
+
bnb_config = None
_ckpt_qcfg = getattr(model_config, "quantization_config", None)
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 38eeb6e7e53..848023a8fca 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -37,12 +37,14 @@ from transformers import AutoConfig
from transformers import __version__ as transformers_version
from peft import PeftConfig, PeftModel
from .loader_utils import (
+ DEFAULT_DEVICE_MAP,
_exclude_rope_inv_freq_from_ddp,
_get_fp8_mode_and_check_settings,
_offline_quantize_to_fp8,
_tag_model_with_fp8_torchao_config,
get_model_name,
prepare_device_map,
+ requested_device_map,
_offline_aware_load,
_resolve_checkpoint_tokenizer_name,
_is_offline_related_error,
@@ -216,6 +218,21 @@ def _config_get(
return getattr(config, field_name, default)
+def _loaded_skip_modules(model_config):
+ """The skip list the load actually used, for the synthetic config stamped after it.
+
+ Whatever ended up on the loaded model is the authority: a pre-quantized checkpoint
+ brings its own list and transformers prefers it over any runtime config, while
+ on-the-fly quantization gets the one Unsloth built. None (transformers picked the
+ output head itself) and [] (told to exclude nothing) are different instructions on
+ reload, so neither is normalized away.
+ """
+ return _config_get(
+ getattr(model_config, "quantization_config", None) or {},
+ "llm_int8_skip_modules",
+ )
+
+
def _config_diff(config):
if isinstance(config, dict):
return config
@@ -416,7 +433,9 @@ class FastLanguageModel(FastLlamaModel):
load_in_16bit = False, # 16bit LoRA
full_finetuning = False,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
+ # Planner hints for device_map = "unsloth"; see resolve_unsloth_device_map.
+ device_map_planner_kwargs = None,
rope_scaling = None,
fix_tokenizer = True,
trust_remote_code = False,
@@ -478,9 +497,12 @@ class FastLanguageModel(FastLlamaModel):
# In multi-GPU (torchrun), each rank must load the model on its own device
# to avoid Accelerate device relocation errors with quantized weights.
is_quantized = load_in_4bit or load_in_8bit or load_in_fp8
+ device_map = requested_device_map(device_map)
if is_quantized and isinstance(device_map, str):
distributed_device_map, is_dist = prepare_device_map()
if is_dist:
+ # One whole model per rank; sharding one across the ranks' GPUs as well
+ # would have every rank fighting for the same cards.
device_map = distributed_device_map
# @_offline_aware_load already forced offline when needed; delegations inherit it.
@@ -495,6 +517,7 @@ class FastLanguageModel(FastLlamaModel):
full_finetuning = full_finetuning,
token = token,
device_map = device_map,
+ device_map_planner_kwargs = device_map_planner_kwargs,
rope_scaling = rope_scaling, # [TODO] No effect
fix_tokenizer = fix_tokenizer, # [TODO] No effect
trust_remote_code = trust_remote_code,
@@ -914,6 +937,7 @@ class FastLanguageModel(FastLlamaModel):
full_finetuning = full_finetuning,
token = token,
device_map = device_map,
+ device_map_planner_kwargs = device_map_planner_kwargs,
rope_scaling = rope_scaling, # [TODO] No effect
fix_tokenizer = fix_tokenizer, # [TODO] No effect
trust_remote_code = trust_remote_code,
@@ -982,6 +1006,7 @@ class FastLanguageModel(FastLlamaModel):
load_in_4bit = load_in_4bit_kwargs,
token = token,
device_map = device_map,
+ device_map_planner_kwargs = device_map_planner_kwargs,
rope_scaling = rope_scaling,
fix_tokenizer = fix_tokenizer,
model_patcher = dispatch_model,
@@ -1039,7 +1064,9 @@ class FastLanguageModel(FastLlamaModel):
"bnb_4bit_use_double_quant": True,
"llm_int8_enable_fp32_cpu_offload": False,
"llm_int8_has_fp16_weight": False,
- "llm_int8_skip_modules": None,
+ # Whatever the load really used. None here would describe a layout
+ # that never existed, and saving it makes the adapter unreloadable.
+ "llm_int8_skip_modules": _loaded_skip_modules(model.config),
"llm_int8_threshold": 6.0,
"load_in_4bit": True,
"load_in_8bit": False,
@@ -1173,7 +1200,9 @@ class FastModel(FastBaseModel):
load_in_16bit = False, # 16bit LoRA
full_finetuning = False,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
+ # Planner hints for device_map = "unsloth"; see resolve_unsloth_device_map.
+ device_map_planner_kwargs = None,
rope_scaling = None, # [TODO] No effect
fix_tokenizer = True, # [TODO] No effect
trust_remote_code = False,
@@ -1331,9 +1360,12 @@ class FastModel(FastBaseModel):
# In multi-GPU (torchrun), each rank must load the model on its own device
# to avoid Accelerate device relocation errors with quantized weights.
is_quantized = load_in_4bit or load_in_8bit or load_in_fp8
+ device_map = requested_device_map(device_map)
if is_quantized and isinstance(device_map, str):
distributed_device_map, is_dist = prepare_device_map()
if is_dist:
+ # One whole model per rank; sharding one across the ranks' GPUs as well
+ # would have every rank fighting for the same cards.
device_map = distributed_device_map
if fast_inference:
@@ -1453,6 +1485,7 @@ class FastModel(FastBaseModel):
full_finetuning = full_finetuning,
token = token,
device_map = device_map,
+ device_map_planner_kwargs = device_map_planner_kwargs,
trust_remote_code = trust_remote_code,
revision = base_revision,
**kwargs,
@@ -1891,6 +1924,7 @@ class FastModel(FastBaseModel):
is_vlm = any(x.endswith("ForConditionalGeneration") for x in architectures)
is_vlm = is_vlm or hasattr(model_config, "vision_config")
load_text_only = text_only and auto_model is None
+ text_only_decoder = False
if load_text_only:
if hasattr(model_config, "vision_config"):
text_config = _get_text_only_config(model_config, old_model_name)
@@ -1911,6 +1945,9 @@ class FastModel(FastBaseModel):
_apply_text_only_key_mapping(kwargs, model_config, text_config)
model_config = text_config
is_vlm = False
+ # model_config is no longer the repo's config, so anything rebuilding
+ # it from model_name (the device-map planner) sees a different model.
+ text_only_decoder = True
else:
is_vlm = False
# If num_labels is set, use AutoModelForSequenceClassification
@@ -1969,6 +2006,7 @@ class FastModel(FastBaseModel):
full_finetuning = full_finetuning,
token = token,
device_map = device_map,
+ device_map_planner_kwargs = device_map_planner_kwargs,
trust_remote_code = trust_remote_code,
revision = model_revision,
tokenizer_revision = _revision_for_tokenizer_repo(
@@ -1993,6 +2031,7 @@ class FastModel(FastBaseModel):
disable_log_stats = disable_log_stats,
load_in_fp8 = load_in_fp8,
text_only = load_text_only,
+ text_only_decoder = text_only_decoder,
*args,
**kwargs,
)
@@ -2034,7 +2073,9 @@ class FastModel(FastBaseModel):
"bnb_4bit_use_double_quant": True,
"llm_int8_enable_fp32_cpu_offload": False,
"llm_int8_has_fp16_weight": False,
- "llm_int8_skip_modules": None,
+ # Whatever the load really used. None here would describe a layout
+ # that never existed, and saving it makes the adapter unreloadable.
+ "llm_int8_skip_modules": _loaded_skip_modules(model.config),
"llm_int8_threshold": 6.0,
"load_in_4bit": True,
"load_in_8bit": False,
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 269ceda220c..454ede1bf9c 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -106,6 +106,271 @@ def prepare_device_map():
return device_map, True
+UNSLOTH_DEVICE_MAP = "unsloth"
+
+
+class _DefaultDeviceMap(str):
+ """`"sequential"`, marked as the value nobody asked for.
+
+ The env opt-in must upgrade the default and leave an explicit "sequential" alone, and a
+ plain comparison cannot tell them apart. A `str` subclass keeps the distinction without
+ changing the value: it equals, hashes and formats as `"sequential"` everywhere, and in
+ `inspect.signature` too, which a sentinel object would not.
+ """
+
+ __slots__ = ()
+
+
+DEFAULT_DEVICE_MAP = _DefaultDeviceMap("sequential")
+
+
+def unmarked_device_map(device_map):
+ """The default with its marker removed; anything else exactly as it came in.
+
+ For a nested load that must not re-read the value as "nobody chose this". A bare `str()`
+ would also flatten a caller's `{"": 0}` into text transformers reads as a device name.
+ """
+ return str(device_map) if isinstance(device_map, _DefaultDeviceMap) else device_map
+
+
+def requested_device_map(device_map):
+ """`UNSLOTH_AUTO_DEVICE_MAP=1` opts in without touching any call site.
+
+ Only the untouched default. A dict, "auto", or a "sequential" the caller typed is a
+ placement someone chose, and accelerate's greedy fill is a different execution model
+ from a head-aware split, so an operator-wide env var does not get to overrule it.
+ """
+ if device_map is DEFAULT_DEVICE_MAP and os.environ.get("UNSLOTH_AUTO_DEVICE_MAP", "0") == "1":
+ return UNSLOTH_DEVICE_MAP
+ return device_map
+
+
+def planner_quantization_kwargs(
+ load_in_4bit = False,
+ load_in_8bit = False,
+ quantization_config = None,
+ extra_skip_modules = None,
+):
+ """The quantization the planner must size for, as the load will really apply it.
+
+ The config or the flags, never both, since transformers refuses both and loader.py
+ clears the flags whenever it forwards a config. Bare flags would describe a
+ full-precision load and raise `DeviceMapInfeasible` on one that would have fit.
+
+ The skip list travels with the flags: SKIP_QUANTIZATION_MODULES stays in compute dtype
+ as `modules_to_not_convert`, and sizing it at 4bit understates the head device by GiBs
+ on a large-vocab VLM. A pre-quantized checkpoint carries its own list in config.json.
+ """
+ if quantization_config is not None:
+ return {"quantization_config": quantization_config}
+ kwargs = {"load_in_4bit": load_in_4bit, "load_in_8bit": load_in_8bit}
+ if load_in_4bit or load_in_8bit:
+ try:
+ from unsloth_zoo.peft_utils import SKIP_QUANTIZATION_MODULES
+ except Exception:
+ # Built on every quantized load, planning or not, so an older unsloth_zoo must
+ # not turn a 4bit load into an ImportError. One without the shared list predates
+ # the planner that consumes it, so this plan was going to decline anyway.
+ return kwargs
+ kwargs["llm_int8_skip_modules"] = SKIP_QUANTIZATION_MODULES + list(extra_skip_modules or [])
+ return kwargs
+
+
+def planner_model_class(config, trust_remote_code = False):
+ """The model class the planner's own rules pick for `config`, or None if unknown.
+
+ The planner never sees the auto class the load chose. `config` is whatever the caller
+ passed, while the planner rebuilds the repo's from `model_name`; the two can disagree.
+ """
+ try:
+ from unsloth_zoo.device_map_planner import _auto_class_for
+ from ._utils import resolve_model_class
+
+ auto_class = _auto_class_for(config, trust_remote_code = trust_remote_code)
+ return resolve_model_class(auto_class, config)
+ except Exception:
+ # Unknown, not mismatched: an unsloth_zoo without this has no planner to feed.
+ return None
+
+
+def planner_class_mismatch_reason(loaded_class, planned_class):
+ """Why the planner's model differs from the one being loaded, else None.
+
+ Overriding the config's own choice gets a map for a module tree the model does not
+ have: `num_labels` swaps in a `score` head where `lm_head` was planned, and dispatch
+ refuses with "does not give any device for ... score.weight". Compared as model
+ classes, since two distinct auto classes can resolve to the same VLM.
+ """
+ if loaded_class is None or planned_class is None or loaded_class is planned_class:
+ return None
+ return f"the load builds {loaded_class.__name__}, not the planned {planned_class.__name__}"
+
+
+# accelerate's `max_memory` spellings, in the order it tries them: GiB/MiB/KiB are binary,
+# GB/MB/KB are decimal, and a lowercase trailing `b` on a decimal unit means bits, not bytes.
+_SIZE_UNITS = (
+ ("GIB", 2**30, False),
+ ("MIB", 2**20, False),
+ ("KIB", 2**10, False),
+ ("GB", 10**9, True),
+ ("MB", 10**6, True),
+ ("KB", 10**3, True),
+)
+
+
+def _as_bytes(size):
+ """A `max_memory` budget in bytes, or None if it cannot be read as one.
+
+ accelerate takes `"10GiB"` as readily as an int, so a caller writes what the load would
+ have taken. The rules are reproduced rather than imported because this runs before
+ anything has established accelerate is installed: an ImportError would read every budget
+ as unparseable and drop the cap in silence. `test_the_local_size_parser_agrees_with_
+ accelerate` holds the copy in step wherever accelerate is present.
+
+ None leaves the measured free memory in place rather than dropping the device. A bool is
+ unreadable here where accelerate would take its int value: `{0: True}` is a typo, and a
+ one byte budget reads as "unusable" to the planner.
+ """
+ if isinstance(size, bool):
+ return None
+ if isinstance(size, int):
+ return size if size >= 0 else None
+ if not isinstance(size, str):
+ return None
+ upper = size.upper()
+ for unit, scale, has_bit_form in _SIZE_UNITS:
+ if not upper.endswith(unit):
+ continue
+ try:
+ amount = int(float(size[: -len(unit)]) * scale)
+ except ValueError:
+ return None
+ # Bits, if they spelled the unit "Gb" rather than "GB". Binary units have no such form.
+ if has_bit_form and size.endswith("b"):
+ amount //= 8
+ return amount if amount >= 0 else None
+ return None
+
+
+def resolve_unsloth_device_map(
+ device_map,
+ model_name,
+ *,
+ fast_inference = False,
+ full_finetuning = False,
+ planner_kwargs = None,
+ skip_reason = None,
+ **config_kwargs,
+):
+ """Plan a head-aware multi-GPU map for `device_map = "unsloth"`, else return as-is.
+
+ Opt-in only, so nothing an existing caller passes changes meaning. The plan is built
+ on the meta device: no GPU memory, no weight download.
+
+ Falls back to "sequential" wherever a plan cannot apply, since a model that loads the
+ old way beats one that refuses to load at all. `DeviceMapInfeasible` is the exception:
+ the planner raises it rather than spilling a bitsandbytes model to CPU, and swallowing
+ it would hand the user an OOM instead of a diagnosis.
+
+ `skip_reason` is the caller's veto, for when only the caller can tell the planner
+ would describe a different model than the load builds.
+ """
+ if device_map != UNSLOTH_DEVICE_MAP:
+ return device_map
+
+ def _fallback(reason):
+ print(f"Unsloth: Not planning a device map; {reason}. Using `sequential`.")
+ return "sequential"
+
+ if skip_reason is not None:
+ return _fallback(skip_reason)
+ if fast_inference:
+ return _fallback("vLLM places its own weights")
+ if full_finetuning:
+ return _fallback("full finetuning does not use the quantized planner")
+ if is_distributed():
+ # Every rank already owns the whole model on its own card; splitting on top of
+ # that puts every rank on every card, a different execution model, not a bigger one.
+ return _fallback("each rank of a distributed launch owns its own device")
+ if DEVICE_TYPE_TORCH != "cuda":
+ return _fallback(f"the planner has no memory budgets for {DEVICE_TYPE_TORCH}")
+ try:
+ device_count = torch.cuda.device_count()
+ except Exception as error:
+ return _fallback(f"the devices could not be counted ({error})")
+
+ # Popped, not forwarded: `max_memory` is a named parameter of the planner, so a copy
+ # left in `planner_kwargs` raises `TypeError: got multiple values for keyword argument`,
+ # which the handler below turns into a silent "sequential", losing the cap and the plan.
+ #
+ # A caller's mapping replaces the measured one rather than editing it: its keys are the
+ # devices they will let the load use. That is accelerate's reading too --
+ # `_init_infer_auto_device_map` takes `devices = list(max_memory.keys())` and
+ # `get_max_memory` never widens a supplied mapping -- so `{0: ..., 1: ...}` on a
+ # four-GPU host means GPUs 2 and 3 are somebody else's.
+ planner_kwargs = dict(planner_kwargs or {})
+ requested_memory = planner_kwargs.pop("max_memory", None)
+ requested_memory = dict(requested_memory) if requested_memory else None
+
+ # Read before probing: `mem_get_info` initialises a CUDA context on each device it
+ # touches, and a withheld card is likely busy with the workload it was withheld for.
+ # One that refuses (ECC error, MIG parent, Exclusive_Process) would also drop the plan
+ # to "sequential" over a device this load was never going to use.
+ if requested_memory is None:
+ probe = list(range(device_count))
+ else:
+ probe = [
+ device
+ for device in requested_memory
+ if isinstance(device, int)
+ and not isinstance(device, bool)
+ and 0 <= device < device_count
+ ]
+ if len(probe) < 2:
+ return "sequential"
+
+ try:
+ from unsloth_zoo.device_map_planner import plan_device_map_for_pretrained
+ except Exception as error:
+ return _fallback(f"the planner is unavailable ({error})")
+
+ # Free, not total: this process's context and anything else resident on the card make
+ # total an overcommit. Guarded because a card can still refuse mid-probe.
+ try:
+ max_memory = {index: torch.cuda.mem_get_info(index)[0] for index in probe}
+ except Exception as error:
+ return _fallback(f"free memory could not be read ({error})")
+
+ if requested_memory is not None:
+ budgets = {}
+ for device, written in requested_memory.items():
+ measured = max_memory.get(device)
+ budget = _as_bytes(written)
+ if budget is None:
+ # Nothing to compare against: what we measured, or for a device we never
+ # measured (cpu, disk) their value untouched for the planner to read.
+ budgets[device] = measured if measured is not None else written
+ else:
+ # Under what is actually free: they may know of reservations we cannot
+ # measure, but planning above free is how a plan OOMs on dispatch.
+ budgets[device] = budget if measured is None else min(measured, budget)
+ max_memory = budgets
+
+ try:
+ plan = plan_device_map_for_pretrained(
+ model_name, max_memory = max_memory, **planner_kwargs, **config_kwargs
+ )
+ except Exception as error:
+ if type(error).__name__ == "DeviceMapInfeasible":
+ raise
+ return _fallback(f"planning failed ({error})")
+
+ if plan is None:
+ return "sequential"
+ print(plan.describe())
+ return plan.device_map
+
+
def __get_model_name(
model_name,
load_in_4bit = True,
diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.py
index ce4b3fa9aa4..41b5a7c3b6b 100644
--- a/unsloth/models/mistral.py
+++ b/unsloth/models/mistral.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from .loader_utils import DEFAULT_DEVICE_MAP
from .llama import *
import os
from ._utils import __version__
@@ -475,7 +476,7 @@ class FastMistralModel(FastLlamaModel):
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None, # Mistral does not support RoPE scaling
fix_tokenizer = True,
model_patcher = None,
diff --git a/unsloth/models/qwen2.py b/unsloth/models/qwen2.py
index f33c3a2b239..61af235b523 100644
--- a/unsloth/models/qwen2.py
+++ b/unsloth/models/qwen2.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from .loader_utils import DEFAULT_DEVICE_MAP
from .llama import *
from .llama import (
LlamaRotaryEmbedding,
@@ -73,7 +74,7 @@ class FastQwen2Model(FastLlamaModel):
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None, # Qwen2 does not support RoPE scaling
fix_tokenizer = True,
model_patcher = None,
diff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.py
index 173424d9f50..986c1fa115b 100644
--- a/unsloth/models/qwen3.py
+++ b/unsloth/models/qwen3.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from .loader_utils import DEFAULT_DEVICE_MAP
from .llama import *
import os
from ._utils import __version__
@@ -413,7 +414,7 @@ class FastQwen3Model(FastLlamaModel):
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None,
fix_tokenizer = True,
model_patcher = None,
diff --git a/unsloth/models/qwen3_moe.py b/unsloth/models/qwen3_moe.py
index 7a5dcbd889c..872cb60a2e7 100644
--- a/unsloth/models/qwen3_moe.py
+++ b/unsloth/models/qwen3_moe.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from .loader_utils import DEFAULT_DEVICE_MAP
from .llama import *
import os
from ._utils import __version__
@@ -205,7 +206,7 @@ class FastQwen3MoeModel(FastQwen3Model):
dtype = None,
load_in_4bit = True,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None,
fix_tokenizer = True,
model_patcher = None,
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 7a9fa4ca249..11ebaaca1c4 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -40,6 +40,12 @@ from trl import __version__ as trl_version_raw
from importlib.metadata import version as importlib_version
from unsloth_zoo.log import logger
from unsloth_zoo.device_type import device_synchronize
+
+try:
+ from unsloth_zoo.device_map_planner import detect_logit_transforms
+except ImportError:
+ # Older unsloth_zoo: fall back to reading the config fields directly.
+ detect_logit_transforms = None
import importlib.util
from ..device_type import (
is_hip,
@@ -1718,13 +1724,21 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):
temperature = self.temperature
model_config = _unsloth_get_model_config(model)
- logit_softcapping = _unsloth_get_final_logit_softcapping(model)
- logit_scale_multiply = getattr(model_config, "logit_scale", 0)
- if logit_scale_multiply is None:
- logit_scale_multiply = 0
- logit_scale_divide = getattr(model_config, "logits_scaling", 0)
- if logit_scale_divide is None:
- logit_scale_divide = 0
+ if detect_logit_transforms is not None:
+ # model_config, not model: under DDP/Accelerate `model` is a wrapper that
+ # does not forward `.config`, so the helper would report zeros.
+ _transforms = detect_logit_transforms(model_config)
+ logit_softcapping = _transforms["logit_softcapping"]
+ logit_scale_multiply = _transforms["logit_scale_multiply"]
+ logit_scale_divide = _transforms["logit_scale_divide"]
+ else:
+ logit_softcapping = _unsloth_get_final_logit_softcapping(model)
+ logit_scale_multiply = getattr(model_config, "logit_scale", 0)
+ if logit_scale_multiply is None:
+ logit_scale_multiply = 0
+ logit_scale_divide = getattr(model_config, "logits_scaling", 0)
+ if logit_scale_divide is None:
+ logit_scale_divide = 0
zipped_inputs = zip(
input_ids_chunks,
@@ -2612,6 +2626,14 @@ RL_PRE_ITEMS["grpo_trainer"].append(
" except Exception:\n"
" UNSLOTH_GRPO_PREFIX_GROUPER_ON = False\n"
)
+# getsource inlines the grpo function bodies but not this file's imports, so the
+# generated cache needs its own guarded import or detect_logit_transforms is a NameError.
+RL_PRE_ITEMS["grpo_trainer"].append(
+ "try:\n"
+ " from unsloth_zoo.device_map_planner import detect_logit_transforms\n"
+ "except Exception:\n"
+ " detect_logit_transforms = None\n"
+)
# Edit _get_per_token_logps to handle mixed precision
@@ -2722,13 +2744,23 @@ def grpo_trainer_compute_loss(function_name, function):
# Get logit softcapping and logit scale
model_config = _unsloth_get_model_config(model)
- logit_softcapping = _unsloth_get_final_logit_softcapping(model) # Gemma
- logit_scale_multiply = getattr(model_config, "logit_scale", 0) # Cohere
- if logit_scale_multiply is None:
- logit_scale_multiply = 0
- logit_scale_divide = getattr(model_config, "logits_scaling", 0) # Granite
- if logit_scale_divide is None:
- logit_scale_divide = 0
+ # The old and reference logps come from _get_per_token_logps_and_entropies and the
+ # gradient logps from here, so both must read the transforms the same way or the
+ # importance ratio compares two different policies.
+ if detect_logit_transforms is not None:
+ # model_config, not model: see _get_per_token_logps_and_entropies.
+ _transforms = detect_logit_transforms(model_config)
+ logit_softcapping = _transforms["logit_softcapping"]
+ logit_scale_multiply = _transforms["logit_scale_multiply"]
+ logit_scale_divide = _transforms["logit_scale_divide"]
+ else:
+ logit_softcapping = _unsloth_get_final_logit_softcapping(model) # Gemma
+ logit_scale_multiply = getattr(model_config, "logit_scale", 0) # Cohere
+ if logit_scale_multiply is None:
+ logit_scale_multiply = 0
+ logit_scale_divide = getattr(model_config, "logits_scaling", 0) # Granite
+ if logit_scale_divide is None:
+ logit_scale_divide = 0
max_left_pad = inputs.get("max_left_pad", 0)
if per_token_logps is not None:
diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.py
index 84051c35848..3f97213f8b6 100644
--- a/unsloth/models/sentence_transformer.py
+++ b/unsloth/models/sentence_transformer.py
@@ -15,6 +15,12 @@
import logging
from .loader import FastModel, DISABLE_SDPA_MODEL_NAMES
+from .loader_utils import (
+ DEFAULT_DEVICE_MAP,
+ UNSLOTH_DEVICE_MAP,
+ requested_device_map,
+ unmarked_device_map,
+)
from ._utils import (
SUPPORTS_BFLOAT16,
resolve_model_class,
@@ -1466,7 +1472,7 @@ class FastSentenceTransformer(FastModel):
load_in_16bit = True, # Changed default: 16-bit is optimal for encoders
full_finetuning = False,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
rope_scaling = None,
fix_tokenizer = True,
trust_remote_code = False,
@@ -1493,6 +1499,19 @@ class FastSentenceTransformer(FastModel):
"Run `pip install sentence-transformers` to install it."
)
+ # The other leaf loaders resolve the "unsloth" sentinel by planning; this one
+ # declines. `st_device` below hands `device_map` to `SentenceTransformer(device=)`,
+ # which ends in `self.to(device)`: the sentinel raises there, and that same `.to()`
+ # would pull any split model back onto one card. The env-var opt-in is resolved too,
+ # or `UNSLOTH_AUTO_DEVICE_MAP=1` asks for a plan without ever naming the sentinel.
+ device_map = requested_device_map(device_map)
+ if device_map == UNSLOTH_DEVICE_MAP:
+ print(
+ "Unsloth: Not planning a device map; SentenceTransformer moves the assembled "
+ "model onto a single device. Using `sequential`."
+ )
+ device_map = "sequential"
+
# Validate the load modes BEFORE the prefetch so a bad config fails without downloading weights.
# Guard on not for_inference: that branch below never used these flags.
if not for_inference:
@@ -1833,6 +1852,15 @@ class FastSentenceTransformer(FastModel):
if _st_cache_dir is not None and "cache_dir" not in kwargs:
kwargs["cache_dir"] = _st_cache_dir
+ # The decline above only spends the sentinel on our copy. Strip the marker before
+ # the nested load, or FastModel reads it as "nobody chose this" and re-upgrades it
+ # under UNSLOTH_AUTO_DEVICE_MAP, splitting a model `st_device` then pulls back onto
+ # one card. Only the marker -- an explicit dict placement must arrive as a dict.
+ #
+ # A plain value rather than pinning the env var around the call: os.environ is
+ # process-wide, so that pin reached unrelated loads on other threads, and two
+ # overlapping sentence loads could restore it out of order.
+ device_map = unmarked_device_map(device_map)
try:
model, tokenizer = FastModel.from_pretrained(
model_name = model_name,
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index caa694b6d1b..8ad68856a54 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -44,9 +44,15 @@ from ._utils import (
)
from ._utils import *
from .loader_utils import (
+ DEFAULT_DEVICE_MAP,
_exclude_rope_inv_freq_from_ddp,
_get_fp8_mode_and_check_settings,
_restore_dropped_fp8_scales,
+ planner_class_mismatch_reason,
+ planner_model_class,
+ planner_quantization_kwargs,
+ requested_device_map,
+ resolve_unsloth_device_map,
)
from ..save import patch_saving_functions
from ..models.loader_utils import is_distributed
@@ -890,7 +896,9 @@ class FastBaseModel:
load_in_16bit = False,
full_finetuning = False,
token = None,
- device_map = "sequential",
+ device_map = DEFAULT_DEVICE_MAP,
+ # Planner hints for device_map = "unsloth"; see resolve_unsloth_device_map.
+ device_map_planner_kwargs = None,
trust_remote_code = False,
model_types = None,
tokenizer_name = None,
@@ -912,6 +920,10 @@ class FastBaseModel:
unsloth_vllm_standby = False,
load_in_fp8 = False, # fp8 LoRA (True, False, 'block')
text_only = False,
+ # True when the caller already swapped a multimodal config for its text sub-config,
+ # so `auto_config` no longer describes the repo. Set by loader.py, and by the block
+ # below on the direct-call path.
+ text_only_decoder = False,
**kwargs,
):
user_config = kwargs.pop("config", None)
@@ -971,6 +983,7 @@ class FastBaseModel:
auto_config = text_config
auto_model = AutoModelForCausalLM
_apply_text_only_key_mapping(kwargs, parent_config, text_config)
+ text_only_decoder = True
elif text_only and auto_model in [
AutoModelForVision2Seq,
AutoModelForImageTextToText,
@@ -1123,6 +1136,8 @@ class FastBaseModel:
)
model_class = resolve_model_class(auto_model, auto_config)
# Check if using forced float32 - we load it in bfloat16, then cast to float16!
+ # Resolved here rather than at the load, because attention resolution below and the
+ # device-map planner both have to size the same dtype the load will really use.
torch_dtype = dtype
if do_forced_float32:
torch_dtype = torch.bfloat16
@@ -1167,6 +1182,55 @@ class FastBaseModel:
load_in_8bit = False
load_in_16bit = False
+ # text_only loads the decoder alone, but the planner gets only `model_name` and
+ # rebuilds the whole VLM: it budgets a vision tower this load never creates and
+ # names `model.language_model.layers.0` where the standalone decoder has
+ # `model.layers.0`, so the first decoder weight ends up with no device set.
+ _planner_skip_reason = (
+ "text_only loads a decoder the repo config does not describe"
+ if text_only_decoder
+ else None
+ )
+ # Same failure from the other direction: `num_labels` (or an explicit `auto_model`)
+ # loads a task head whose `score` replaces the planned `lm_head`, and dispatch
+ # refuses a map with no `score.weight`.
+ if _planner_skip_reason is None:
+ _planner_skip_reason = planner_class_mismatch_reason(
+ model_class,
+ planner_model_class(auto_config, trust_remote_code = trust_remote_code),
+ )
+
+ # A no-op unless the caller asked for "unsloth" (or set UNSLOTH_AUTO_DEVICE_MAP);
+ # an already-planned map comes back unchanged, so a direct FastBaseModel call
+ # behaves the same as going through FastModel.
+ device_map = resolve_unsloth_device_map(
+ requested_device_map(device_map),
+ model_name,
+ fast_inference = fast_inference,
+ full_finetuning = full_finetuning,
+ planner_kwargs = device_map_planner_kwargs,
+ skip_reason = _planner_skip_reason,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ # The pin the config and weights below use; the default branch would size a
+ # different checkpoint than the one being loaded.
+ revision = _revision,
+ # The dtype the load below is given: `from_pretrained` overrides config.json,
+ # so planning the checkpoint's own mis-sizes by 2x whenever it changed.
+ **add_dtype_kwargs(torch_dtype),
+ # A caller-supplied config overrides the flags: loader.py clears them when it
+ # forwards one, so the flags alone would size a 4bit load at full precision.
+ **planner_quantization_kwargs(
+ load_in_4bit = load_in_4bit,
+ load_in_8bit = load_in_8bit,
+ quantization_config = user_quantization_config,
+ # The same extra _skip_modules below adds.
+ extra_skip_modules = ["out_proj"]
+ if any(mt == "nemotron_h" for mt in (model_types or []))
+ else None,
+ ),
+ )
+
if int(load_in_4bit) + int(load_in_8bit) + int(load_in_16bit) >= 2:
raise RuntimeError(
"Unsloth: Can only load in 4bit or 8bit or 16bit, not a combination!"
@@ -1326,6 +1390,7 @@ class FastBaseModel:
if user_quantization_config is None:
kwargs["quantization_config"] = quantization_config
+ # torch_dtype is resolved above, where the device-map planner also needs it.
kwargs = add_dtype_kwargs(torch_dtype, kwargs)
config_attn_impl = kwargs.get("attn_implementation", None)