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
Decide the embedding offload and the multi-GPU split without being asked (#9677)
Daniel Hanb9792a5b14bd
diff --git a/tests/test_offload_tied_autodisable.py b/tests/test_offload_tied_autodisable.pyindex 15eb1186ea1..a955426bcdf 100644--- a/tests/test_offload_tied_autodisable.py+++ b/tests/test_offload_tied_autodisable.py@@ -13,8 +13,14 @@ macOS, Windows and WSL alike: the host's own os.name never decides.import ast, osfrom contextlib import contextmanager-import torch-import torch.nn as nn+import pytest++# Skip rather than error where torch is absent. Only `nn.Embedding` / `nn.Linear` /+# `torch.device` are wanted here, no GPU, but a bare module-level import turns a machine+# without torch into a collection error, which aborts the whole pytest session instead of+# leaving one skipped module behind.+torch = pytest.importorskip("torch")+nn = pytest.importorskip("torch.nn")HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))VISION = os.path.join(HERE, "unsloth", "models", "vision.py")@@ -22,14 +28,32 @@ VISION = os.path.join(HERE, "unsloth", "models", "vision.py")_SRC = open(VISION, encoding = "utf-8").read()+_DISTRIBUTED = [False]++def _load(*names):mod = ast.parse(_SRC)- ns = {"torch": torch, "os": os}+ # The sentinel lives in loader_utils; importing that module would drag in torch's CUDA+ # stack, so mirror the one value these functions read.+ # `is_distributed` is driven explicitly so the assertions never depend on whether the+ # host happens to have torchrun's env vars set.+ ns = {+ "torch": torch,+ "os": os,+ "OFFLOAD_EMBEDDING_AUTO": "auto",+ "is_distributed": lambda: _DISTRIBUTED[0],+ }wanted = set(names)for node in mod.body:if isinstance(node, ast.FunctionDef) and node.name in wanted:exec(ast.get_source_segment(_SRC, node), ns)wanted.discard(node.name)+ elif isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith(+ "_OFFLOAD_EMBEDDING_"+ ):+ # The size thresholds the auto decision reads; taken from the source so the+ # tests below cannot drift from the shipped numbers.+ exec(ast.get_source_segment(_SRC, node), ns)if wanted:raise AssertionError(f"not found in vision.py: {sorted(wanted)}")return ns@@ -39,6 +63,7 @@ _NS = _load("_embeddings_are_tied","_offload_embedding_unsupported_platform","_embedding_dispatch_device",+ "_embedding_is_worth_offloading","_resolve_offload_embedding",)resolve = _NS["_resolve_offload_embedding"]@@ -211,3 +236,155 @@ if __name__ == "__main__":fn()print(f"[PASS] {name}")print("all offload tied auto-disable tests passed")+++# --------------------------------------------------------------------------------------+# `offload_embedding = "auto"`: the loader decides, and says nothing when it declines.+# --------------------------------------------------------------------------------------++worth_offloading = _NS["_embedding_is_worth_offloading"]+MIN_BYTES = _NS["_OFFLOAD_EMBEDDING_MIN_BYTES"]+MIN_FRACTION = _NS["_OFFLOAD_EMBEDDING_MIN_FRACTION"]+++class _FakeWeight:+ def __init__(+ self,+ n_bytes,+ device_type = "cuda",+ index = 0,+ ):+ self._bytes = n_bytes+ self.device = torch.device(+ f"{device_type}:{index}" if device_type == "cuda" else device_type+ )++ def numel(self):+ return self._bytes // 2++ def element_size(self):+ return 2++ def data_ptr(self):+ # Distinct per object, so the tied-weights check sees these as untied.+ return id(self)+++class _FakeEmbedding:+ def __init__(self, weight):+ self.weight = weight+++@contextmanager+def _card(total_bytes):+ """Drive total device memory directly; no GPU is touched."""+ saved = torch.cuda.get_device_properties+ torch.cuda.get_device_properties = lambda index = 0: type(+ "_Props", (), {"total_memory": total_bytes}+ )()+ try:+ yield+ finally:+ torch.cuda.get_device_properties = saved+++def test_a_big_embedding_on_a_small_card_is_offloaded():+ """Muse Glimmer's 202048 x 6656 embedding is 2.5 GiB, 16% of a 16 GB T4. Every one of+ the four notebooks passed `offload_embedding = True` by hand for exactly this."""+ with _card(16 * 2**30):+ assert worth_offloading(_FakeEmbedding(_FakeWeight(int(2.5 * 2**30)))) is True+++def test_the_same_embedding_on_a_big_card_is_left_alone():+ """3% of an 80 GB card. The PCIe traffic buys nothing there."""+ with _card(80 * 2**30):+ assert worth_offloading(_FakeEmbedding(_FakeWeight(int(2.5 * 2**30)))) is False+++def test_a_small_embedding_is_never_worth_the_traffic():+ """Under the absolute floor even though it clears the fraction on a tiny card."""+ with _card(4 * 2**30):+ assert worth_offloading(_FakeEmbedding(_FakeWeight(MIN_BYTES // 2))) is False+++def test_anything_unmeasurable_declines():+ """Not offloading is what every release before this did, so it is the safe answer."""+ with _card(16 * 2**30):+ assert worth_offloading(_FakeEmbedding(None)) is False+ assert worth_offloading(_FakeEmbedding(_FakeWeight(4 * 2**30, "cpu"))) is False+ assert worth_offloading(object()) is False+++def test_auto_declines_a_tied_model_without_printing(capsys):+ """The tied decline explains why something a caller ASKED for is not happening. For a+ default nobody set it would be an apology in front of every tied-embedding load."""+ model = _tied_model()+ with _as_platform("posix"):+ assert resolve(model, "auto") is False+ assert capsys.readouterr().out == ""+++def test_an_explicit_request_still_explains_itself(capsys):+ model = _tied_model()+ with _as_platform("posix"):+ assert resolve(model, True) is False+ assert "ties embed_tokens" in capsys.readouterr().out+++def _sized_model(n_bytes):+ """An untied, undispatched model whose embedding is exactly `n_bytes` on cuda:0."""+ return _Model(_FakeEmbedding(_FakeWeight(n_bytes)), _FakeEmbedding(_FakeWeight(8)))+++def test_auto_offloads_a_big_embedding_and_declines_a_small_one():+ """`resolve` must actually consult the size test, not just default to yes: a blanket+ yes would offload every model on every card and cost PCIe traffic for nothing."""+ with _as_platform("posix"), _card(16 * 2**30):+ assert resolve(_sized_model(int(2.5 * 2**30)), "auto") is True+ assert resolve(_sized_model(64 * 2**20), "auto") is False+++def test_auto_declines_the_same_embedding_on_a_card_with_room():+ with _as_platform("posix"), _card(80 * 2**30):+ assert resolve(_sized_model(int(2.5 * 2**30)), "auto") is False+++def test_explicit_true_and_false_are_untouched_by_the_auto_default():+ """Backwards compatibility: the size test only ever runs for `"auto"`."""+ model = _untied_model()+ with _as_platform("posix"), _card(80 * 2**30):+ # 80 GB card, so `"auto"` would decline; an explicit True must not.+ assert resolve(model, True) is True+ assert resolve(model, False) is False+++@contextmanager+def _under_ddp():+ _DISTRIBUTED[0] = True+ try:+ yield+ finally:+ _DISTRIBUTED[0] = False+++def test_a_distributed_launch_declines_the_offload(capsys):+ """The offload leaves embed_tokens on the CPU while the rest of the rank stays on CUDA.+ Under full finetuning that parameter is trainable, and DDP wrapping with device_ids+ refuses a module whose trainable parameters span both, so the run dies before step 1.+ The old False default kept distributed callers away from this; the new one does not."""+ with _as_platform("posix"), _card(16 * 2**30), _under_ddp():+ assert resolve(_sized_model(int(2.5 * 2**30)), "auto") is False+ assert capsys.readouterr().out == ""+++def test_a_distributed_launch_also_declines_an_explicit_request(capsys):+ """Same veto for someone who asked outright, with the reason, as the other declines do.+ It is a VRAM optimisation, not a correctness switch, so turning it off beats failing."""+ with _as_platform("posix"), _card(16 * 2**30), _under_ddp():+ assert resolve(_sized_model(int(2.5 * 2**30)), True) is False+ assert "distributed launch" in capsys.readouterr().out+++def test_a_single_process_run_is_unaffected():+ with _as_platform("posix"), _card(16 * 2**30):+ assert resolve(_sized_model(int(2.5 * 2**30)), "auto") is Truediff --git a/tests/test_unsloth_device_map_optin.py b/tests/test_unsloth_device_map_optin.pyindex 9772d2952c8..ad27e291bf1 100644--- a/tests/test_unsloth_device_map_optin.py+++ b/tests/test_unsloth_device_map_optin.py@@ -22,7 +22,8 @@ import typesimport pytestHERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))-LOADER_UTILS = os.path.join(HERE, "unsloth", "models", "loader_utils.py")+MODELS = os.path.join(HERE, "unsloth", "models")+LOADER_UTILS = os.path.join(MODELS, "loader_utils.py")_SRC = open(LOADER_UTILS, encoding = "utf-8").read()_SKIP_MODULES = ["lm_head", "vision_tower", "audio_tower"]@@ -124,22 +125,51 @@ def test_an_explicit_dict_is_returned_untouched():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.[email protected]("switch", [None, "1"])+def test_only_the_default_is_ever_upgraded(monkeypatch, switch):+ """Planning is what a caller who chose nothing gets, never a licence to override one+ they did choose. "auto", a dict, and a "sequential" they typed out all survive it --+ hence the marker, since the last of those is the same string as the default."""ns = _load()- monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", "1")+ if switch is None:+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)+ else:+ monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", switch)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")+++def test_the_env_var_can_turn_planning_back_off(monkeypatch):+ """The multi-GPU operator who wants accelerate's greedy fill back needs a switch that+ does not require editing call sites, so `0` has to reach the default itself."""+ ns = _load()+ monkeypatch.setenv("UNSLOTH_AUTO_DEVICE_MAP", "0")assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == "sequential"+ # Still a plain "sequential" downstream, marker and all.+ assert ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]) == ns["DEFAULT_DEVICE_MAP"]+++def test_an_unset_switch_plans_so_a_bare_from_pretrained_needs_no_device_map(monkeypatch):+ """The reason the default flipped: a notebook should not have to pass+ `device_map = "unsloth"` to get the placement that fits."""+ monkeypatch.delenv("UNSLOTH_AUTO_DEVICE_MAP", raising = False)+ planned = {"model.embed_tokens": 0, "lm_head": 1}+ calls = []+ ns = _load(+ devices = 2,+ free = {0: 16 * 2**30, 1: 16 * 2**30},+ planner = lambda name, **kw: calls.append(name) or _Plan(planned),+ )+ resolved = ns["resolve_unsloth_device_map"](+ ns["requested_device_map"](ns["DEFAULT_DEVICE_MAP"]),+ "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit",+ )+ assert resolved == planned+ assert calls == ["unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit"]# ------------------------------------------------------- where planning cannot apply@@ -616,3 +646,277 @@ def test_the_diffusion_plan_is_sized_against_the_config_the_load_applies():assert (passed.get("quantization_config") == "qcfg"), f"diffusion.py:{call.lineno} plans without the skip list the load applies"+++# --------------------------------------------------------------------------------------+# Planning by default reaches paths the opt-in never did.+# --------------------------------------------------------------------------------------+++def _helpers():+ """`planner_kwargs_with_max_memory` / `planner_hub_kwargs`, without importing torch."""+ src = open(LOADER_UTILS, encoding = "utf-8").read()+ ns = {"os": os}+ for node in ast.parse(src).body:+ keep = (+ isinstance(node, ast.FunctionDef)+ and node.name+ in (+ "planner_kwargs_with_max_memory",+ "planner_hub_kwargs",+ "planner_config_overrides",+ "_get_effective_local_files_only",+ "_env_says_offline",+ )+ ) or (+ isinstance(node, ast.Assign)+ and getattr(node.targets[0], "id", "").startswith("_OFFLINE_ENV_")+ )+ if keep:+ exec(ast.get_source_segment(src, node), ns)+ return ns+++def test_a_transformers_max_memory_reaches_the_planner():+ """Before the default flipped, `max_memory` bounded placement because transformers saw+ a string device_map. It only consults it then -- `_get_device_map` gates the whole+ `infer_auto_device_map` branch on `isinstance(device_map, str)` -- so once a plan+ returns a dict the budget is dropped and the map can exceed the caps or use a card the+ caller withheld."""+ ns = _helpers()+ merged = ns["planner_kwargs_with_max_memory"](None, {"max_memory": {0: "12GiB"}})+ assert merged["max_memory"] == {0: "12GiB"}+++def test_an_explicit_planner_max_memory_wins_over_the_loader_one():+ ns = _helpers()+ merged = ns["planner_kwargs_with_max_memory"](+ {"max_memory": {0: "4GiB"}}, {"max_memory": {0: "12GiB"}}+ )+ assert merged["max_memory"] == {0: "4GiB"}+++def test_no_max_memory_leaves_the_planner_kwargs_untouched():+ ns = _helpers()+ assert ns["planner_kwargs_with_max_memory"](None, {}) is None+ same = {"retained_rows": 8}+ assert ns["planner_kwargs_with_max_memory"](same, {"token": "x"}) is same+++def test_the_planner_is_told_where_the_hub_is(monkeypatch):+ """It resolves the config a second time from `model_name`. Without these it can reach+ the network behind `local_files_only`, or miss a model that only exists in the caller's+ cache and lose a plan the load needed."""+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ ns = _helpers()+ assert ns["planner_hub_kwargs"]({"cache_dir": "/models", "local_files_only": True}) == {+ "cache_dir": "/models",+ "local_files_only": True,+ }+ assert ns["planner_hub_kwargs"]({}) == {}+ assert ns["planner_hub_kwargs"]({"local_files_only": False}) == {}++[email protected]("name", ["vision.py", "llama.py", "diffusion.py"])+def test_every_leaf_planner_call_forwards_the_budget_and_the_hub(name):+ """A leaf that misses either one silently plans against the wrong facts."""+ 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):+ continue+ if getattr(node.func, "id", None) != "resolve_unsloth_device_map":+ continue+ rendered = ast.unparse(node)+ assert (+ "planner_kwargs_with_max_memory" in rendered+ ), f"{name}:{node.lineno} plans without the caller's max_memory"+ assert (+ "planner_hub_kwargs" in rendered+ ), f"{name}:{node.lineno} plans without the caller's cache_dir/local_files_only"+ assert (+ "planner_config_overrides" in rendered+ ), f"{name}:{node.lineno} plans without the caller's config overrides"+ return+ raise AssertionError(f"no resolve_unsloth_device_map call in {name}")+++def test_the_wrapper_tells_the_leaf_the_config_was_the_callers():+ """FastModel pops `config` out of kwargs at loader.py:1248 and forwards it as+ `auto_config`, so by the time FastBaseModel looks, its own `kwargs.pop("config")` is+ None and a veto keyed on that alone never fires on the path almost everyone uses.+ The flag travels explicitly, the way `text_only_decoder` already does for the same+ reason: `auto_config` no longer describing the repo cannot be inferred downstream."""+ loader = open(os.path.join(MODELS, "loader.py"), encoding = "utf-8").read()+ assert "auto_config_from_caller = user_config is not None" in loader++ vision = open(os.path.join(MODELS, "vision.py"), encoding = "utf-8").read()+ args = [+ a.arg+ for node in ast.walk(ast.parse(vision))+ if isinstance(node, ast.FunctionDef) and node.name == "from_pretrained"+ for a in list(node.args.args) + list(node.args.kwonlyargs)+ ]+ assert "auto_config_from_caller" in args, "the leaf cannot see that the config was theirs"+ assert "or auto_config_from_caller" in vision+++def test_a_resize_declines_the_automatic_offload():+ """`resize_token_embeddings` replaces the embedding module, and forward hooks do not+ travel to the replacement, so an offload installed during the load would leave a CPU+ embedding feeding a GPU decoder. An explicit request is left alone."""+ loader = open(os.path.join(MODELS, "loader.py"), encoding = "utf-8").read()+ assert "resize_model_vocab is not None" in loader+ assert "and offload_embedding == OFFLOAD_EMBEDDING_AUTO" in loader+++def test_a_caller_supplied_config_declines_planning():+ """The weights load against their config; the planner rebuilds the repo's. Same class,+ different `num_hidden_layers` or `vocab_size`, and the map omits blocks or under-budgets+ weights -- which the class comparison cannot see."""+ source = open(os.path.join(MODELS, "vision.py"), encoding = "utf-8").read()+ assert "user_config is not None" in source+ tree = ast.parse(source)+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ rendered = ast.unparse(node)+ if "user_config is not None" in rendered and "_planner_skip_reason" in rendered:+ return+ raise AssertionError("vision.py plans without vetoing a caller-supplied config")+++def test_the_optimized_path_says_so_when_it_drops_an_offload_request():+ """`FastLanguageModel` accepts `offload_embedding`, but the optimized architectures+ take a path that has never had the parameter, so the request went nowhere in silence.+ The `"auto"` default stays quiet, since off is a decision it is entitled to make."""+ source = open(os.path.join(MODELS, "loader.py"), encoding = "utf-8").read()+ assert "does not support it" in source+ assert "offload_embedding != OFFLOAD_EMBEDDING_AUTO" in source+++def test_the_auto_mode_is_recognised_by_value_everywhere():+ """`_resolve_offload_embedding` asks `== OFFLOAD_EMBEDDING_AUTO`, so a caller who+ hands in an equal but non-interned `"auto"` (one read out of a JSON config, say) is+ in automatic mode as far as the resolver is concerned. Any guard elsewhere that asks+ `is` disagrees with it: the resize guard would leave the offload on and the optimized+ path would print a notice for a request nobody made. Same question, same operator."""+ loader = open(os.path.join(MODELS, "loader.py"), encoding = "utf-8").read()+ for node in ast.walk(ast.parse(loader)):+ if not isinstance(node, ast.Compare):+ continue+ rendered = ast.unparse(node)+ if "OFFLOAD_EMBEDDING_AUTO" not in rendered:+ continue+ assert not any(+ isinstance(op, (ast.Is, ast.IsNot)) for op in node.ops+ ), f"loader.py:{node.lineno} compares the auto mode by identity: {rendered}"+++def test_the_optimized_path_declines_a_caller_supplied_config():+ """FastLanguageModel leaves `config` in kwargs, so the optimized Llama leaf pops its+ own `user_config` and loads the weights against it while the planner rebuilds the+ repo's from `model_name`. A caller who changed `num_hidden_layers` or `vocab_size`+ would get a map for a different model, so the plan is declined rather than guessed."""+ llama = open(os.path.join(MODELS, "llama.py"), encoding = "utf-8").read()+ tree = ast.parse(llama)+ body = None+ for node in ast.walk(tree):+ if isinstance(node, ast.Assign) and ast.unparse(node) == "_planner_skip_reason = None":+ body = node+ assert body is not None, "llama.py no longer starts a planner skip reason"++ assert "if user_config is not None:" in llama+ assert (+ "a caller-supplied config may not describe the repo the planner rebuilds" in llama+ ), "the optimized path plans against a config the load does not use"++ # The veto has to come first, or a later branch that finds no other reason overwrites it.+ veto = llama.index("a caller-supplied config may not describe the repo the planner rebuilds")+ num_labels = llama.index("num_labels loads a task head the repo config does not describe")+ assert veto < num_labels, "the caller-config veto is set after another branch clears it"+ assert "if _planner_skip_reason is None and num_labels is not None:" in llama+++def test_the_diffusion_leaf_plans_with_the_locality_the_load_uses():+ """diffusion.py pops `local_files_only` off kwargs and resolves the offline env vars+ into it before the load, so handing the planner the raw kwargs would tell it nothing.+ It gets the resolved value, or an offline load reaches the Hub behind the caller's+ back and, when that lookup fails, silently loses the split the model needs to fit."""+ source = open(os.path.join(MODELS, "diffusion.py"), encoding = "utf-8").read()+ for node in ast.walk(ast.parse(source)):+ if not isinstance(node, ast.Call):+ continue+ if getattr(node.func, "id", None) != "resolve_unsloth_device_map":+ continue+ rendered = ast.unparse(node)+ assert (+ "local_files_only" in rendered and "cache_dir" in rendered+ ), f"diffusion.py:{node.lineno} plans without the locality the load resolved"+ return+ raise AssertionError("no resolve_unsloth_device_map call in diffusion.py")+++def test_a_code_revision_reaches_the_planner():+ """`trust_remote_code` makes resolving the model class a second Hub lookup, and the+ planner honours `code_revision` for it. The load already gets it through kwargs, so+ leaving it out plans one revision of the remote code and loads another."""+ ns = _helpers()+ assert ns["planner_hub_kwargs"]({"code_revision": "abc123"}) == {"code_revision": "abc123"}+ assert "code_revision" not in ns["planner_hub_kwargs"]({})+ assert ns["planner_hub_kwargs"]({"code_revision": None}) == {}+++def test_a_max_position_embeddings_override_reaches_the_planner():+ """The planner rebuilds the repo config from a name, so an override that lives only in+ the caller's kwargs never reaches it. Raising it on an architecture with learned+ position embeddings makes the planned tensors smaller than the materialized ones, and+ a map that fitted on paper OOMs."""+ ns = _helpers()+ assert ns["planner_config_overrides"]({"max_position_embeddings": 8192}) == {+ "max_position_embeddings": 8192,+ }+ assert ns["planner_config_overrides"]({}) == {}+ assert ns["planner_config_overrides"](None) == {}+ assert ns["planner_config_overrides"]({"max_position_embeddings": None}) == {}+++def test_the_diffusion_leaf_plans_with_the_code_revision_too():+ """Same reason as its locality: this leaf builds the helper's input itself, so a key+ added to the helper does not reach it unless it is named here."""+ source = open(os.path.join(MODELS, "diffusion.py"), encoding = "utf-8").read()+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "planner_hub_kwargs":+ assert "code_revision" in ast.unparse(+ node+ ), "the diffusion leaf plans against a different revision of the remote code"+ return+ raise AssertionError("no planner_hub_kwargs call in diffusion.py")+++def test_an_unresolvable_explicit_model_class_declines_planning():+ """`resolve_model_class` reads `auto_model._model_mapping`, which a concrete+ `PreTrainedModel` subclass does not have, so it returns None and+ `planner_class_mismatch_reason` reads unknown as compatible. The planner would then+ build whatever the repo config selects while the load builds the caller's class."""+ vision = open(os.path.join(MODELS, "vision.py"), encoding = "utf-8").read()+ assert 'getattr(auto_model, "_model_mapping", None) is None' in vision+ assert "an explicit model class has no auto mapping" in vision++ # Ahead of the class comparison it backstops, or that one returns None and the+ # caller-config branch below claims the slot with the wrong reason.+ veto = vision.index("an explicit model class has no auto mapping")+ caller = vision.index("a caller-supplied config may not describe the repo the planner")+ assert veto < caller, "the unresolvable-class veto never gets to run"+++def test_an_auto_class_still_plans():+ """The veto is keyed on the absence of `_model_mapping`, which every Auto class has,+ so a remote-code checkpoint whose config simply is not in the mapping keeps its plan.+ Declining on `model_class is None` alone would have turned planning off for those."""+ import ast as _ast++ vision = open(os.path.join(MODELS, "vision.py"), encoding = "utf-8").read()+ idx = vision.index("an explicit model class has no auto mapping")+ guard = vision[vision.rindex("if (", 0, idx) : idx]+ assert "_model_mapping" in guard, "the veto is not keyed on the class being concrete"diff --git a/unsloth/models/diffusion.py b/unsloth/models/diffusion.pyindex e2bdcd597d4..9822eea66e1 100644--- a/unsloth/models/diffusion.py+++ b/unsloth/models/diffusion.py@@ -28,6 +28,9 @@ from unsloth_zoo.hf_utils import add_dtype_kwargsfrom ._utils import is_bfloat16_supported, maybe_prefetch_hf_snapshotfrom .llama import loggerfrom .loader_utils import (+ planner_config_overrides,+ planner_hub_kwargs,+ planner_kwargs_with_max_memory,planner_quantization_kwargs,requested_device_map,resolve_unsloth_device_map,@@ -249,7 +252,20 @@ class FastDiffusionModel:if getattr(config, "_unsloth_legacy_alias", False)else None),- planner_kwargs = device_map_planner_kwargs,+ planner_kwargs = planner_kwargs_with_max_memory(+ device_map_planner_kwargs,+ kwargs,+ ),+ # This leaf popped `local_files_only` off kwargs above, so the helper gets the+ # resolved value rather than the caller's raw mapping.+ **planner_hub_kwargs(+ {+ "cache_dir": cache_dir,+ "local_files_only": local_files_only,+ "code_revision": kwargs.get("code_revision"),+ },+ ),+ **planner_config_overrides(kwargs),token = token,trust_remote_code = trust_remote_code,revision = revision,diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex cbddb4eaada..1c4ce8a25fd 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -36,6 +36,9 @@ from .loader_utils import (_restore_dropped_fp8_scales,planner_class_mismatch_reason,planner_model_class,+ planner_config_overrides,+ planner_hub_kwargs,+ planner_kwargs_with_max_memory,planner_quantization_kwargs,requested_device_map,resolve_unsloth_device_map,@@ -2638,7 +2641,14 @@ class FastLlamaModel:# 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:+ # The weights load against `user_config`; the planner rebuilds the repo's from+ # `model_name`. A changed `num_hidden_layers` or `vocab_size` then gets a map for a+ # different model, which dispatches short or budgets short.+ if user_config is not None:+ _planner_skip_reason = (+ "a caller-supplied config may not describe the repo the planner rebuilds"+ )+ if _planner_skip_reason is None and num_labels is not None:_planner_skip_reason = (planner_class_mismatch_reason(resolve_model_class(AutoModelForSequenceClassification, model_config),@@ -2676,10 +2686,12 @@ class FastLlamaModel:requested_device_map(device_map),model_name,fast_inference = fast_inference,- planner_kwargs = device_map_planner_kwargs,+ planner_kwargs = planner_kwargs_with_max_memory(device_map_planner_kwargs, kwargs),skip_reason = _planner_skip_reason,+ **planner_config_overrides(kwargs),token = token,trust_remote_code = trust_remote_code,+ **planner_hub_kwargs(kwargs),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.diff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 970b3945970..d276550b03a 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -38,6 +38,7 @@ from transformers import __version__ as transformers_versionfrom peft import PeftConfig, PeftModelfrom .loader_utils import (DEFAULT_DEVICE_MAP,+ OFFLOAD_EMBEDDING_AUTO,_exclude_rope_inv_freq_from_ddp,_get_fp8_mode_and_check_settings,_offline_quantize_to_fp8,@@ -443,7 +444,7 @@ class FastLanguageModel(FastLlamaModel):resize_model_vocab = None,revision = None,use_exact_model_name = False,- offload_embedding = False,+ offload_embedding = OFFLOAD_EMBEDDING_AUTO,float32_mixed_precision = None, # Forces float32 mixed precisionfast_inference = False, # uses vLLMgpu_memory_utilization = 0.5,@@ -1033,6 +1034,16 @@ class FastLanguageModel(FastLlamaModel):except Exception as e:print(f"Unsloth: Could not patch bitsandbytes for torch.compile - {e}")+ # The optimized path has never carried `offload_embedding`, so a request for one is+ # dropped rather than honoured; say so instead of leaving the caller to infer it+ # from memory use. `"auto"` stays quiet: it promises a decision, and off is one.+ if offload_embedding != OFFLOAD_EMBEDDING_AUTO and offload_embedding:+ print(+ "Unsloth: Not offloading embeddings; the optimized path for this "+ "architecture does not support it. Pass `device_map` or use FastModel "+ "if you need the offload."+ )+model, tokenizer = dispatch_model.from_pretrained(model_name = model_name,max_seq_length = max_seq_length,@@ -1250,7 +1261,7 @@ class FastModel(FastBaseModel):whisper_language = None,whisper_task = None,unsloth_force_compile = False,- offload_embedding = False,+ offload_embedding = OFFLOAD_EMBEDDING_AUTO,float32_mixed_precision = None, # Forces float32 mixed precision# Add the missing vLLM/inference parametersfast_inference = False, # uses vLLM@@ -2088,7 +2099,16 @@ class FastModel(FastBaseModel):whisper_language = whisper_language,whisper_task = whisper_task,auto_config = model_config,- offload_embedding = offload_embedding,+ auto_config_from_caller = user_config is not None,+ # `resize_token_embeddings` below replaces the embedding module and hooks do+ # not travel to the replacement, so an offload installed during the load would+ # leave a CPU embedding feeding a GPU decoder. An explicit request is left+ # alone, since that combination was already this caller's to get wrong.+ offload_embedding = (+ False+ if resize_model_vocab is not None and offload_embedding == OFFLOAD_EMBEDDING_AUTO+ else offload_embedding+ ),float32_mixed_precision = float32_mixed_precision,# Pass vLLM/inference parametersfast_inference = fast_inference,diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex 454ede1bf9c..7f43d0da075 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -108,6 +108,9 @@ def prepare_device_map():UNSLOTH_DEVICE_MAP = "unsloth"+# A string, not None, so an explicit False stays distinguishable from "unset".+OFFLOAD_EMBEDDING_AUTO = "auto"+class _DefaultDeviceMap(str):"""`"sequential"`, marked as the value nobody asked for.@@ -124,6 +127,58 @@ class _DefaultDeviceMap(str):DEFAULT_DEVICE_MAP = _DefaultDeviceMap("sequential")+def planner_hub_kwargs(loader_kwargs):+ """The Hub options the planner's own `AutoConfig` lookup needs.++ It resolves the config a second time, from `model_name`. Without these the lookup can+ go to the network behind a `local_files_only` request, or miss a cache-only model and+ turn a plan the load needed into a "sequential" fallback.+ """+ loader_kwargs = loader_kwargs or {}+ hub = {}+ if loader_kwargs.get("cache_dir") is not None:+ hub["cache_dir"] = loader_kwargs["cache_dir"]+ if _get_effective_local_files_only(loader_kwargs):+ hub["local_files_only"] = True+ # Resolving a remote class is a third lookup, and the planner honours `code_revision`+ # for it (`_HUB_KWARGS` in unsloth_zoo's `device_map_planner`). Left out, the plan is+ # built from the default revision's code and can name a tree the model does not have.+ if loader_kwargs.get("code_revision") is not None:+ hub["code_revision"] = loader_kwargs["code_revision"]+ return hub+++def planner_config_overrides(loader_kwargs):+ """Config fields the caller overrides on the load, which the planner has to size for.++ The planner rebuilds the repo's config from a name, so an override living only in+ kwargs is invisible to it. `max_position_embeddings` is the one that changes weight+ sizes: raise it on learned position embeddings and the planned tensors come out+ smaller than the materialized ones, so a map that fitted on paper OOMs.+ `plan_device_map_for_pretrained` hands leftover kwargs to `AutoConfig.from_pretrained`,+ which applies them the way the load does.+ """+ value = (loader_kwargs or {}).get("max_position_embeddings")+ return {} if value is None else {"max_position_embeddings": value}+++def planner_kwargs_with_max_memory(planner_kwargs, loader_kwargs):+ """The caller's transformers `max_memory` has to reach the planner as well.++ Once a plan is returned the load gets an explicit dict, and transformers consults+ `max_memory` only for a string `device_map` (`_get_device_map` gates the whole+ `infer_auto_device_map` branch on `isinstance(device_map, str)`). A budget that used to+ bound placement would be dropped in silence, and the plan could exceed their caps or+ use a card they withheld. An explicit `device_map_planner_kwargs["max_memory"]` wins.+ """+ budget = (loader_kwargs or {}).get("max_memory")+ if budget is None:+ return planner_kwargs+ merged = dict(planner_kwargs or {})+ merged.setdefault("max_memory", budget)+ return merged++def unmarked_device_map(device_map):"""The default with its marker removed; anything else exactly as it came in.@@ -134,13 +189,14 @@ def unmarked_device_map(device_map):def requested_device_map(device_map):- """`UNSLOTH_AUTO_DEVICE_MAP=1` opts in without touching any call site.+ """Head-aware planning is what a caller who chose nothing gets.- 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.+ Only the untouched default is upgraded: a dict, "auto", or a "sequential" the caller+ typed is a placement someone chose, and greedy fill is a different execution model.+ `UNSLOTH_AUTO_DEVICE_MAP=0` turns it off process-wide, for the multi-GPU operator who+ wants that fill back."""- if device_map is DEFAULT_DEVICE_MAP and os.environ.get("UNSLOTH_AUTO_DEVICE_MAP", "0") == "1":+ if device_map is DEFAULT_DEVICE_MAP and os.environ.get("UNSLOTH_AUTO_DEVICE_MAP", "1") == "1":return UNSLOTH_DEVICE_MAPreturn device_mapdiff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 8ad68856a54..f05f5fc3aee 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -45,6 +45,10 @@ from ._utils import (from ._utils import *from .loader_utils import (DEFAULT_DEVICE_MAP,+ OFFLOAD_EMBEDDING_AUTO,+ planner_config_overrides,+ planner_hub_kwargs,+ planner_kwargs_with_max_memory,_exclude_rope_inv_freq_from_ddp,_get_fp8_mode_and_check_settings,_restore_dropped_fp8_scales,@@ -333,6 +337,33 @@ def _embedding_dispatch_device(input_embeddings):return None if hook is None else getattr(hook, "execution_device", None)+# Big in absolute terms and big on this card, since every lookup then crosses PCIe. 2.5 GiB+# is 16% of a 16 GB T4 and worth moving, 3% of an 80 GB card and not.+_OFFLOAD_EMBEDDING_MIN_BYTES = 2**30+_OFFLOAD_EMBEDDING_MIN_FRACTION = 0.05+++def _embedding_is_worth_offloading(input_embeddings):+ """Whether `"auto"` should offload, judged from the embedding against its own card.++ False on anything unmeasurable, which is what every release before this one did.+ """+ try:+ weight = getattr(input_embeddings, "weight", None)+ if weight is None:+ return False+ size = weight.numel() * weight.element_size()+ device = weight.device+ if device.type != "cuda":+ return False+ total = torch.cuda.get_device_properties(device.index or 0).total_memory+ except Exception:+ return False+ if not total:+ return False+ return size >= _OFFLOAD_EMBEDDING_MIN_BYTES and size / total >= _OFFLOAD_EMBEDDING_MIN_FRACTION++def _resolve_offload_embedding(model, offload_embedding):"""Report `offload_embedding` as True only when the offload will really run.@@ -340,34 +371,41 @@ def _resolve_offload_embedding(model, offload_embedding):cannot help instead of failing the load. It also gates`_attach_bnb_multidevice_hooks`, which must still run whenever no offloadhappens, so every "no offload" case has to answer False.++ `"auto"` (the default) decides from the size of the embedding, and the declines below+ stay silent for it: they explain why something a caller *asked* for is not happening,+ and nobody asked for a default."""- if not offload_embedding:+ automatic = offload_embedding == OFFLOAD_EMBEDDING_AUTO++ def _decline(reason):+ if not automatic:+ print(f"Unsloth: Not offloading embeddings; {reason}")+ return False++ if not automatic and not offload_embedding:return Falseplatform_name = _offload_embedding_unsupported_platform()if platform_name is not None:- print(f"Unsloth: Not offloading embeddings; offloading is unsupported on {platform_name}.")- return False+ return _decline(f"offloading is unsupported on {platform_name}.")try:in_embed = model.get_input_embeddings()out_embed = (model.get_output_embeddings() if hasattr(model, "get_output_embeddings") else None)except Exception:- # Cannot inspect it, so leave the caller's request alone.- return offload_embedding+ # Cannot inspect it, so leave an explicit request alone and decline the default.+ return False if automatic else offload_embeddingif _embeddings_are_tied(in_embed, out_embed):- print(- "Unsloth: Not offloading embeddings; this model ties embed_tokens "- "to lm_head, so offloading saves no VRAM."- )- return False+ return _decline("this model ties embed_tokens to lm_head, so offloading saves no VRAM.")if _embedding_dispatch_device(in_embed) is not None:- print(- "Unsloth: Not offloading embeddings; this model is dispatched across devices, "- "which overrides the offload."- )- return False- return True+ return _decline("this model is dispatched across devices, which overrides the offload.")+ if is_distributed():+ # The offload leaves embed_tokens on the CPU while the rest of the rank stays on+ # CUDA. Under full finetuning it is trainable, and DDP with device_ids refuses a+ # module whose trainable parameters span both, so the run dies before step one.+ return _decline("a distributed launch cannot wrap a model split across CPU and GPU.")+ return _embedding_is_worth_offloading(in_embed) if automatic else TrueVLLM_SUPPORTED_VLM = [@@ -908,7 +946,7 @@ class FastBaseModel:whisper_language = None,whisper_task = None,auto_config = None,- offload_embedding = False,+ offload_embedding = OFFLOAD_EMBEDDING_AUTO,float32_mixed_precision = None, # Forces float32 mixed precision# vLLM parametersfast_inference = False,@@ -924,6 +962,10 @@ class FastBaseModel:# 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,+ # True when `auto_config` came from the caller. It cannot be inferred here:+ # FastModel pops `config` out of kwargs before this sees them, so by now it looks+ # exactly like one we resolved ourselves.+ auto_config_from_caller = False,**kwargs,):user_config = kwargs.pop("config", None)@@ -1199,6 +1241,25 @@ class FastBaseModel:model_class,planner_model_class(auto_config, trust_remote_code = trust_remote_code),)+ # The comparison above returns None for a concrete `PreTrainedModel` subclass:+ # `resolve_model_class` reads `auto_model._model_mapping`, which only Auto classes+ # have. Unknown is not compatible, so decline rather than plan the repo's class.+ if (+ _planner_skip_reason is None+ and model_class is None+ and getattr(auto_model, "_model_mapping", None) is None+ ):+ _planner_skip_reason = (+ "an explicit model class has no auto mapping, so the plan cannot be "+ "checked against the class the load builds"+ )+ # The weights load against the caller's config; the planner rebuilds the repo's from+ # a name. Same class, another `num_hidden_layers` or `vocab_size`, and the map omits+ # blocks or under-budgets weights. Only the caller knows, so do not guess.+ if _planner_skip_reason is None and (user_config is not None or auto_config_from_caller):+ _planner_skip_reason = (+ "a caller-supplied config may not describe the repo the planner rebuilds"+ )# 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@@ -1208,10 +1269,12 @@ class FastBaseModel:model_name,fast_inference = fast_inference,full_finetuning = full_finetuning,- planner_kwargs = device_map_planner_kwargs,+ planner_kwargs = planner_kwargs_with_max_memory(device_map_planner_kwargs, kwargs),skip_reason = _planner_skip_reason,+ **planner_config_overrides(kwargs),token = token,trust_remote_code = trust_remote_code,+ **planner_hub_kwargs(kwargs),# The pin the config and weights below use; the default branch would size a# different checkpoint than the one being loaded.revision = _revision,@@ -1412,10 +1475,11 @@ class FastBaseModel:raise_handler = RaiseUninitialized()try:if offload_embedding and fast_inference:- # vLLM manages its own weights; embedding offload does not apply.- print(- "Unsloth: Not offloading embeddings; incompatible with fast_inference (vLLM)."- )+ # vLLM manages its own weights. Silent for the default, as above.+ if offload_embedding != OFFLOAD_EMBEDDING_AUTO:+ print(+ "Unsloth: Not offloading embeddings; incompatible with fast_inference (vLLM)."+ )offload_embedding = Falseif not fast_inference:# Prevent load_in_fp8 from being forwarded into HF internal model loading