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
Grouped-linear LoRA for DeepSeek-V4, remote-code shims for Step-3.7, and a real message for Mistral-format checkpoints (#11528)
Daniel Han893889dfcc89
diff --git a/tests/test_grouped_linear_lora.py b/tests/test_grouped_linear_lora.pynew file mode 100644index 00000000000..8c4fa44103e--- /dev/null+++ b/tests/test_grouped_linear_lora.py@@ -0,0 +1,234 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""LoRA on a block-diagonal grouped linear (DeepSeek-V4's `o_a_proj`)."""++import pytest+import torch++peft = pytest.importorskip("peft")+++class GroupedLinear(torch.nn.Linear):+ """The shape contract of `DeepseekV4GroupedLinear` and `FP8GroupedLinear`."""++ def __init__(self, in_per_group, out_features, n_groups):+ super().__init__(in_per_group, out_features, bias = False)+ self.n_groups = n_groups++ def forward(self, x):+ input_shape = x.shape[:-2]+ hidden_dim = x.shape[-1]+ w = self.weight.view(self.n_groups, -1, hidden_dim).transpose(1, 2)+ x = x.reshape(-1, self.n_groups, hidden_dim).transpose(0, 1)+ y = torch.bmm(x, w).transpose(0, 1)+ return y.reshape(*input_shape, self.n_groups, -1)+++class Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.o_a_proj = GroupedLinear(16, 4 * 8, 4)+ self.o_b_proj = torch.nn.Linear(4 * 8, 16, bias = False)++ def forward(self, x):+ return self.o_b_proj(self.o_a_proj(x).flatten(2))+++def _peft_model(register):+ from peft import LoraConfig, get_peft_model++ torch.manual_seed(0)+ model = Block()+ config = LoraConfig(+ r = 4, lora_alpha = 8, target_modules = ["o_a_proj", "o_b_proj"], init_lora_weights = False+ )+ if register:+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora+ assert register_grouped_linear_lora(config, model) == [GroupedLinear]+ return get_peft_model(model, config)+++def test_is_grouped_linear_wants_n_groups_and_an_overridden_forward():+ from unsloth.models.grouped_linear_lora import is_grouped_linear++ assert is_grouped_linear(GroupedLinear(16, 32, 4))+ assert not is_grouped_linear(torch.nn.Linear(16, 32))+ plain = torch.nn.Linear(16, 32)+ plain.n_groups = 4+ assert not is_grouped_linear(plain)+++def test_dense_lora_fails_on_the_grouped_linear():+ """The arm that fails on main."""+ model = _peft_model(register = False)+ with pytest.raises(RuntimeError, match = "must match the size"):+ model(torch.randn(2, 5, 4, 16))+++def test_grouped_lora_trains_and_matches_the_merged_weight():+ model = _peft_model(register = True)+ x = torch.randn(2, 5, 4, 16)+ out = model(x)+ assert out.shape == (2, 5, 16)+ out.sum().backward()+ layer = model.base_model.model.o_a_proj+ assert type(layer).__name__ == "GroupedLinearLoRA"+ assert layer.lora_A["default"].weight.grad is not None+ assert layer.lora_B["default"].weight.grad is not None+ # Merging lora_B @ lora_A into the block-diagonal weight gives the same forward.+ with torch.no_grad():+ merged = model.merge_and_unload()+ merged_out = merged(x)+ torch.testing.assert_close(merged_out, out.detach(), atol = 1e-5, rtol = 1e-5)+++def test_merge_into_an_fp8_grouped_weight_is_refused():+ """FP8GroupedLinear keeps an fp8 weight plus weight_scale_inv; B @ A cannot be added in place.+ PEFT merges layer by layer, so the dense layer ahead of it must not be merged either."""+ if not hasattr(torch, "float8_e4m3fn"):+ pytest.skip("torch without float8")+ from peft import LoraConfig, get_peft_model+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora++ class DenseFirst(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.q_proj = torch.nn.Linear(16, 16, bias = False) # merged first by PEFT+ self.o_a_proj = GroupedLinear(16, 4 * 8, 4)++ def forward(self, x):+ return self.o_a_proj(self.q_proj(x))++ torch.manual_seed(0)+ config = LoraConfig(+ r = 4, lora_alpha = 8, target_modules = ["q_proj", "o_a_proj"], init_lora_weights = False+ )+ block = DenseFirst()+ register_grouped_linear_lora(config, block)+ model = get_peft_model(block, config)+ base = model.base_model.model.o_a_proj.get_base_layer()+ with torch.no_grad():+ base.weight = torch.nn.Parameter(base.weight.to(torch.float8_e4m3fn), requires_grad = False)+ before = base.weight.clone()+ dense = model.base_model.model.q_proj+ dense_before = dense.get_base_layer().weight.clone()+ for merge in (model.merge_and_unload, model.merge_adapter):+ with pytest.raises(NotImplementedError, match = "fp8 grouped linear"):+ merge()+ assert torch.equal(base.weight.view(torch.uint8), before.view(torch.uint8))+ assert not model.base_model.model.o_a_proj.merged+ assert model.base_model.model.q_proj is dense and not dense.merged+ assert torch.equal(dense.get_base_layer().weight, dense_before)+++def test_grouped_lora_equals_the_diagonal_of_the_dense_delta():+ model = _peft_model(register = True)+ layer = model.base_model.model.o_a_proj+ x = torch.randn(3, 4, 16)+ with torch.no_grad():+ base = layer.base_layer(x)+ dense = layer.lora_B["default"](layer.lora_A["default"](x)) * layer.scaling["default"]+ dense = dense.view(3, 4, 4, 8)+ expected = base + torch.stack([dense[:, g, g] for g in range(4)], dim = 1)+ torch.testing.assert_close(layer(x), expected, atol = 1e-5, rtol = 1e-5)+++def test_state_dict_is_a_plain_lora_checkpoint():+ model = _peft_model(register = True)+ state = peft.get_peft_model_state_dict(model)+ assert state["base_model.model.o_a_proj.lora_A.weight"].shape == (4, 16)+ assert state["base_model.model.o_a_proj.lora_B.weight"].shape == (32, 4)+++def test_dora_is_refused_on_a_grouped_linear():+ """The grouped forward computes the plain LoRA sum only, so DoRA is refused."""+ from peft import LoraConfig+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora++ model = Block()+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["o_a_proj"], use_dora = True)+ with pytest.raises(NotImplementedError, match = "DoRA"):+ register_grouped_linear_lora(config, model)+++def test_a_variant_reaching_the_forward_is_refused():+ from peft import LoraConfig, get_peft_model++ model = Block()+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["o_a_proj"], init_lora_weights = False)+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora++ register_grouped_linear_lora(config, model)+ peft_model = get_peft_model(model, config)+ layer = peft_model.base_model.model.o_a_proj+ if not hasattr(layer, "lora_variant"):+ pytest.skip("this PEFT has no LoRA variants")+ layer.lora_variant["default"] = object()+ with pytest.raises(NotImplementedError, match = "variants"):+ peft_model(torch.randn(2, 4, 16))+++def test_dora_is_allowed_when_no_grouped_linear_is_targeted():+ """DoRA on the dense o_b_proj alone is valid: the grouped forward is never built."""+ from peft import LoraConfig+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora++ model = Block()+ config = LoraConfig(r = 4, lora_alpha = 8, target_modules = ["o_b_proj"], use_dora = True)+ assert register_grouped_linear_lora(config, model) == []+ regex = LoraConfig(r = 4, lora_alpha = 8, target_modules = ".*o_b_proj", use_dora = True)+ assert register_grouped_linear_lora(regex, model) == []+ everything = LoraConfig(r = 4, lora_alpha = 8, target_modules = None, use_dora = True)+ with pytest.raises(NotImplementedError, match = "DoRA"):+ register_grouped_linear_lora(everything, model)+++def test_a_saved_adapter_reloads_onto_the_grouped_forward(tmp_path):+ """The custom mapping is not in adapter_config.json, so a reload must register it again."""+ from peft import PeftModel+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora_for_adapter++ peft_model = _peft_model(register = True)+ x = torch.randn(2, 5, 4, 16)+ with torch.no_grad():+ want = peft_model(x)+ peft_model.save_pretrained(str(tmp_path))++ base = Block()+ base_state = {+ k.replace(".base_layer", ""): v+ for k, v in peft_model.base_model.model.state_dict().items()+ if "lora_" not in k+ }+ base.load_state_dict(base_state, strict = True)+ config = register_grouped_linear_lora_for_adapter(base, str(tmp_path))+ assert config is not None+ reloaded = PeftModel.from_pretrained(base, str(tmp_path), config = config, torch_device = "cpu")+ assert type(reloaded.base_model.model.o_a_proj).__name__ == "GroupedLinearLoRA"+ with torch.no_grad():+ got = reloaded(x)+ torch.testing.assert_close(got, want)+ # A model with no grouped linear reloads exactly as before.+ assert register_grouped_linear_lora_for_adapter(torch.nn.Linear(4, 4), str(tmp_path)) is None+++def test_fan_in_fan_out_is_reset_like_peft_does_for_nn_linear():+ """PEFT resets fan_in_fan_out for nn.Linear; the custom mapping skips that dispatcher."""+ from peft import LoraConfig, get_peft_model+ from unsloth.models.grouped_linear_lora import register_grouped_linear_lora++ torch.manual_seed(0)+ model = Block()+ config = LoraConfig(+ r = 4,+ lora_alpha = 8,+ target_modules = ["o_a_proj"],+ init_lora_weights = False,+ fan_in_fan_out = True,+ )+ register_grouped_linear_lora(config, model)+ model = get_peft_model(model, config)+ x = torch.randn(2, 5, 4, 16)+ with torch.no_grad():+ out = model(x)+ merged = model.merge_and_unload()(x)+ torch.testing.assert_close(merged, out, atol = 1e-5, rtol = 1e-5)diff --git a/tests/test_mistral_format_checkpoint.py b/tests/test_mistral_format_checkpoint.pynew file mode 100644index 00000000000..7fe5e870e70--- /dev/null+++ b/tests/test_mistral_format_checkpoint.py@@ -0,0 +1,77 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""A Mistral-format checkpoint (params.json, no config.json, e.g. Mistral-Large-3) gets a+message that says what it is, instead of the generic "both configs failed" one."""++import json+import os++import pytest+from real_accelerator import (+ has_real_accelerator,+) # tests/_shared, on sys.path via tests/conftest.py+import torch+++def _write(tmp_path, names):+ for name in names:+ (tmp_path / name).write_text(json.dumps({"dim": 8}))+ return str(tmp_path)+++def test_params_json_without_config_json_is_mistral_format(tmp_path):+ from unsloth.models.loader import _is_mistral_format_checkpoint+ assert _is_mistral_format_checkpoint(_write(tmp_path, ["params.json", "tekken.json"])) is True+++def test_a_params_json_without_a_mistral_marker_is_not_claimed(tmp_path):+ """Meta's original Llama layout also has params.json; the generic message must stay."""+ from unsloth.models.loader import _is_mistral_format_checkpoint++ assert (+ _is_mistral_format_checkpoint(+ _write(tmp_path, ["params.json", "consolidated.00.pth", "tokenizer.model"])+ )+ is False+ )+ assert (+ _is_mistral_format_checkpoint(+ _write(tmp_path, ["params.json", "consolidated.safetensors.index.json"])+ )+ is True+ )+++def test_a_config_json_next_to_params_json_is_a_transformers_repo(tmp_path):+ from unsloth.models.loader import _is_mistral_format_checkpoint+ assert _is_mistral_format_checkpoint(_write(tmp_path, ["params.json", "config.json"])) is False+++def test_an_empty_or_unknown_directory_is_not_claimed(tmp_path):+ from unsloth.models.loader import _is_mistral_format_checkpoint+ assert _is_mistral_format_checkpoint(str(tmp_path)) is False+ assert (+ _is_mistral_format_checkpoint(str(tmp_path / "does-not-exist"), local_files_only = True)+ is False+ )+++def test_the_message_names_the_file_and_the_route():+ from unsloth.models.loader import _mistral_format_error++ text = _mistral_format_error("mistralai/Mistral-Large-3-675B-Instruct-2512")+ assert "params.json" in text and "config.json" in text+ assert "vLLM" in text and "mistral-common" in text+ assert "Mistral-Large-3-675B-Instruct-2512" in text++[email protected](not has_real_accelerator(), reason = "import unsloth needs an accelerator")+def test_loader_raises_the_specific_message(tmp_path):+ """The arm that fails on main: the loader used to raise the generic message."""+ import unsloth # noqa: F401+ from unsloth import FastLanguageModel++ path = _write(tmp_path, ["params.json", "tekken.json"])+ with pytest.raises(RuntimeError) as info:+ FastLanguageModel.from_pretrained(path, max_seq_length = 64)+ assert "Mistral's own format" in str(info.value), str(info.value)[:400]+ assert "Both AutoConfig and PeftConfig" not in str(info.value)diff --git a/tests/test_remote_code_shims.py b/tests/test_remote_code_shims.pynew file mode 100644index 00000000000..f7f7f4d35d4--- /dev/null+++ b/tests/test_remote_code_shims.py@@ -0,0 +1,364 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""Remote code that embeds in `get_input_embeddings` or returns no loss (Step-3.7-Flash)."""++import sys++import pytest+import torch++transformers = pytest.importorskip("transformers")+from transformers import PreTrainedModel, PretrainedConfig+from transformers.modeling_outputs import CausalLMOutputWithPast+++class TinyConfig(PretrainedConfig):+ model_type = "tiny_remote"++ def __init__(+ self,+ vocab_size = 32,+ hidden_size = 8,+ **kwargs,+ ):+ self.vocab_size = vocab_size+ self.hidden_size = hidden_size+ super().__init__(**kwargs)+++class Inner(PreTrainedModel):+ config_class = TinyConfig++ def __init__(self, config):+ super().__init__(config)+ self.embed_tokens = torch.nn.Embedding(config.vocab_size, config.hidden_size)++ def get_input_embeddings(self, input_ids):+ return self.embed_tokens(input_ids)++ def forward(+ self,+ input_ids = None,+ inputs_embeds = None,+ **kwargs,+ ):+ if inputs_embeds is None:+ inputs_embeds = self.get_input_embeddings(input_ids)+ return inputs_embeds+++class Outer(PreTrainedModel):+ config_class = TinyConfig++ def __init__(self, config):+ super().__init__(config)+ self.model = Inner(config)+ self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias = False)++ def get_input_embeddings(self):+ return self.model.get_input_embeddings()++ def get_output_embeddings(self):+ return self.model.get_output_embeddings() # the inner model has no head: None++ def forward(+ self,+ input_ids = None,+ labels = None,+ **kwargs,+ ):+ logits = self.lm_head(self.model(input_ids))+ if labels is not None:+ self.config.text_config.vocab_size # the port's own loss code trips here+ return CausalLMOutputWithPast(logits = logits)+++# Remote code lives under transformers_modules; the loss shim keys on that.+Outer.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+# Newer transformers reads sys.modules[cls.__module__] while building a model+# (the experts implementation probe), so the name must resolve to a real module.+sys.modules.setdefault(Outer.__module__, sys.modules[__name__])+++def model():+ torch.manual_seed(0)+ return Outer(TinyConfig())+++def test_the_defect_before_the_shim(model):+ """The arm that fails on main."""+ with pytest.raises(TypeError, match = "missing 1 required positional argument"):+ model.get_input_embeddings()+++def test_accessor_serves_both_contracts_after_the_shim(model):+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ apply_remote_code_shims(+ model+ ) # class-level, so a second call in the same process repairs nothing new+ assert Inner._unsloth_original_get_input_embeddings is not None+ assert model.get_input_embeddings() is model.model.embed_tokens+ assert model.model.get_input_embeddings() is model.model.embed_tokens+ ids = torch.tensor([[1, 2, 3]])+ torch.testing.assert_close(model.model.get_input_embeddings(ids), model.model.embed_tokens(ids))+ model.enable_input_require_grads()+++def test_output_accessor_finds_the_head_the_port_forgot(model):+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ assert (+ model.get_output_embeddings() is None+ or Outer._unsloth_original_get_output_embeddings is not None+ )+ apply_remote_code_shims(model)+ assert model.get_output_embeddings() is model.lm_head+++def test_forward_gains_a_loss_when_the_original_has_none(model):+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ apply_remote_code_shims(model)+ assert Outer._unsloth_original_forward is not None+ ids = torch.randint(0, 32, (2, 6))+ out = model(input_ids = ids, labels = ids)+ assert out.loss is not None and torch.isfinite(out.loss)+ from transformers.loss.loss_utils import ForCausalLMLoss++ torch.testing.assert_close(out.loss, ForCausalLMLoss(out.logits, ids, 32))+ out.loss.backward()+ assert model.lm_head.weight.grad is not None+ assert model(input_ids = ids).loss is None+++def test_a_forward_that_returns_its_own_loss_is_left_alone():+ class Good(Outer):+ def forward(+ self,+ input_ids = None,+ labels = None,+ **kwargs,+ ):+ logits = self.lm_head(self.model(input_ids))+ return CausalLMOutputWithPast(loss = torch.tensor(42.0), logits = logits)++ Good.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ model = Good(TinyConfig())+ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (1, 4))+ assert float(model(input_ids = ids, labels = ids).loss) == 42.0+++def test_a_tuple_output_with_its_own_loss_is_left_alone():+ """return_dict = False gives (loss, logits); the model's own loss must survive the probe."""++ class TupleGood(Outer):+ def forward(+ self,+ input_ids = None,+ labels = None,+ **kwargs,+ ):+ logits = self.lm_head(self.model(input_ids))+ return (torch.tensor(42.0), logits) if labels is not None else (logits,)++ TupleGood.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ model = TupleGood(TinyConfig())+ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (1, 4))+ for _ in range(2):+ out = model(input_ids = ids, labels = ids)+ assert float(out[0]) == 42.0 and out[1].shape == (1, 4, 32)++[email protected]("healthy_first", [True, False])+def test_loss_support_is_decided_per_instance(healthy_first):+ """One remote class, two configs: only the broken one gets the synthesized loss."""++ class Mixed(Outer):+ def forward(+ self,+ input_ids = None,+ labels = None,+ **kwargs,+ ):+ logits = self.lm_head(self.model(input_ids))+ if labels is not None and self.config.own_loss:+ return CausalLMOutputWithPast(loss = torch.tensor(42.0), logits = logits)+ return CausalLMOutputWithPast(logits = logits)++ Mixed.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ healthy, broken = Mixed(TinyConfig(own_loss = True)), Mixed(TinyConfig(own_loss = False))+ apply_remote_code_shims(healthy)+ apply_remote_code_shims(broken)+ ids = torch.randint(0, 32, (1, 4))+ order = [healthy, broken] if healthy_first else [broken, healthy]+ for model in order + order:+ loss = float(model(input_ids = ids, labels = ids).loss)+ assert (loss == 42.0) is (model is healthy), (model.config.own_loss, loss)+++def test_a_subclass_override_of_a_repaired_accessor_is_repaired_too(model):+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ apply_remote_code_shims(model) # repairs Inner.get_input_embeddings++ class SubInner(Inner):+ def get_input_embeddings(self, input_ids):+ return self.embed_tokens(input_ids) * 2++ class SubOuter(Outer):+ def __init__(self, config):+ super().__init__(config)+ self.model = SubInner(config)++ SubOuter.__module__ = SubInner.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ sub = SubOuter(TinyConfig())+ apply_remote_code_shims(sub)+ assert sub.model.get_input_embeddings() is sub.model.embed_tokens+ ids = torch.randint(0, 32, (1, 4))+ assert torch.equal(sub.model.get_input_embeddings(ids), sub.model.embed_tokens(ids) * 2)+++def test_transformers_own_classes_are_not_touched():+ from unsloth.models.remote_code_shims import (+ apply_remote_code_shims,+ accessor_requires_arguments,+ )+ from transformers import LlamaConfig, LlamaForCausalLM++ model = LlamaForCausalLM(+ LlamaConfig(+ vocab_size = 16,+ hidden_size = 8,+ intermediate_size = 16,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ num_key_value_heads = 2,+ )+ )+ assert apply_remote_code_shims(model) == []+ assert not hasattr(LlamaForCausalLM, "_unsloth_original_forward")+ assert not accessor_requires_arguments(LlamaForCausalLM.get_input_embeddings)+++def test_the_repaired_forward_is_reached_through_an_accelerate_hook():+ """device_map loading hooks forward before the shims run (Step-3.7 in 16-bit)."""+ accelerate = pytest.importorskip("accelerate")+ from accelerate.hooks import add_hook_to_module, ModelHook+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ torch.manual_seed(0)+ model = Outer(TinyConfig())+ add_hook_to_module(model, ModelHook())+ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (2, 6))+ out = model(input_ids = ids, labels = ids)+ assert out.loss is not None and torch.isfinite(out.loss)+++def test_the_synthesized_loss_is_the_first_ordered_entry(model):+ """Positional readers take output[0] and to_tuple()[0] as the loss when labels were given."""+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (2, 6))+ out = model(input_ids = ids, labels = ids)+ assert list(out.keys())[0] == "loss"+ assert out[0] is out.loss and out.to_tuple()[0] is out.loss+++def test_positional_labels_reach_the_synthesized_loss(model):+ """Positional labels get the same loss as keyword labels."""+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (2, 6))+ by_keyword = model(input_ids = ids, labels = ids)+ by_position = model(ids, ids)+ assert by_position.loss is not None+ torch.testing.assert_close(by_position.loss, by_keyword.loss)+++def test_a_forward_without_a_loss_runs_once_on_the_probing_call():+ """A second forward would hold both autograd graphs at once."""+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ calls = []++ class NoLoss(Outer):+ def forward(+ self,+ input_ids = None,+ labels = None,+ **kwargs,+ ):+ calls.append(labels is not None)+ return CausalLMOutputWithPast(logits = self.lm_head(self.model(input_ids)))++ NoLoss.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ torch.manual_seed(0)+ model = NoLoss(TinyConfig())+ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (2, 6))+ out = model(input_ids = ids, labels = ids)+ assert calls == [True]+ from transformers.loss.loss_utils import ForCausalLMLoss++ torch.testing.assert_close(out.loss, ForCausalLMLoss(out.logits, ids, 32))+ model(input_ids = ids, labels = ids)+ assert calls == [True, False]+++def test_non_token_logits_never_get_a_causal_loss():+ """A classification head's (batch, n_labels) logits must not be shifted across examples."""+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ class Classifier(Outer):+ def forward(+ self,+ input_ids = None,+ labels = None,+ **kwargs,+ ):+ return CausalLMOutputWithPast(logits = self.lm_head(self.model(input_ids)).mean(1))++ Classifier.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ model = Classifier(TinyConfig())+ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (4, 6))+ with pytest.raises(RuntimeError, match = "token-level"):+ model(input_ids = ids, labels = torch.tensor([0, 1, 2, 3]))+++def test_an_unrelated_first_call_error_does_not_switch_the_objective():+ """A failing first call must not pin the fallback: the model's own loss wins once calls work."""+ from unsloth.models.remote_code_shims import apply_remote_code_shims++ class Picky(Outer):+ def forward(+ self,+ input_ids = None,+ labels = None,+ bad = False,+ **kwargs,+ ):+ if bad:+ raise TypeError("bad batch")+ logits = self.lm_head(self.model(input_ids))+ return CausalLMOutputWithPast(loss = torch.tensor(7.0), logits = logits)++ Picky.__module__ = "transformers_modules.tiny_remote.modeling_tiny"+ model = Picky(TinyConfig())+ apply_remote_code_shims(model)+ ids = torch.randint(0, 32, (1, 4))+ with pytest.raises(TypeError, match = "bad batch"):+ model(input_ids = ids, labels = ids, bad = True)+ assert float(model(input_ids = ids, labels = ids).loss) == 7.0diff --git a/unsloth/models/grouped_linear_lora.py b/unsloth/models/grouped_linear_lora.pynew file mode 100644index 00000000000..c51678f02a1--- /dev/null+++ b/unsloth/models/grouped_linear_lora.py@@ -0,0 +1,193 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""LoRA for block-diagonal grouped linears (DeepSeek-V4 `o_a_proj`, `FP8GroupedLinear`).++PEFT's dense LoRA sum has the wrong shape for them; only the forward changes (group g uses+its own row block of `lora_B`), so saving, loading and merging are unchanged.+"""++import functools++import torch++__all__ = [+ "is_grouped_linear",+ "grouped_linear_classes",+ "register_grouped_linear_lora",+]+++def is_grouped_linear(module):+ return (+ isinstance(module, torch.nn.Linear)+ and isinstance(getattr(module, "n_groups", None), int)+ and type(module).forward is not torch.nn.Linear.forward+ )+++def grouped_linear_classes(model):+ classes = []+ for module in model.modules():+ if is_grouped_linear(module) and type(module) not in classes:+ classes.append(type(module))+ return classes+++def _grouped_lora_layer():+ from peft.tuners.lora.layer import Linear as LoraLinear+ class GroupedLinearLoRA(LoraLinear):+ _unsloth_grouped_lora = True++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ # PEFT's nn.Linear dispatcher resets this; the custom mapping skips it.+ self.fan_in_fan_out = False++ def merge(self, *args, **kwargs):+ _refuse_fp8_grouped_merge([self])+ return super().merge(*args, **kwargs)++ def forward(self, x, *args, **kwargs):+ self._check_forward_args(x, *args, **kwargs)+ adapter_names = kwargs.pop("adapter_names", None)+ if self.disable_adapters:+ if self.merged:+ self.unmerge()+ return self.base_layer(x, *args, **kwargs)+ if adapter_names is not None:+ raise NotImplementedError(+ "Unsloth: mixed adapter batches are not supported on grouped linears."+ )+ if self.merged:+ return self.base_layer(x, *args, **kwargs)++ result = self.base_layer(x, *args, **kwargs)+ result_dtype = result.dtype+ n_groups = self.base_layer.n_groups+ out_per_group = result.shape[-1]+ for active_adapter in self.active_adapters:+ if active_adapter not in self.lora_A:+ continue+ if active_adapter in getattr(self, "lora_variant", {}):+ # Variants (DoRA) replace the plain LoRA sum, which is all this layer computes.+ raise NotImplementedError(+ "Unsloth: DoRA and other LoRA variants are not supported on grouped "+ "linears (block-diagonal `o_a_proj`). Use plain LoRA for these layers."+ )+ lora_A = self.lora_A[active_adapter]+ lora_B = self.lora_B[active_adapter]+ dropout = self.lora_dropout[active_adapter]+ scaling = self.scaling[active_adapter]+ x_cast = self._cast_input_dtype(x, lora_A.weight.dtype)+ low_rank = lora_A(dropout(x_cast))+ # lora_B.weight is (n_groups * out_per_group, r): block g is rows of group g.+ weight_B = lora_B.weight.view(n_groups, out_per_group, -1)+ delta = torch.einsum("...gr,gor->...go", low_rank, weight_B)+ if lora_B.bias is not None:+ delta = delta + lora_B.bias.view(n_groups, out_per_group)+ result = result + delta.to(result_dtype) * scaling+ return result.to(result_dtype)++ return GroupedLinearLoRA+++def _refuse_fp8_grouped_merge(modules):+ """PEFT adds B @ A to the stored weight; an FP8GroupedLinear's weight is fp8 read with an+ unchanged weight_scale_inv, so that merge is wrong or raises."""+ for module in modules:+ if not getattr(module, "_unsloth_grouped_lora", False):+ continue+ weight = getattr(module.get_base_layer(), "weight", None)+ if weight is not None and weight.dtype.itemsize == 1 and weight.is_floating_point():+ raise NotImplementedError(+ "Unsloth: cannot merge LoRA into an fp8 grouped linear in place. Load the "+ "model in 16-bit to merge, or save the adapter on its own."+ )+++def _preflight_peft_merges():+ """Refuse before PEFT merges anything: it merges layer by layer, so a refusal from the+ grouped layer itself would leave the earlier layers already merged."""+ try:+ from peft.tuners.tuners_utils import BaseTuner+ except Exception:+ return+ for name in ("_unload_and_optionally_merge", "merge_adapter"):+ original = BaseTuner.__dict__.get(name)+ if original is None or getattr(original, "_unsloth_fp8_grouped_preflight", False):+ continue++ def make(original, name):+ def wrapped(self, *args, **kwargs):+ merging = name == "merge_adapter" or kwargs.get("merge", args[0] if args else True)+ if merging:+ _refuse_fp8_grouped_merge(self.model.modules())+ return original(self, *args, **kwargs)++ wrapped._unsloth_fp8_grouped_preflight = True+ return functools.wraps(original)(wrapped)++ setattr(BaseTuner, name, make(original, name))+++def _targets_module(lora_config, name):+ """Whether `lora_config` selects the module called `name`, by PEFT's own matcher.++ `target_modules = None` or an unreadable config counts as targeted.+ """+ target_modules = getattr(lora_config, "target_modules", None)+ if target_modules is None or target_modules == "all-linear":+ return True+ try:+ from peft.tuners.tuners_utils import check_target_module_exists+ return bool(check_target_module_exists(lora_config, name))+ except Exception:+ return True+++def targeted_grouped_linear_classes(lora_config, model):+ classes = []+ for name, module in model.named_modules():+ if (+ is_grouped_linear(module)+ and type(module) not in classes+ and _targets_module(lora_config, name)+ ):+ classes.append(type(module))+ return classes+++def register_grouped_linear_lora(lora_config, model):+ """Map every targeted grouped-linear class in `model` to `GroupedLinearLoRA` on `lora_config`; returns them."""+ classes = targeted_grouped_linear_classes(lora_config, model)+ if not classes or not hasattr(lora_config, "_register_custom_module"):+ return []+ if getattr(lora_config, "use_dora", False):+ raise NotImplementedError(+ "Unsloth: `use_dora = True` is not supported on a model with block-diagonal grouped "+ "linears (" + ", ".join(cls.__name__ for cls in classes) + "): the grouped LoRA "+ "forward computes the plain LoRA sum only, so the DoRA magnitude vector would never "+ "train. Use plain LoRA."+ )+ layer = _grouped_lora_layer()+ _preflight_peft_merges()+ lora_config._register_custom_module({cls: layer for cls in classes})+ return classes+++def register_grouped_linear_lora_for_adapter(model, adapter_path, **hub_kwargs):+ """The `PeftConfig` of a saved adapter with the grouped mapping registered, or None.++ The mapping holds class objects, so it is never in the saved adapter config.+ """+ if not grouped_linear_classes(model):+ return None+ try:+ from peft import PeftConfig+ peft_config = PeftConfig.from_pretrained(adapter_path, **hub_kwargs)+ except Exception:+ return None+ if not register_grouped_linear_lora(peft_config, model):+ return None+ return peft_configdiff --git a/unsloth/models/loader.py b/unsloth/models/loader.pyindex 1cb7d5950c8..944fe66a5c8 100644--- a/unsloth/models/loader.py+++ b/unsloth/models/loader.py@@ -32,6 +32,7 @@ from .cohere import FastCohereModelfrom transformers import AutoConfigfrom transformers import __version__ as transformers_versionfrom peft import PeftConfig, PeftModel+from .grouped_linear_lora import register_grouped_linear_lora_for_adapterfrom .loader_utils import (DEFAULT_DEVICE_MAP,OFFLOAD_EMBEDDING_AUTO,@@ -301,6 +302,43 @@ def _config_diff(config):return {}+def _is_mistral_format_checkpoint(+ model_name,+ token = None,+ revision = None,+ local_files_only = False,+):+ """True for a checkpoint in Mistral's own format (`params.json`, no `config.json`), which+ AutoConfig cannot read. Answers False on any doubt, including offline."""+ # Meta's original Llama checkpoints also ship `params.json`, so require a Mistral-only file.+ markers = ("tekken.json", "consolidated.safetensors", "consolidated.safetensors.index.json")+ try:+ if os.path.isdir(model_name):+ has = lambda name: os.path.isfile(os.path.join(model_name, name))+ else:+ if local_files_only:+ return False+ from huggingface_hub import file_exists+ has = lambda name: file_exists(model_name, name, revision = revision, token = token)+ return has("params.json") and not has("config.json") and any(has(m) for m in markers)+ except Exception:+ return False+++def _mistral_format_error(model_name):+ return (+ f"Unsloth: `{model_name}` is a checkpoint in Mistral's own format: it ships `params.json` "+ "and no `config.json`, and transformers has no modeling code for it (the model card says "+ "so and points at vLLM).\n"+ "Unsloth trains through transformers, so this checkpoint cannot be loaded for training "+ "until transformers gains an implementation or a transformers-format conversion of the "+ "weights is published. For inference use vLLM with mistral-common, as the model card "+ "describes.\n"+ "If you meant a transformers-format repo, check the repo id: the converted uploads carry "+ "a `config.json`."+ )++def _has_sequence_classification_architecture(config):architectures = _config_get(config, "architectures", None) or []return any(str(arch).endswith("ForSequenceClassification") for arch in architectures)@@ -955,6 +993,8 @@ class FastLanguageModel(FastLlamaModel):f'Try `pip install --upgrade "transformers>=4.43.2"`\n'f"to obtain the latest transformers build, then restart this session.")+ if _is_mistral_format_checkpoint(model_name, token, base_revision, local_files_only):+ raise RuntimeError(_mistral_format_error(model_name)) from autoconfig_exccombined_error = ("Unsloth: Failed to load model. Both AutoConfig and PeftConfig loading failed.\n\n"f"AutoConfig error: {autoconfig_error}\n\n"@@ -1310,6 +1350,17 @@ class FastLanguageModel(FastLlamaModel):peft_load_kwargs = {}if kwargs.get("cache_dir") is not None:peft_load_kwargs["cache_dir"] = kwargs["cache_dir"]+ # Grouped linears (DeepSeek-V4 o_a_proj): the LoRA mapping is not saved, re-register it.+ _grouped_config = register_grouped_linear_lora_for_adapter(+ model,+ old_model_name,+ token = token,+ revision = revision,+ local_files_only = local_files_only,+ **peft_load_kwargs,+ )+ if _grouped_config is not None:+ peft_load_kwargs["config"] = _grouped_configmodel = PeftModel.from_pretrained(model,old_model_name,@@ -1758,6 +1809,8 @@ class FastModel(FastBaseModel):f'Try `pip install --upgrade "transformers>=4.43.2"`\n'f"to obtain the latest transformers build, then restart this session.")+ if _is_mistral_format_checkpoint(model_name, token, base_revision, local_files_only):+ raise RuntimeError(_mistral_format_error(model_name)) from autoconfig_exccombined_error = ("Unsloth: Failed to load model. Both AutoConfig and PeftConfig loading failed.\n\n"f"AutoConfig error: {autoconfig_error}\n\n"@@ -2437,6 +2490,16 @@ class FastModel(FastBaseModel):peft_load_kwargs = {}if kwargs.get("cache_dir") is not None:peft_load_kwargs["cache_dir"] = kwargs["cache_dir"]+ _grouped_config = register_grouped_linear_lora_for_adapter(+ model,+ old_model_name,+ token = token,+ revision = revision,+ local_files_only = local_files_only,+ **peft_load_kwargs,+ )+ if _grouped_config is not None:+ peft_load_kwargs["config"] = _grouped_configtry:model = PeftModel.from_pretrained(model,diff --git a/unsloth/models/remote_code_shims.py b/unsloth/models/remote_code_shims.pynew file mode 100644index 00000000000..25dd38b63f6--- /dev/null+++ b/unsloth/models/remote_code_shims.py@@ -0,0 +1,313 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Repairs for remote modeling code (vLLM ports such as Step-3.7-Flash) that breaks training:++* `get_input_embeddings(self, input_ids)` returns embedded tokens, not the embedding module.+* `forward(..., labels=...)` accepts labels but returns no loss, or fails in its loss code.++Only the checkpoint's own classes are patched, and the original behaviour stays reachable.+"""++import functools+import inspect++import torch++__all__ = [+ "apply_remote_code_shims",+ "accessor_requires_arguments",+ "find_embedding_module",+]++_EMBEDDING_ATTRIBUTES = ("embed_tokens", "wte", "word_embeddings", "tok_embeddings", "embeddings")+++def accessor_requires_arguments(function):+ """True when `function(self)` cannot be called: a required parameter follows self."""+ try:+ parameters = list(inspect.signature(function).parameters.values())+ except (TypeError, ValueError):+ return False+ return any(+ p.default is inspect.Parameter.empty+ and p.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)+ for p in parameters[1:]+ )+++def _vocab_sizes(module):+ config = getattr(module, "config", None)+ sizes = set()+ for holder in (+ config,+ getattr(config, "text_config", None),+ getattr(config, "get_text_config", lambda: None)(),+ ):+ size = getattr(holder, "vocab_size", None)+ if isinstance(size, int):+ sizes.add(size)+ return sizes+++def find_embedding_module(module):+ for name in _EMBEDDING_ATTRIBUTES:+ child = getattr(module, name, None)+ if isinstance(child, torch.nn.Embedding):+ return child+ from transformers import PreTrainedModel++ for child in module.children():+ if isinstance(child, PreTrainedModel) and not accessor_requires_arguments(+ type(child).get_input_embeddings+ ):+ try:+ embedding = child.get_input_embeddings()+ except Exception:+ continue+ if isinstance(embedding, torch.nn.Module):+ return embedding+ sizes = _vocab_sizes(module)+ for child in module.modules():+ if isinstance(child, torch.nn.Embedding) and child.num_embeddings in sizes:+ return child+ return None+++def _repair_accessor(cls):+ original = cls.__dict__.get("get_input_embeddings")+ if original is None or "_unsloth_original_get_input_embeddings" in cls.__dict__:+ return False++ @functools.wraps(original)+ def get_input_embeddings(self, *args, **kwargs):+ if args or kwargs:+ return original(self, *args, **kwargs)+ embedding = find_embedding_module(self)+ if embedding is None:+ raise NotImplementedError(+ f"Unsloth: `{type(self).__name__}.get_input_embeddings` embeds tokens instead of returning "+ "the embedding module, and no token embedding could be located to stand in for it."+ )+ return embedding++ cls.get_input_embeddings = get_input_embeddings+ cls._unsloth_original_get_input_embeddings = original+ return True+++def _is_remote_code(cls):+ return "transformers_modules" in (getattr(cls, "__module__", "") or "")+++_OUTPUT_HEAD_ATTRIBUTES = ("lm_head", "output", "embed_out", "output_layer")+++def find_output_head(module):+ for name in _OUTPUT_HEAD_ATTRIBUTES:+ child = getattr(module, name, None)+ if isinstance(child, torch.nn.Module) and hasattr(child, "weight"):+ return child+ return None+++def _repair_output_accessor(cls):+ """`get_output_embeddings` that returns None while the class owns an `lm_head` (Step-3.7 delegates to a headless inner model)."""+ original = cls.__dict__.get("get_output_embeddings")+ if original is None or "_unsloth_original_get_output_embeddings" in cls.__dict__:+ return False++ @functools.wraps(original)+ def get_output_embeddings(self, *args, **kwargs):+ try:+ head = original(self, *args, **kwargs)+ except (AttributeError, TypeError, NotImplementedError):+ head = None+ if head is None and not args and not kwargs:+ head = find_output_head(self)+ return head++ cls.get_output_embeddings = get_output_embeddings+ cls._unsloth_original_get_output_embeddings = original+ return True+++def _output_accessor_is_broken(model):+ if find_output_head(model) is None:+ return False+ try:+ return model.get_output_embeddings() is None+ except (AttributeError, TypeError, NotImplementedError):+ return True+++def _fill_missing_loss(cls):+ """Wrap `cls.forward` so a call with labels always yields a loss.++ The first labelled call probes the original; if it gives no loss, labels are withheld+ from then on and the causal LM loss is computed from its logits.+ """+ original = cls.__dict__.get("forward")+ # Own dict only: a subclass of an already repaired class has its own unwrapped forward.+ if original is None or "_unsloth_original_forward" in cls.__dict__:+ return False+ try:+ parameters = inspect.signature(original).parameters+ except (TypeError, ValueError):+ return False+ if "labels" not in parameters:+ return False++ # Per instance: two configs of one remote class can differ in whether the loss works.+ state_key = "_unsloth_returns_loss"++ def _loss_from(output, labels, kwargs):+ logits = (+ output.get("logits", None)+ if isinstance(output, dict)+ else output[0]+ if isinstance(output, tuple)+ else None+ )+ if logits is None:+ return None+ if logits.ndim != 3 or tuple(logits.shape[:2]) != tuple(labels.shape):+ raise RuntimeError(+ f"Unsloth: `{cls.__name__}.forward` returned no loss and its logits {tuple(logits.shape)} are not "+ f"token-level logits for labels {tuple(labels.shape)}, so no causal LM loss can stand in for it."+ )+ from transformers.loss.loss_utils import ForCausalLMLoss++ return ForCausalLMLoss(+ logits = logits,+ labels = labels,+ vocab_size = logits.shape[-1],+ num_items_in_batch = kwargs.get("num_items_in_batch", None),+ )++ def _has_own_loss(output):+ if isinstance(output, dict):+ return output.get("loss", None) is not None+ # return_dict = False: (loss, logits, ...) when labels were given; logits are never 0-d.+ if isinstance(output, (tuple, list)) and output:+ first = output[0]+ return isinstance(first, torch.Tensor) and first.ndim == 0 and first.is_floating_point()+ return False++ try:+ signature = inspect.signature(original)+ except (TypeError, ValueError):+ signature = None+ self_placeholder = object()++ def _bind(args, kwargs):+ """Move a positional `labels` into kwargs; anything unbindable is left as it came."""+ if not args or signature is None:+ return args, kwargs+ try:+ bound = signature.bind_partial(self_placeholder, *args, **kwargs)+ except TypeError:+ return args, kwargs+ flat = {}+ for name, parameter in signature.parameters.items():+ if name not in bound.arguments:+ continue+ if parameter.kind is inspect.Parameter.VAR_KEYWORD:+ flat.update(bound.arguments[name])+ elif parameter.kind is inspect.Parameter.VAR_POSITIONAL:+ return args, kwargs+ else:+ flat[name] = bound.arguments[name]+ flat.pop(next(iter(signature.parameters)), None)+ return (), flat++ @functools.wraps(original)+ def forward(self, *args, **kwargs):+ args, kwargs = _bind(args, kwargs)+ labels = kwargs.get("labels", None)+ returns_loss = self.__dict__.get(state_key, None)+ if labels is None or returns_loss is True:+ return original(self, *args, **kwargs)+ output = None+ if returns_loss is None:+ try:+ output = original(self, *args, **kwargs)+ if _has_own_loss(output):+ self.__dict__[state_key] = True+ return output+ except (AttributeError, TypeError, KeyError):+ output = None+ kwargs = dict(kwargs)+ kwargs.pop("labels")+ # Reuse the probe's logits: a second forward would hold two graphs at once.+ loss = None if output is None else _loss_from(output, labels, kwargs)+ if loss is None:+ del output+ output = original(self, *args, **kwargs)+ loss = _loss_from(output, labels, kwargs)+ if loss is None:+ raise RuntimeError(+ f"Unsloth: `{cls.__name__}.forward` returned neither a loss nor logits, so no loss can be trained on."+ )+ if returns_loss is None:+ # Cached only once a no-label forward worked: a first call failing for another reason must not pin it.+ self.__dict__[state_key] = False+ print(+ f"Unsloth: `{cls.__name__}.forward` accepts `labels` but returns no loss, "+ "so the causal LM loss is computed from its logits."+ )+ if isinstance(output, dict):+ # `loss` must come first: positional readers take output[0] as the loss.+ fields = {k: v for k, v in output.items() if k != "loss"}+ try:+ return type(output)(loss = loss, **fields)+ except Exception:+ rebuilt = type(output)()+ rebuilt["loss"] = loss+ for k, v in fields.items():+ rebuilt[k] = v+ return rebuilt+ return (loss,) + tuple(output)++ cls.forward = forward+ cls._unsloth_original_forward = original+ return True+++def _rebind_accelerate_hook(model):+ """Point an accelerate hook attached during loading at the repaired forward.++ `device_map` loading keeps the bound original as `model._old_forward`, bypassing class repairs.+ """+ if getattr(type(model), "_unsloth_original_forward", None) is None:+ return+ if "_old_forward" not in vars(model):+ return+ import types++ model._old_forward = types.MethodType(type(model).forward, model)+++def apply_remote_code_shims(model):+ from transformers import PreTrainedModel++ repaired = []+ # Deepest first, so a parent's accessor can delegate to an already repaired child.+ modules = [m for m in model.modules() if isinstance(m, PreTrainedModel)]+ seen = set()+ for module in reversed(modules):+ cls = type(module)+ if cls in seen:+ continue+ seen.add(cls)+ if accessor_requires_arguments(cls.get_input_embeddings) and _repair_accessor(cls):+ repaired.append(f"{cls.__name__}.get_input_embeddings")+ cls = type(model)+ if _is_remote_code(cls) and _output_accessor_is_broken(model) and _repair_output_accessor(cls):+ repaired.append(f"{cls.__name__}.get_output_embeddings")+ if _is_remote_code(cls) and _fill_missing_loss(cls):+ repaired.append(f"{cls.__name__}.forward")+ _rebind_accelerate_hook(model)+ if repaired:+ print("Unsloth: Repaired remote modeling code so it trains: " + ", ".join(repaired) + ".")+ return repaireddiff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex e1917d8a81c..dc2397d85ad 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -94,6 +94,8 @@ from ._utils import (from ._utils import *from ._remote_code_buffers import restore_remote_code_non_persistent_buffersfrom ._custom_dtype import resolve_dtype, trusted_custom_dtype+from .remote_code_shims import apply_remote_code_shims+from .grouped_linear_lora import register_grouped_linear_lorafrom .loader_utils import (DEFAULT_DEVICE_MAP,OFFLOAD_EMBEDDING_AUTO,@@ -2378,6 +2380,8 @@ class FastBaseModel:# transformers 5 leaves remote code's non-persistent buffers (RoPE inv_freq, decay slopes) uninitialised.restore_remote_code_non_persistent_buffers(model)# Must precede _attach_bnb_multidevice_hooks: it returns early while offload_embedding is True.+ # Repair remote code first so the offload decision reads the real input embeddings.+ apply_remote_code_shims(model)offload_embedding = _resolve_offload_embedding(model,offload_embedding,@@ -3142,6 +3146,14 @@ class FastBaseModel:lora_config = LoraConfig(**{k: v for k, v in local_variables.items() if k in allowed_parameters},)+ # Block-diagonal grouped linears (DeepSeek-V4's o_a_proj) need a LoRA forward that is grouped too.+ _grouped_classes = register_grouped_linear_lora(lora_config, model)+ if _grouped_classes:+ print(+ "Unsloth: Using a grouped LoRA forward on "+ + ", ".join(cls.__name__ for cls in _grouped_classes)+ + " (block-diagonal linears)."+ )model = prepare_model_for_kbit_training(model,use_gradient_checkpointing = use_gradient_checkpointing,