Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Use the head-aware planner for Studio's multi-GPU device map (#10042)
Daniel Haneab5cda3683e
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 78d12afee33..cebf669a15c 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -86,9 +86,9 @@ def _multi_gpu_device_map_kwargs() -> dict:unsloth's ``from_pretrained`` defaults to ``device_map="sequential"``, which stacksthe whole model on GPU0 and OOMs multi-GPU hosts whose other GPUs sit empty (#7053).- Returns ``{"device_map": "balanced"}`` only on a real multi-GPU CUDA/ROCm host- (mirroring the inference loader's ``get_device_map``), else empty so single-GPU, CPU- and MLX loads keep the loader default."""+ Returns a sharding map only on a real multi-GPU CUDA/ROCm host (mirroring the+ inference loader's ``get_device_map``), else empty so single-GPU, CPU and MLX loads+ keep the loader default."""if _IS_MLX:return {}try:@@ -102,7 +102,9 @@ def _multi_gpu_device_map_kwargs() -> dict:device_map = get_device_map(None)else:return {}- if device_map == "balanced":+ # Every sharding answer `get_device_map` gives; a "balanced"-only whitelist+ # dropped the map the moment CUDA began asking for a planned one.+ if device_map in ("balanced", "unsloth", "unsloth_balanced"):return {"device_map": device_map}except Exception as exc:logger.debug(f"multi-GPU device_map resolution failed; using loader default: {exc}")@@ -140,6 +142,17 @@ def _is_cpu_spill_rejection(exc: BaseException) -> bool:return "dispatched on the cpu or the disk" in str(exc).lower()+def _is_device_map_infeasible(exc: BaseException) -> bool:+ """The planner refusing to place the model, matched by class name.++ It raises rather than spilling a bitsandbytes model to CPU, budgeting from free+ memory read before this process opens a context -- so a training or chat job+ holding the other cards can make it refuse a model the single-device loader+ still fits. By name, so the export does not require a version defining it.+ """+ return type(exc).__name__ == "DeviceMapInfeasible"++class _CpuSpillRetry(Exception):"""A multi-GPU load that succeeded but left modules offloaded to CPU/disk."""@@ -649,7 +662,10 @@ class ExportBackend:if (_device_map_override is Noneand (- isinstance(e, _CpuSpillRetry) or _is_oom_error(e) or _is_cpu_spill_rejection(e)+ isinstance(e, _CpuSpillRetry)+ or _is_oom_error(e)+ or _is_cpu_spill_rejection(e)+ or _is_device_map_infeasible(e))and _multi_gpu_device_map_kwargs()):@@ -665,7 +681,7 @@ class ExportBackend:logger.warning(f"Multi-GPU export load unusable ({retry_reason}); retrying on "- f"the single-device loader default."+ f"the sequential loader default.")self.cleanup_memory()return self.load_checkpoint(@@ -674,7 +690,10 @@ class ExportBackend:load_in_4bit = load_in_4bit,trust_remote_code = trust_remote_code,hf_token = hf_token,- _device_map_override = {},+ # Named, not omitted: an omitted map is unsloth's DEFAULT_DEVICE_MAP, which+ # `requested_device_map` upgrades back to the planner, re-running the+ # placement that just failed. A typed "sequential" passes through.+ _device_map_override = {"device_map": "sequential"},)def _write_export_metadata(self, save_directory: str):diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 0fbd635c64e..6fbc241a61a 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -1778,7 +1778,7 @@ class UnslothTrainer:result_dataset = Dataset.from_list(processed_examples)logger.info(- f"CSM preprocessing complete: {len(result_dataset)} examples " f"({skipped} skipped)\n"+ f"CSM preprocessing complete: {len(result_dataset)} examples ({skipped} skipped)\n")return result_dataset@@ -2029,7 +2029,7 @@ class UnslothTrainer:result_dataset = Dataset.from_list(processed_examples)logger.info(- f"SNAC preprocessing complete: {len(result_dataset)} examples " f"({skipped} skipped)\n"+ f"SNAC preprocessing complete: {len(result_dataset)} examples ({skipped} skipped)\n")return result_dataset@@ -2220,8 +2220,7 @@ class UnslothTrainer:result_dataset = Dataset.from_list(processed_examples)logger.info(- f"BiCodec preprocessing complete: {len(result_dataset)} examples "- f"({skipped} skipped)\n"+ f"BiCodec preprocessing complete: {len(result_dataset)} examples ({skipped} skipped)\n")sample = result_dataset[0]["text"]logger.info(f"Sample text (first 200 chars): {sample[:200]}...\n")@@ -2413,7 +2412,7 @@ class UnslothTrainer:result_dataset = HFDataset.from_list(processed_examples)logger.info(- f"DAC preprocessing complete: {len(result_dataset)} examples " f"({skipped} skipped)\n"+ f"DAC preprocessing complete: {len(result_dataset)} examples ({skipped} skipped)\n")sample = result_dataset[0]["text"]logger.info(f"Sample text (first 200 chars): {sample[:200]}...\n")@@ -2787,8 +2786,7 @@ class UnslothTrainer:self.dataset_snapshot_path)logger.info(- f"Loaded cached dataset for {dataset_source}: "- f"{len(dataset)} rows\n"+ f"Loaded cached dataset for {dataset_source}: {len(dataset)} rows\n")except Exception as error:from hub.utils.dataset_cache import (@@ -2803,8 +2801,7 @@ class UnslothTrainer:raiseself._update_progress(status_message = (- f"Cached dataset unavailable; "- f"downloading {dataset_source}..."+ f"Cached dataset unavailable; downloading {dataset_source}..."))dataset = None@@ -3479,9 +3476,9 @@ class UnslothTrainer:# kills the feature. Env-only, deliberately NOT worker.py's# _data_parallel_world_size, which also counts visible CUDA devices:# that bounds a row subset where over-counting is free, this feeds a- # veto where both directions are wrong. Unsloth's multi-GPU load is- # device_map="balanced", model-parallel to transformers with _n_gpu = 1,- # so a balanced 4-GPU run draws one GPU's rows per step and counting+ # veto where both directions are wrong. Unsloth's multi-GPU load is a+ # sharding device_map, model-parallel to transformers with _n_gpu = 1,+ # so a sharded 4-GPU run draws one GPU's rows per step and counting# devices would report 4x the passes, vetoing a qualifying run.world_size = world_size_from_env()if world_size > 1:diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 791f6d82fe4..82b5178a561 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -92,7 +92,7 @@ def _data_parallel_world_size() -> int:extra rank does. XPU and MPS stay at one device there, so only CUDA counts.The larger of the two, never the sum: a distributed run forces n_gpu to 1, and a- model-parallel one (device_map="balanced", which is what Unsloth's own multi-GPU+ model-parallel one (a sharding device_map, which is what Unsloth's own multi-GPUload uses) forces it to 1 as well. Rounding up when the model turns out to besharded rather than replicated only tokenizes a larger subset of a corpus thisbound is orders of magnitude below anyway; rounding down means the run silentlydiff --git a/studio/backend/tests/test_export_multi_gpu_device_map.py b/studio/backend/tests/test_export_multi_gpu_device_map.pyindex 4e5546da379..066431b0430 100644--- a/studio/backend/tests/test_export_multi_gpu_device_map.py+++ b/studio/backend/tests/test_export_multi_gpu_device_map.py@@ -3,8 +3,9 @@"""Export checkpoint loading must shard across every visible GPU (#7053): the``device_map="sequential"`` loader default stacks the whole model on GPU0 and OOMs-while the other GPUs sit empty. The loader now passes ``device_map="balanced"``, but-only on a real multi-GPU CUDA/ROCm host, so single-GPU, CPU and MLX are untouched."""+while the other GPUs sit empty. The loader now passes whichever sharding map+``get_device_map`` resolves (``"unsloth"`` on CUDA, ``"balanced"`` elsewhere), but only+on a real multi-GPU host, so single-GPU, CPU and MLX are untouched."""from __future__ import annotations@@ -48,6 +49,16 @@ def test_multi_gpu_host_gets_balanced(monkeypatch):assert mod._multi_gpu_device_map_kwargs() == {"device_map": "balanced"}+def test_multi_gpu_cuda_host_passes_the_unsloth_planner_through(monkeypatch):+ """CUDA multi-GPU now resolves to "unsloth". A whitelist of just "balanced"+ dropped the map and left the export on the loader default, which is the+ single-GPU stacking this file exists to prevent."""+ mod = _export_mod(monkeypatch)+ monkeypatch.setattr(mod, "_IS_MLX", False)+ _stub_hardware(monkeypatch, [0, 1, 2], "unsloth_balanced")+ assert mod._multi_gpu_device_map_kwargs() == {"device_map": "unsloth_balanced"}++def test_single_gpu_host_keeps_loader_default(monkeypatch):mod = _export_mod(monkeypatch)monkeypatch.setattr(mod, "_IS_MLX", False)@@ -251,7 +262,9 @@ def test_successful_load_that_offloads_to_cpu_retries_single_device(monkeypatch,assert ok, messageassert len(calls) == 2assert calls[0]["device_map"] == "balanced"- assert "device_map" not in calls[1]+ # Named, not omitted: an omitted map is unsloth's marked default, which is upgraded+ # back to the planner rather than being the single-device load this retry wants.+ assert calls[1]["device_map"] == "sequential"def test_single_gpu_offload_is_left_alone(monkeypatch, tmp_path):@@ -278,7 +291,11 @@ def test_retry_result_is_kept_even_if_it_also_offloads(monkeypatch, tmp_path):monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: False)monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())- monkeypatch.setattr(mod, "_multi_gpu_device_map_kwargs", lambda: {"device_map": "balanced"})+ monkeypatch.setattr(+ mod,+ "_multi_gpu_device_map_kwargs",+ lambda: {"device_map": "balanced"},+ )checkpoint = tmp_path / "checkpoint-100"checkpoint.mkdir()@@ -287,3 +304,141 @@ def test_retry_result_is_kept_even_if_it_also_offloads(monkeypatch, tmp_path):ok, message = backend.load_checkpoint(str(checkpoint))assert ok, messageassert len(_AlwaysSpills.calls) == 2+++# ── the "unsloth" planner refusing to place the model ──+++def test_is_device_map_infeasible_matches_by_class_name(monkeypatch):+ mod = _export_mod(monkeypatch)++ class DeviceMapInfeasible(RuntimeError):+ pass++ assert mod._is_device_map_infeasible(DeviceMapInfeasible("needs 7.5 GiB free on cuda:0"))+ assert not mod._is_device_map_infeasible(RuntimeError("needs 7.5 GiB free on cuda:0"))+++def test_planner_refusal_retries_on_the_single_device_loader(monkeypatch, tmp_path):+ """The planner budgets from memory read before this process opens a context, so a+ training or chat job holding the other cards can make it refuse a model the old+ single-device load still fits. That was a working export before the switch."""+ mod = _export_mod(monkeypatch)++ class DeviceMapInfeasible(RuntimeError):+ pass++ class _RefusesThenLoads:+ calls: list[dict] = []++ @classmethod+ def from_pretrained(cls, **kwargs):+ cls.calls.append(kwargs)+ if len(cls.calls) == 1:+ raise DeviceMapInfeasible("2 x 8 GiB is not enough for the head")+ return types.SimpleNamespace(+ hf_device_map = {"model.layers.0": 0}+ ), types.SimpleNamespace()++ monkeypatch.setattr(mod, "FastLanguageModel", _RefusesThenLoads)+ monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: None)+ monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())+ monkeypatch.setattr(+ mod, "_multi_gpu_device_map_kwargs", lambda: {"device_map": "unsloth_balanced"}+ )++ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ backend = mod.ExportBackend.__new__(mod.ExportBackend)+ backend.cleanup_memory = lambda: None+ ok, message = backend.load_checkpoint(str(checkpoint))++ assert ok, message+ assert len(_RefusesThenLoads.calls) == 2+ assert _RefusesThenLoads.calls[0]["device_map"] == "unsloth_balanced"+ assert _RefusesThenLoads.calls[1]["device_map"] == "sequential"+++def test_an_unrelated_error_is_still_reported_rather_than_retried(monkeypatch, tmp_path):+ # The retry is for placement, not for every failure: a broken checkpoint must not+ # be loaded twice and reported against the second attempt.+ mod = _export_mod(monkeypatch)++ class _AlwaysBroken:+ calls: list[dict] = []++ @classmethod+ def from_pretrained(cls, **kwargs):+ cls.calls.append(kwargs)+ raise ValueError("adapter_config.json is not valid JSON")++ monkeypatch.setattr(mod, "FastLanguageModel", _AlwaysBroken)+ monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: None)+ monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())+ monkeypatch.setattr(+ mod, "_multi_gpu_device_map_kwargs", lambda: {"device_map": "unsloth_balanced"}+ )++ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ backend = mod.ExportBackend.__new__(mod.ExportBackend)+ backend.cleanup_memory = lambda: None+ ok, message = backend.load_checkpoint(str(checkpoint))++ assert not ok+ assert len(_AlwaysBroken.calls) == 1+ assert "not valid JSON" in message+++def test_the_retry_names_sequential_rather_than_omitting_the_device_map(monkeypatch, tmp_path):+ """An omitted device_map is not the loader default any more.++ unsloth's signature default is `DEFAULT_DEVICE_MAP`, a marked "sequential" that+ `requested_device_map` upgrades back to the planner unless UNSLOTH_AUTO_DEVICE_MAP=0.+ So `_device_map_override = {}` would re-run the very placement that just failed and+ report the same error, and the retry would look like a fallback while being none.+ """+ mod = _export_mod(monkeypatch)++ class DeviceMapInfeasible(RuntimeError):+ pass++ class _RefusesAnyPlan:+ calls: list[dict] = []++ @classmethod+ def from_pretrained(cls, **kwargs):+ cls.calls.append(kwargs)+ # Stands in for the planner: it refuses whenever it is the one asked to place.+ if (+ kwargs.get("device_map") in ("unsloth", "unsloth_balanced", None)+ or "device_map" not in kwargs+ ):+ raise DeviceMapInfeasible("needs 7.57 GiB free on cuda:0, has 4.10 GiB")+ return types.SimpleNamespace(+ hf_device_map = {"model.layers.0": 0}+ ), types.SimpleNamespace()++ monkeypatch.setattr(mod, "FastLanguageModel", _RefusesAnyPlan)+ monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: None)+ monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())+ monkeypatch.setattr(+ mod, "_multi_gpu_device_map_kwargs", lambda: {"device_map": "unsloth_balanced"}+ )++ checkpoint = tmp_path / "checkpoint-100"+ checkpoint.mkdir()+ backend = mod.ExportBackend.__new__(mod.ExportBackend)+ backend.cleanup_memory = lambda: None+ ok, message = backend.load_checkpoint(str(checkpoint))++ assert ok, message+ assert len(_RefusesAnyPlan.calls) == 2+ assert _RefusesAnyPlan.calls[0]["device_map"] == "unsloth_balanced"+ assert _RefusesAnyPlan.calls[1]["device_map"] == "sequential"diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.pyindex 37467fc934f..82c3b428016 100644--- a/studio/backend/tests/test_gpu_selection.py+++ b/studio/backend/tests/test_gpu_selection.py@@ -553,14 +553,24 @@ class TestGpuAutoSelection(_GpuCacheResetMixin, unittest.TestCase):with patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA):self.assertEqual(get_device_map(None), "sequential")self.assertEqual(get_device_map([0]), "sequential")- self.assertEqual(get_device_map([0, 1]), "balanced")+ self.assertEqual(get_device_map([0, 1]), "unsloth_balanced")def test_get_device_map_uses_all_inherited_visible_gpus_for_uuid_masks(self):with (patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": "GPU-aaa,GPU-bbb"}, clear = True),patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA),):- self.assertEqual(get_device_map(None), "balanced")+ self.assertEqual(get_device_map(None), "unsloth_balanced")++ def test_xpu_keeps_balanced_because_the_unsloth_planner_is_cuda_only(self):+ """The planner falls back to "sequential" off CUDA, which would undo the shard."""+ with patch("utils.hardware.hardware.get_device", return_value = DeviceType.XPU):+ self.assertEqual(get_device_map([0, 1]), "balanced")++ def test_a_single_gpu_never_asks_for_a_plan(self):+ for device in (DeviceType.CUDA, DeviceType.XPU):+ with patch("utils.hardware.hardware.get_device", return_value = device):+ self.assertEqual(get_device_map([0]), "sequential")def test_get_offloaded_device_map_entries_returns_only_cpu_and_disk(self):model = SimpleNamespace(@@ -2298,3 +2308,155 @@ class TestEstimateFp16ModelSizeBytesPrefersLocalWeights(unittest.TestCase):self.assertEqual(src, "safetensors")mock_load.assert_not_called()mock_local.assert_not_called()+++class TestDeviceMapAcrossPlatformsAndAccelerators(_GpuCacheResetMixin, unittest.TestCase):+ """The full [Windows, Linux, WSL, Mac] x [NVIDIA, AMD, Intel, Apple, CPU] product.++ Two claims: the answer is something the loader can read, and it does not vary by+ operating system. An OS-dependent answer would move a user's placement when they+ moved the same box between Linux and WSL.++ The AMD row is the one to read carefully. Studio reports a ROCm card as+ DeviceType.CUDA, and unsloth maps its "hip" device type to DEVICE_TYPE_TORCH+ "cuda", so AMD takes the NVIDIA branch and the planner runs there.+ """++ # sys.platform, os.name, platform.system(), platform.release()+ OSES = {+ "Linux": ("linux", "posix", "Linux", "6.8.0-generic"),+ "WSL": ("linux", "posix", "Linux", "5.15.0-microsoft-standard-WSL2"),+ "Windows": ("win32", "nt", "Windows", "10"),+ "Mac": ("darwin", "posix", "Darwin", "23.5.0"),+ }+ ACCELERATORS = {+ "NVIDIA": (DeviceType.CUDA, "unsloth_balanced"),+ "AMD (ROCm)": (DeviceType.CUDA, "unsloth_balanced"),+ "Intel (XPU)": (DeviceType.XPU, "balanced"),+ "Apple (MLX)": (DeviceType.MLX, "sequential"),+ "CPU only": (DeviceType.CPU, "sequential"),+ }+ READABLE = {"sequential", "balanced", "unsloth_balanced"}++ def _answer(self, os_key, device, gpu_ids):+ platform_name, os_name, system, release = self.OSES[os_key]+ with (+ patch.object(sys, "platform", platform_name),+ patch.object(os, "name", os_name),+ patch("platform.system", return_value = system),+ patch("platform.release", return_value = release),+ patch("utils.hardware.hardware.get_device", return_value = device),+ ):+ return get_device_map(gpu_ids)++ def test_every_cell_of_the_product(self):+ for os_key in self.OSES:+ for label, (device, multi_answer) in self.ACCELERATORS.items():+ for gpu_ids, want in (+ ([0], "sequential"),+ ([0, 1], multi_answer),+ (list(range(8)), multi_answer),+ ):+ with self.subTest(os = os_key, accelerator = label, gpus = len(gpu_ids)):+ got = self._answer(os_key, device, gpu_ids)+ self.assertEqual(got, want)+ self.assertIn(got, self.READABLE)++ def test_the_answer_does_not_depend_on_the_operating_system(self):+ for label, (device, _) in self.ACCELERATORS.items():+ for gpu_ids in ([0], [0, 1], list(range(8))):+ answers = {self._answer(key, device, gpu_ids) for key in self.OSES}+ with self.subTest(accelerator = label, gpus = len(gpu_ids)):+ self.assertEqual(+ len(answers),+ 1,+ f"{label} with {len(gpu_ids)} GPU(s) answered {answers} across "+ "operating systems; the placement must not move with the OS",+ )+++class TestTheCudaMapNamesItsFallback(_GpuCacheResetMixin, unittest.TestCase):+ """CUDA asks for `"unsloth_balanced"`, not `"unsloth"`.++ The planner declines several shapes -- a full finetune, an explicit `auto_model` with+ no `_model_mapping`, a Falcon-H1 checkpoint missing the mamba exclusions -- and plain+ `"unsloth"` falls back to `"sequential"`, which is not a shard: `get_max_memory` gives+ cuda:0 its whole free budget, so `infer_auto_device_map` fills it first. On+ `unsloth/Qwen2.5-7B-Instruct` in bf16 across two cards:++ 8 GiB each sequential {'0': 14, '1': 18} balanced {'0': 13, '1': 19}+ 16 GiB each sequential {'0': 1} balanced {'0': 13, '1': 19}++ At 16 GiB the weights fit on one card, so sequential puts them all there with nothing+ left for optimizer state. Naming the fallback covers every declined shape, including+ ones Studio cannot detect and ones unsloth adds later.+ """++ def test_multi_gpu_cuda_names_the_balanced_fallback(self):+ with patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA):+ self.assertEqual(get_device_map([0, 1]), "unsloth_balanced")++ def test_the_plain_sentinel_is_not_used(self):+ # "unsloth" alone falls back to "sequential" on every veto path, which is the bug.+ with patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA):+ self.assertNotEqual(get_device_map([0, 1]), "unsloth")++ def test_xpu_keeps_plain_balanced(self):+ with patch("utils.hardware.hardware.get_device", return_value = DeviceType.XPU):+ self.assertEqual(get_device_map([0, 1]), "balanced")++ def test_a_single_gpu_never_asks_for_a_plan(self):+ for device in (DeviceType.CUDA, DeviceType.XPU, DeviceType.CPU):+ with patch("utils.hardware.hardware.get_device", return_value = device):+ self.assertEqual(get_device_map([0]), "sequential")+++class TestTheFallbackNameIsOneUnslothResolves(unittest.TestCase):+ """The string Studio emits has to be one unsloth's resolver knows.++ A typo, or a rename on the unsloth side, would reach transformers as an unrecognised+ device_map and raise "the value needs to be a device name ... but found X". Read from+ the loader rather than repeated here, so the two cannot drift apart.++ Parsed rather than imported: `import unsloth` needs unsloth_zoo, which the backend+ test environment does not install, and skipping there would leave the one place the+ two sides are compared unrun in CI.+ """++ def _planned_device_maps(self):+ import ast++ source = None+ here = os.path.dirname(os.path.abspath(__file__))+ candidate = os.path.join(here, "..", "..", "..", "unsloth", "models", "loader_utils.py")+ if os.path.exists(candidate):+ source = open(candidate, encoding = "utf-8").read()+ else:+ # An installed Studio: find_spec locates the package without executing it.+ import importlib.util++ spec = importlib.util.find_spec("unsloth")+ locations = list(getattr(spec, "submodule_search_locations", None) or [])+ for location in locations:+ installed = os.path.join(location, "models", "loader_utils.py")+ if os.path.exists(installed):+ source = open(installed, encoding = "utf-8").read()+ break+ self.assertIsNotNone(source, "loader_utils.py not found; the comparison cannot be made")++ namespace = {}+ for node in ast.parse(source).body:+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) in (+ "UNSLOTH_DEVICE_MAP",+ "UNSLOTH_BALANCED_DEVICE_MAP",+ "_PLANNED_DEVICE_MAPS",+ ):+ exec(ast.get_source_segment(source, node), namespace)+ return namespace["_PLANNED_DEVICE_MAPS"]++ def test_the_cuda_answer_is_a_planned_map_unsloth_accepts(self):+ planned = self._planned_device_maps()+ with patch("utils.hardware.hardware.get_device", return_value = DeviceType.CUDA):+ answer = get_device_map([0, 1])+ self.assertIn(answer, planned)+ self.assertEqual(planned[answer], "balanced")diff --git a/studio/backend/tests/test_gpu_selection_sandbox.py b/studio/backend/tests/test_gpu_selection_sandbox.pyindex ba6d0571231..e1b69f7bcf5 100644--- a/studio/backend/tests/test_gpu_selection_sandbox.py+++ b/studio/backend/tests/test_gpu_selection_sandbox.py@@ -325,12 +325,12 @@ class TestGetDeviceMap(unittest.TestCase):dm = get_device_map(gpu_ids = [0])self.assertEqual(dm, "sequential")- def test_multi_gpu_returns_balanced(self):+ def test_multi_gpu_returns_the_unsloth_planner(self):from utils.hardware.hardware import get_device_mapimport utils.hardware.hardware as hwwith patch.object(hw, "get_device", return_value = hw.DeviceType.CUDA):dm = get_device_map(gpu_ids = [0, 1])- self.assertEqual(dm, "balanced")+ self.assertEqual(dm, "unsloth_balanced")def test_cpu_returns_sequential(self):from utils.hardware.hardware import get_device_mapdiff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex d57ff38f750..ea64c4200cc 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -4939,12 +4939,29 @@ def apply_gpu_ids(gpu_ids, backend: Optional[str] = None) -> None:def get_device_map(gpu_ids: Optional[list[int]] = None) -> str:"""Return the Hugging Face ``device_map`` string for model loading.- Returns ``"balanced"`` (shard evenly across GPUs) when:+ Returns ``"unsloth_balanced"`` on CUDA, or ``"balanced"`` on XPU, to shard+ across GPUs when:- ``gpu_ids`` explicitly lists >1 GPU, **or**- ``CUDA_VISIBLE_DEVICES``/``ZE_AFFINITY_MASK`` uses non-numericidentifiers (UUID/MIG/wildcard) and >1 GPU is visible (fallback:numeric IDs unresolvable, so assume multi-GPU is intended).+ CUDA asks for unsloth's head-aware planner instead of accelerate's+ ``"balanced"``, which caps every device but the last at about+ ``model_size / n_devices``. On a quantized model the unquantized ``lm_head``+ then does not fit on cuda:0, every module lands on the last card, and a 4bit+ model wholly on a non-zero card cannot be trained: ``prepare_model`` refuses it.++ ``"unsloth_balanced"`` rather than ``"unsloth"`` because the planner declines+ several shapes -- a full finetune, an ``auto_model`` with no ``_model_mapping``,+ a Falcon-H1 checkpoint missing the mamba exclusions, and any added later -- and+ the plain name falls back to ``"sequential"``, which fills cuda:0 to its whole+ free budget: a 7B in bf16 across 2x16 GiB lands entirely on cuda:0 against 13/19+ for ``balanced``. Naming the fallback keeps every declined shape sharded without+ Studio enumerating a list that belongs to unsloth.++ XPU keeps plain ``"balanced"``: the planner has no non-CUDA memory budgets.+Returns ``"sequential"`` (single device) otherwise, including CPU/MLXbackends.@@ -4978,7 +4995,7 @@ def get_device_map(gpu_ids: Optional[list[int]] = None) -> str:multi_gpu = Trueif multi_gpu:- return "balanced"+ return "unsloth_balanced" if device == DeviceType.CUDA else "balanced"return "sequential"diff --git a/tests/studio/test_hardware_dispatch_matrix.py b/tests/studio/test_hardware_dispatch_matrix.pyindex e969f5eb48c..a25fb259983 100644--- a/tests/studio/test_hardware_dispatch_matrix.py+++ b/tests/studio/test_hardware_dispatch_matrix.py@@ -242,7 +242,7 @@ def spoof_hardware(monkeypatch):):if name == "mlx" or name.startswith("mlx."):raise ImportError(- f"mlx import blocked by spoof_hardware " f"(profile={profile.name})"+ f"mlx import blocked by spoof_hardware (profile={profile.name})")return None@@ -303,9 +303,9 @@ def test_studio_detect_hardware_matches_profile(profile, spoof_hardware):f"profile {profile.name}: expected {profile.expect_device_type}, "f"got {detected!r}. {profile.extra_notes}")- assert hw.IS_ROCM is profile.expect_is_rocm, (- f"profile {profile.name}: expected IS_ROCM={profile.expect_is_rocm}, " f"got {hw.IS_ROCM}"- )+ assert (+ hw.IS_ROCM is profile.expect_is_rocm+ ), f"profile {profile.name}: expected IS_ROCM={profile.expect_is_rocm}, got {hw.IS_ROCM}"@pytest.mark.parametrize("profile", PROFILES, ids = PROFILE_IDS)@@ -415,6 +415,8 @@ def _loader_device_map_helpers():exec(_ast.get_source_segment(source, node), namespace)elif isinstance(node, _ast.Assign) and getattr(node.targets[0], "id", None) in ("UNSLOTH_DEVICE_MAP",+ "UNSLOTH_BALANCED_DEVICE_MAP",+ "_PLANNED_DEVICE_MAPS","DEFAULT_DEVICE_MAP","_SIZE_UNITS",):@@ -435,11 +437,12 @@ def _loader_device_map_helpers():def test_studio_placement_survives_the_loader_opt_in(profile, gpu_ids, opt_in, spoof_hardware, monkeypatch):- """Whatever Unsloth decided, the loader hands the same thing to transformers.+ """Whatever Unsloth decided, the loader hands transformers a map of the same shape.- The one value the opt-in can rewrite is "sequential", and Unsloth 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".+ "sequential" and "balanced" survive untouched. "unsloth_balanced" is a request to+ plan, so the loader may answer with a plan or, when it declines -- as it does here,+ with no planner installed -- with the sharding map that name declines to. What it+ must never do is turn a multi-GPU ask into "sequential", which fills cuda:0 first."""spoof_hardware(profile)hw = _import_studio_hardware_module()@@ -448,7 +451,7 @@ def test_studio_placement_survives_the_loader_opt_in(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")+ assert device_map in ("balanced", "sequential", "unsloth_balanced")if opt_in == "unset":monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)@@ -463,7 +466,9 @@ def test_studio_placement_survives_the_loader_opt_in(resolved = loader["resolve_unsloth_device_map"](loader["requested_device_map"](device_map), "unsloth/Qwen3-0.6B")- assert resolved == device_map, (+ # No planner module is installed, so a planned name always reaches its fallback.+ expected = loader["_PLANNED_DEVICE_MAPS"].get(device_map, device_map)+ assert resolved == expected, (f"profile {profile.name}, gpu_ids={gpu_ids}, UNSLOTH_AUTO_DEVICE_MAP={opt_in}: "f"Unsloth asked for {device_map!r} and the loader produced {resolved!r}")@@ -472,12 +477,18 @@ def test_studio_placement_survives_the_loader_opt_in(@pytest.mark.parametrize("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 Unsloth's loads, and- "unsloth" is not one of its answers on any backend. If it ever becomes one, the- Unsloth-side reasoning above stops holding and this fails first."""+ the plain "unsloth" sentinel is not one of its answers on any backend.++ That name declines to "sequential", which gives cuda:0 its whole free budget and so+ puts a model that fits there on one card. Every path the planner vetoes -- a full+ finetune, an `auto_model` with no `_model_mapping`, a Falcon-H1 checkpoint missing+ the mamba exclusions -- ends in that fallback, so a multi-GPU ask has to use the+ name whose fallback still shards.+ """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"}+ assert answers <= {"balanced", "sequential", "unsloth_balanced"}diff --git a/tests/test_unsloth_device_map_leaks.py b/tests/test_unsloth_device_map_leaks.pyindex 8faa6e29071..2f115f595a3 100644--- a/tests/test_unsloth_device_map_leaks.py+++ b/tests/test_unsloth_device_map_leaks.py@@ -115,7 +115,10 @@ def test_sentence_transformer_never_hands_the_sentinel_to_sentence_transformers(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)+ and any(+ ast.unparse(c) in ("UNSLOTH_DEVICE_MAP", "_PLANNED_DEVICE_MAPS")+ for c in node.comparators+ )]assert spends, "the 'unsloth' sentinel reaches SentenceTransformer(device = ...) unresolved"@@ -176,3 +179,70 @@ def test_sentence_transformer_decline_survives_the_env_var():assert "os.environ['UNSLOTH_AUTO_DEVICE_MAP']" not in ast.unparse(function), "the process-wide pin is back; every other thread sees it"+++def test_every_planned_map_membership_test_is_guarded_against_a_dict():+ """`device_map` is a dict as often as it is a string, and dicts are unhashable.++ `{"": 0, "model.vision_tower": 1} in _PLANNED_DEVICE_MAPS` raises TypeError, so an+ explicit placement -- the one shape a user hand-wrote and most wants honoured -- would+ fail the load outright. Both call sites take the `isinstance` first for that reason,+ and there is no way to notice from reading either one alone.+ """+ for name in os.listdir(MODELS):+ if not name.endswith(".py"):+ continue+ tree = ast.parse(_source(name))+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Compare)+ and any(ast.unparse(c) == "_PLANNED_DEVICE_MAPS" for c in node.comparators)+ ):+ continue+ # One tree, walked twice: a second parse gives different node objects, so+ # the identity test below would find no parent and pass on anything.+ parents = [+ ast.unparse(outer)+ for outer in ast.walk(tree)+ if isinstance(outer, ast.BoolOp) and node in ast.walk(outer)+ ]+ assert any("isinstance(" in text and ", str)" in text for text in parents), (+ f"{name}: a membership test on _PLANNED_DEVICE_MAPS with no isinstance "+ f"guard beside it -- an explicit dict device_map raises TypeError here"+ )+++def test_sentence_transformer_declines_to_a_value_st_device_normalises():+ """Whatever planned name is asked for, this loader declines to "sequential".++ `st_device` only normalises dicts, "auto" and "sequential"; anything else reaches+ `SentenceTransformer(device = ...)` and then `.to(...)`, so declining to "balanced"+ -- the value that name declines to everywhere else -- would raise on a string that+ is not a torch device. Nothing is sharded here, so the sharding fallback is wrong.+ """+ 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"+ )++ declines = [+ ast.unparse(node.value)+ 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) != "requested_device_map(device_map)"+ ]+ assert "'sequential'" in declines, "the decline is not a literal 'sequential'"+ assert (+ "_PLANNED_DEVICE_MAPS[device_map]" not in declines+ ), "declining to the sharding fallback sends 'balanced' to SentenceTransformer(device=)"++ whitelists = [+ node+ for node in ast.walk(function)+ if isinstance(node, ast.List)+ and [getattr(e, "value", None) for e in node.elts] == ["auto", "sequential"]+ ]+ assert whitelists, "the st_device whitelist changed; re-check what the decline may be"diff --git a/tests/test_unsloth_device_map_optin.py b/tests/test_unsloth_device_map_optin.pyindex ad27e291bf1..d75b5a6a838 100644--- a/tests/test_unsloth_device_map_optin.py+++ b/tests/test_unsloth_device_map_optin.py@@ -73,6 +73,8 @@ def _load(exec(ast.get_source_segment(_SRC, node), ns)elif isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) in ("UNSLOTH_DEVICE_MAP",+ "UNSLOTH_BALANCED_DEVICE_MAP",+ "_PLANNED_DEVICE_MAPS","DEFAULT_DEVICE_MAP","_SIZE_UNITS",):@@ -379,6 +381,74 @@ def test_an_infeasible_plan_is_raised_not_swallowed():ns["resolve_unsloth_device_map"]("unsloth", "m")+# ------------------------------------------------- the second name, whose decline shards+++ "kwargs,devices,planner",+ [+ ({"skip_reason": "text_only"}, 2, None),+ ({"fast_inference": True}, 2, None),+ ({"full_finetuning": True}, 2, None),+ ({}, 2, lambda *a, **k: None),+ ({}, 2, lambda *a, **k: (_ for _ in ()).throw(RuntimeError("hub unreachable"))),+ ],+)+def test_the_balanced_sentinel_declines_to_balanced_not_sequential(kwargs, devices, planner):+ """`"unsloth_balanced"` is the same plan with a different answer when it is declined.++ "sequential" is not a shard: `get_max_memory` gives cuda:0 its whole free budget, so+ `infer_auto_device_map` fills it first and a model that fits lands there whole. On+ `unsloth/Qwen2.5-7B-Instruct` in bf16 across two cards, 16 GiB each, "sequential"+ answers {'0': 1} where "balanced" answers {'0': 13, '1': 19}. A caller that asked to+ plan across several cards wants a split even when the planner declines, and it+ declines on more shapes than a caller can enumerate -- a full finetune, an+ `auto_model` with no `_model_mapping`, a prequantized Falcon-H1 checkpoint.+ """+ ns = _load(devices = devices, planner = planner)+ assert ns["resolve_unsloth_device_map"]("unsloth_balanced", "m", **kwargs) == "balanced"+ # The plain sentinel is unchanged: an existing caller keeps the answer it had.+ assert ns["resolve_unsloth_device_map"]("unsloth", "m", **kwargs) == "sequential"++[email protected]("devices", [0, 1])+def test_the_balanced_sentinel_declines_to_balanced_on_one_device_too(devices):+ """The silent fallbacks are the easy ones to leave hardcoded, and both were."""+ ns = _load(devices = devices, planner = lambda *a, **k: pytest.fail("nothing to plan"))+ assert ns["resolve_unsloth_device_map"]("unsloth_balanced", "m") == "balanced"+++def test_both_names_plan_identically_when_the_planner_answers():+ """The name chooses the fallback and nothing else, so a plan is not a second code+ path that could drift."""+ planned = {"": 0, "model.vision_tower": 1}+ for name in ("unsloth", "unsloth_balanced"):+ ns = _load(planner = lambda *a, **k: _Plan(dict(planned)))+ assert ns["resolve_unsloth_device_map"](name, "m") == planned+++def test_an_infeasible_plan_is_still_raised_for_the_balanced_name():+ """The one deliberate raise must not be softened into a shard by the new name."""++ 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_balanced", "m")+++def test_the_default_device_map_still_resolves_to_the_plain_sentinel():+ """An omitted device_map becomes the planner, and its decline has always been+ "sequential" -- which is also what an omitted device_map got before planning existed.+ Widening that to "balanced" would change what every single-card caller loads."""+ ns = _load()+ assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == "unsloth"++# ------------------------------------------------------------- when it does plandiff --git a/tests/test_unsloth_device_map_platform_matrix.py b/tests/test_unsloth_device_map_platform_matrix.pyindex c9cdecf1634..f36a0f10b65 100644--- a/tests/test_unsloth_device_map_platform_matrix.py+++ b/tests/test_unsloth_device_map_platform_matrix.py@@ -153,6 +153,8 @@ def _build(exec(ast.get_source_segment(_SRC, node), ns)elif isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) in ("UNSLOTH_DEVICE_MAP",+ "UNSLOTH_BALANCED_DEVICE_MAP",+ "_PLANNED_DEVICE_MAPS","DEFAULT_DEVICE_MAP","_SIZE_UNITS",):diff --git a/tests/test_unsloth_device_map_review_fixes.py b/tests/test_unsloth_device_map_review_fixes.pyindex d02208ce41d..908149ce36a 100644--- a/tests/test_unsloth_device_map_review_fixes.py+++ b/tests/test_unsloth_device_map_review_fixes.py@@ -91,7 +91,13 @@ def _build(or (isinstance(node, ast.Assign)and getattr(node.targets[0], "id", None)- in ("UNSLOTH_DEVICE_MAP", "DEFAULT_DEVICE_MAP", "_SIZE_UNITS")+ in (+ "UNSLOTH_DEVICE_MAP",+ "UNSLOTH_BALANCED_DEVICE_MAP",+ "_PLANNED_DEVICE_MAPS",+ "DEFAULT_DEVICE_MAP",+ "_SIZE_UNITS",+ )))if keep:diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex 8dc3e743e51..31c60ce6d2e 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -120,6 +120,13 @@ def prepare_device_map():UNSLOTH_DEVICE_MAP = "unsloth"+# Same planner, different answer when it declines. Every veto path ends in "sequential",+# which fills the first device to its whole free budget -- right for a loader default,+# wrong for a caller that picked several cards on their combined capacity. Naming the+# fallback spares such a caller enumerating veto reasons that are unsloth's and can grow.+UNSLOTH_BALANCED_DEVICE_MAP = "unsloth_balanced"+_PLANNED_DEVICE_MAPS = {UNSLOTH_DEVICE_MAP: "sequential", UNSLOTH_BALANCED_DEVICE_MAP: "balanced"}+# A string, not None, so an explicit False stays distinguishable from "unset".OFFLOAD_EMBEDDING_AUTO = "auto"@@ -343,12 +350,14 @@ def resolve_unsloth_device_map(`skip_reason` is the caller's veto, for when only the caller can tell the plannerwould describe a different model than the load builds."""- if device_map != UNSLOTH_DEVICE_MAP:+ # `isinstance` first: a caller's explicit dict is unhashable, so `in` alone raises.+ if not isinstance(device_map, str) or device_map not in _PLANNED_DEVICE_MAPS:return device_map+ _declined = _PLANNED_DEVICE_MAPS[device_map]def _fallback(reason):- print(f"Unsloth: Not planning a device map; {reason}. Using `sequential`.")- return "sequential"+ print(f"Unsloth: Not planning a device map; {reason}. Using `{_declined}`.")+ return _declinedif skip_reason is not None:return _fallback(skip_reason)@@ -395,7 +404,7 @@ def resolve_unsloth_device_map(and 0 <= device < device_count]if len(probe) < 2:- return "sequential"+ return _declinedtry:from unsloth_zoo.device_map_planner import plan_device_map_for_pretrained@@ -434,7 +443,7 @@ def resolve_unsloth_device_map(return _fallback(f"planning failed ({error})")if plan is None:- return "sequential"+ return _declinedprint(plan.describe())return plan.device_mapdiff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 7707b30adf5..0a1bea85a27 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -17,7 +17,7 @@ import loggingfrom .loader import FastModel, DISABLE_SDPA_MODEL_NAMESfrom .loader_utils import (DEFAULT_DEVICE_MAP,- UNSLOTH_DEVICE_MAP,+ _PLANNED_DEVICE_MAPS,requested_device_map,unmarked_device_map,)@@ -1514,7 +1514,12 @@ class FastSentenceTransformer(FastModel):# 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:+ # Always "sequential", never the asked-for name's own declined value: the `st_device`+ # blocks below normalise only dicts, "auto" and "sequential", so "balanced" would+ # reach `SentenceTransformer(device = "balanced")` and then `.to("balanced")`, which+ # is not a torch device. There is nothing to shard here in any case.+ # `isinstance` first: a caller's explicit dict is unhashable, so `in` alone raises.+ if isinstance(device_map, str) and device_map in _PLANNED_DEVICE_MAPS:print("Unsloth: Not planning a device map; SentenceTransformer moves the assembled ""model onto a single device. Using `sequential`."