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
Fix silent dropping of embed_tokens/lm_head when listed in target_modules (#9331)
Chakshu Dhannawatedd81b4f8df9
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex e1a7fecd4bd..00ba6dc5911 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -1367,6 +1367,7 @@ class UnslothTrainer:peft_kwargs = dict(r = lora_r,target_modules = target_modules,+ modules_to_save = modules_to_save,lora_alpha = lora_alpha,lora_dropout = lora_dropout,bias = "none",@@ -1398,6 +1399,7 @@ class UnslothTrainer:self.model,r = lora_r,target_modules = target_modules,+ modules_to_save = modules_to_save,lora_alpha = lora_alpha,lora_dropout = lora_dropout,bias = "none",@@ -1417,6 +1419,7 @@ class UnslothTrainer:self.model,r = lora_r,target_modules = target_modules,+ modules_to_save = modules_to_save,lora_alpha = lora_alpha,lora_dropout = lora_dropout,bias = "none",diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex d21218f24f0..b79ca5f2d80 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -4637,12 +4637,16 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) -># ── 4d. Prepare model (LoRA, full finetuning, or CPT) ──if is_cpt:_send_status(event_queue, "Configuring LoRA for continued pretraining...")- # embed_tokens (if included) goes to modules_to_save -- trained full-precision at- # embedding_learning_rate. lm_head stays a LoRA target for merges (unsloth PR #4106).+ # Both go to modules_to_save: trained full-precision at+ # embedding_learning_rate, since LoRA on either never trains.+ # By leaf: PEFT resolves model.embed_tokens to the same module.+ _embedding_modules = ("embed_tokens", "lm_head")_user_modules = config.get("target_modules") or []- wants_embed = "embed_tokens" in _user_modules- cpt_trains_embeddings = wants_embed- cpt_target_modules = [m for m in _user_modules if m != "embed_tokens"]+ _leaf = lambda m: str(m).rsplit(".", 1)[-1] # noqa: E731+ _wants = [m for m in _user_modules if _leaf(m) in _embedding_modules]+ # Either module in modules_to_save fills the embedding_learning_rate group.+ cpt_trains_embeddings = bool(_wants)+ cpt_target_modules = [m for m in _user_modules if _leaf(m) not in _embedding_modules]if not cpt_target_modules:cpt_target_modules = ["q_proj",@@ -4652,12 +4656,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->"gate_proj","up_proj","down_proj",- "lm_head",]success = trainer.prepare_model_for_training(use_lora = True,target_modules = cpt_target_modules,- modules_to_save = ["embed_tokens"] if wants_embed else None,+ modules_to_save = _wants or None,lora_r = config.get("lora_r", 128),lora_alpha = config.get("lora_alpha", 32),lora_dropout = config.get("lora_dropout", 0.0),@@ -4728,8 +4731,8 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->)elif embedding_lr_value is not None:logger.warning(- "CPT: embedding_learning_rate was provided but embed_tokens is "- "not being trained; ignoring the override.\n"+ "CPT: embedding_learning_rate was provided but neither embed_tokens "+ "nor lm_head is being trained; ignoring the override.\n")embedding_lr_value = Nonediff --git a/studio/backend/tests/test_cpt_modules_to_save_reaches_every_branch.py b/studio/backend/tests/test_cpt_modules_to_save_reaches_every_branch.pynew file mode 100644index 00000000000..039b9d6e587--- /dev/null+++ b/studio/backend/tests/test_cpt_modules_to_save_reaches_every_branch.py@@ -0,0 +1,54 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Studio's CPT path routes embed_tokens/lm_head through `modules_to_save`.++Every branch of `Trainer.prepare_model_for_training` that builds an adapter therefore+has to forward that argument. The audio branches used to omit it, which silently froze+the matrices the run was configured to train while still applying an embedding LR.+"""++import ast+import os++TRAINER = os.path.join(+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),+ "core",+ "training",+ "trainer.py",+)+++def _peft_calls():+ """Every get_peft_model call, plus the peft_kwargs dict that feeds one."""+ tree = ast.parse(open(TRAINER, encoding = "utf-8").read())+ fn = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "prepare_model_for_training"+ )+ calls = []+ for node in ast.walk(fn):+ if not isinstance(node, ast.Call):+ continue+ name = getattr(node.func, "attr", None)+ if name == "get_peft_model" or (name is None and getattr(node.func, "id", None) == "dict"):+ kwargs = {k.arg for k in node.keywords if k.arg}+ # Only the dicts that actually build an adapter.+ if name == "get_peft_model" or "target_modules" in kwargs:+ calls.append((node.lineno, kwargs))+ return calls+++def test_every_adapter_call_forwards_modules_to_save():+ calls = _peft_calls()+ assert len(calls) >= 5, f"expected every branch, found {len(calls)}"+ missing = [+ lineno+ for lineno, kwargs in calls+ if "target_modules" in kwargs and "modules_to_save" not in kwargs+ ]+ assert not missing, (+ f"trainer.py lines {missing} build an adapter without modules_to_save; "+ "a CPT run there would silently not train the embeddings it asked for"+ )diff --git a/studio/backend/tests/test_vram_estimation.py b/studio/backend/tests/test_vram_estimation.pyindex 2def8738e26..4d71e8d5898 100644--- a/studio/backend/tests/test_vram_estimation.py+++ b/studio/backend/tests/test_vram_estimation.py@@ -2319,3 +2319,69 @@ class TestErnieVlSharedExpertWidth(unittest.TestCase):if __name__ == "__main__":unittest.main()+++def test_embedding_targets_cost_full_matrices_not_lora_pairs():+ """embed_tokens/lm_head are redirected to modules_to_save, so they cost vocab*hidden."""+ from utils.hardware.vram_estimation import _full_weight_embedding_elements++ untied = replace(LLAMA_8B, tie_word_embeddings = False)+ one = untied.vocab_size * untied.hidden_size++ assert _full_weight_embedding_elements(untied, DEFAULT_TARGET_MODULES) == 0+ assert _full_weight_embedding_elements(untied, DEFAULT_TARGET_MODULES + ["embed_tokens"]) == one+ assert (+ _full_weight_embedding_elements(+ untied, DEFAULT_TARGET_MODULES + ["embed_tokens", "lm_head"]+ )+ == 2 * one+ )++ # A tied pair gets ensure_weight_tying, which leaves ONE trainable matrix.+ tied = replace(LLAMA_8B, tie_word_embeddings = True)+ assert (+ _full_weight_embedding_elements(tied, DEFAULT_TARGET_MODULES + ["embed_tokens", "lm_head"])+ == tied.vocab_size * tied.hidden_size+ )++ # Regex / all-linear / None never carry these names.+ assert _full_weight_embedding_elements(untied, "all-linear") == 0+ assert _full_weight_embedding_elements(untied, None) == 0+++def test_embedding_targets_feed_optimizer_and_gradient_bytes():+ """The count drives trainable_params, so it must reach compute_lora_params."""+ untied = replace(LLAMA_8B, tie_word_embeddings = False)+ base = compute_lora_params(untied, 16, DEFAULT_TARGET_MODULES)+ with_embed = compute_lora_params(untied, 16, DEFAULT_TARGET_MODULES + ["embed_tokens"])+ assert with_embed - base == untied.vocab_size * untied.hidden_size+++def test_an_embedding_only_request_still_counts_the_default_projections():+ """Counting only the embeddings under-reports by every projection adapter the CPT+ fallback adds."""+ tied = replace(LLAMA_8B, tie_word_embeddings = True)+ projections = compute_lora_params(tied, 128, list(DEFAULT_TARGET_MODULES))+ one_matrix = tied.vocab_size * tied.hidden_size+ for targets in (["embed_tokens"], ["embed_tokens", "lm_head"], ["lm_head"]):+ assert compute_lora_params(tied, 128, targets) == projections + one_matrix, targets+ # "all-linear" expands in the trainer too, but matches no counter here unnormalized.+ for targets in (["all-linear", "lm_head"], ["all-linear", "embed_tokens"]):+ assert compute_lora_params(tied, 128, targets) == projections + one_matrix, targets+++def test_qualified_embedding_names_are_counted_too():+ """PEFT matches on the module suffix, so model.embed_tokens is the same matrix and+ must not be estimated as if no embedding were trained."""+ tied = replace(LLAMA_8B, tie_word_embeddings = True)+ projections = compute_lora_params(tied, 128, list(DEFAULT_TARGET_MODULES))+ one_matrix = tied.vocab_size * tied.hidden_size+ for targets in (+ ["model.embed_tokens"],+ list(DEFAULT_TARGET_MODULES) + ["model.embed_tokens"],+ list(DEFAULT_TARGET_MODULES) + ["language_model.lm_head"],+ ["all-linear", "model.embed_tokens"],+ ):+ assert compute_lora_params(tied, 128, targets) == projections + one_matrix, targets+ # A qualified projection is NOT an embedding and keeps its low-rank cost.+ assert compute_lora_params(tied, 128, ["layers.0.q_proj"]) < one_matrixdiff --git a/studio/backend/utils/hardware/vram_estimation.py b/studio/backend/utils/hardware/vram_estimation.pyindex 86069ead3d3..2ade2c96c60 100644--- a/studio/backend/utils/hardware/vram_estimation.py+++ b/studio/backend/utils/hardware/vram_estimation.py@@ -907,9 +907,41 @@ def _lora_mlp_elements(return total+EMBEDDING_TARGET_MODULES = frozenset(("embed_tokens", "lm_head"))+++def _embedding_leaves(target_modules) -> set:+ """PEFT matches on the module suffix, so model.embed_tokens is the same module."""+ if isinstance(target_modules, str):+ return set()+ leaves = {str(m).rsplit(".", 1)[-1] for m in target_modules or ()}+ return leaves & EMBEDDING_TARGET_MODULES+++def _full_weight_embedding_elements(arch: ModelArchConfig, target_modules) -> int:+ """embed_tokens/lm_head cost a full matrix each, not a low-rank pair.++ Unsloth redirects them into modules_to_save. A tied pair also gets+ ensure_weight_tying, which collapses them to one trainable matrix.+ """+ selected = len(_embedding_leaves(target_modules))+ if arch.tie_word_embeddings:+ selected = min(selected, 1)+ return arch.vocab_size * arch.hidden_size * selected++def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: list) -> int:all_linear = _targets_all_linear(target_modules)selected_modules = list(DEFAULT_TARGET_MODULES) if all_linear else target_modules+ # Studio's CPT path hands the trainer everything but the embedding names, where an+ # empty remainder becomes the default projections and "all-linear" expands to them+ # (worker.py). Count those, or the estimate picks a GPU that then OOMs.+ if not all_linear and _full_weight_embedding_elements(arch, target_modules):+ remainder = [+ m for m in selected_modules if str(m).rsplit(".", 1)[-1] not in EMBEDDING_TARGET_MODULES+ ]+ if not remainder or _targets_all_linear(remainder):+ selected_modules = list(selected_modules) + list(DEFAULT_TARGET_MODULES)hd = arch.hidden_sizer = lora_rankn_layers = arch.num_hidden_layers@@ -972,7 +1004,12 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: lmlp_total = moe_mlp * n_moe + dense_onlyelse:mlp_total = structured_dense_mlp- return attn_total + mlp_total + _per_layer_input_lora_params(arch, r, target_modules)+ return (+ attn_total+ + mlp_total+ + _per_layer_input_lora_params(arch, r, target_modules)+ + _full_weight_embedding_elements(arch, selected_modules)+ )elif n_experts > 1:attn_total = _lora_attn_elements(arch, r, selected_modules) * n_layersn_dense = arch.num_dense_layers@@ -1024,7 +1061,12 @@ def compute_lora_params(arch: ModelArchConfig, lora_rank: int, target_modules: l* n_layers)- return attn_total + mlp_total + _per_layer_input_lora_params(arch, r, target_modules)+ return (+ attn_total+ + mlp_total+ + _per_layer_input_lora_params(arch, r, target_modules)+ + _full_weight_embedding_elements(arch, selected_modules)+ )def compute_lora_adapter_bytes(lora_params: int) -> int:diff --git a/tests/python/conftest.py b/tests/python/conftest.pyindex f7b125edf66..c4a60d725af 100644--- a/tests/python/conftest.py+++ b/tests/python/conftest.py@@ -4,3 +4,4 @@def pytest_configure(config):config.addinivalue_line("markers", "server: heavyweight tests requiring studio venv")config.addinivalue_line("markers", "e2e: end-to-end tests requiring network and venv creation")+ config.addinivalue_line("markers", "slow: tests needing a GPU and a model download")diff --git a/tests/python/test_embed_lm_head_target_modules_redirect.py b/tests/python/test_embed_lm_head_target_modules_redirect.pynew file mode 100644index 00000000000..665e43ab5cd--- /dev/null+++ b/tests/python/test_embed_lm_head_target_modules_redirect.py@@ -0,0 +1,290 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Regression test for unslothai/unsloth#9326.++When `embed_tokens` and/or `lm_head` are listed in `target_modules`, Unsloth's+fast regex path would silently drop them because they do not sit under an+attention/MLP ancestor. The fix auto-moves them to `modules_to_save` and+warns once, which also makes `embedding_learning_rate` work.+"""++import os+import pytest+import torch+++pytestmark = pytest.mark.skipif(+ not torch.cuda.is_available(),+ reason = "embedding target redirect integration test needs a CUDA GPU",+)+++MODEL_NAME = "Qwen/Qwen2.5-Coder-0.5B-Instruct"++TARGET_MODULES = [+ "q_proj",+ "k_proj",+ "v_proj",+ "o_proj",+ "gate_proj",+ "up_proj",+ "down_proj",+ "embed_tokens",+ "lm_head",+]+++def _run_redirect_check(new_model_path: bool, target_modules):+ """Core assertions shared by both FastLanguageModel paths."""+ from unsloth import FastLanguageModel++ previous_new_model = os.environ.pop("UNSLOTH_USE_NEW_MODEL", None)++ model, tokenizer = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ )+ try:+ if new_model_path:+ os.environ["UNSLOTH_USE_NEW_MODEL"] = "1"+ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = list(target_modules),+ )++ config = model.peft_config["default"]+ saved_modules = config.modules_to_save or []+ state = dict(model.named_parameters())+ tied = bool(getattr(model.config, "tie_word_embeddings", False))++ assert any("embed_tokens" in m for m in saved_modules), saved_modules++ # target_modules should no longer carry the embedding modules+ assert "embed_tokens" not in config.target_modules, config.target_modules+ assert "lm_head" not in config.target_modules, config.target_modules++ # Attention/MLP LoRA adapters should still be present+ assert any("layers.0.self_attn.q_proj.lora_A" in k for k in state)++ # embed_tokens/lm_head must be trainable via ModulesToSave, not LoRA+ assert any(+ "embed_tokens.modules_to_save.default.weight" in k and v.requires_grad+ for k, v in state.items()+ )+ if tied:+ # Tying keeps ONE trainable matrix instead of a second, divergent copy.+ assert "lm_head" not in saved_modules, saved_modules+ assert model.get_output_embeddings().weight.requires_grad+ else:+ assert "lm_head" in saved_modules, saved_modules+ assert any(+ "lm_head.modules_to_save.default.weight" in k and v.requires_grad+ for k, v in state.items()+ )+ assert not any("embed_tokens.lora_A" in k for k in state)+ assert not any("lm_head.lora_A" in k for k in state)+ finally:+ del model+ torch.cuda.empty_cache()+ if previous_new_model is None:+ os.environ.pop("UNSLOTH_USE_NEW_MODEL", None)+ else:+ os.environ["UNSLOTH_USE_NEW_MODEL"] = previous_new_model+++ ("new_model_path", "target_modules"),+ [+ pytest.param(False, TARGET_MODULES, id = "legacy-redirect"),+ pytest.param(True, TARGET_MODULES, id = "new-model-redirect"),+ ],+)+def test_embed_lm_head_target_redirect(new_model_path: bool, target_modules):+ """Both model paths train embed_tokens/lm_head via modules_to_save, not LoRA."""+ _run_redirect_check(new_model_path, target_modules)+++def test_a_repeat_call_with_the_same_targets_still_passes_through():+ """A tied lm_head lands in modules_to_tie, which the equality check has to count."""+ from unsloth import FastLanguageModel++ model, _ = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ )+ try:+ kwargs = dict(r = 8, lora_alpha = 16, target_modules = list(TARGET_MODULES))+ model = FastLanguageModel.get_peft_model(model, **kwargs)+ assert getattr(+ model.peft_config["default"], "modules_to_tie", None+ ), "tied model did not redirect lm_head; this guard would check nothing"+ model = FastLanguageModel.get_peft_model(model, **kwargs)+ # Same configuration, written the other way round: the embeddings named directly+ # in modules_to_save rather than reached through the redirect.+ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = [m for m in TARGET_MODULES if m not in ("embed_tokens", "lm_head")],+ modules_to_save = ["embed_tokens", "lm_head"],+ )+ finally:+ del model+ torch.cuda.empty_cache()+++ "first",+ [+ TARGET_MODULES,+ [m for m in TARGET_MODULES if m != "embed_tokens"],+ [m for m in TARGET_MODULES if m != "lm_head"],+ ],+)+def test_dropping_the_embeddings_from_a_repeat_call_is_not_silently_ignored(first):+ """The embeddings live in modules_to_save/modules_to_tie, so a narrowed request must+ still be seen as different rather than returning the existing adapter."""+ from unsloth import FastLanguageModel++ core = [m for m in TARGET_MODULES if m not in ("embed_tokens", "lm_head")]+ model, _ = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ )+ try:+ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = list(first),+ )+ with pytest.raises(TypeError, match = "parameters are different"):+ FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = core,+ )+ finally:+ del model+ torch.cuda.empty_cache()+++def test_qualified_targets_are_not_collapsed_to_their_leaf():+ """Only PEFT's model.embed_tokens alias is folded away. layers.0.q_proj is a real+ request and is not the same module as layers.1.q_proj."""+ from unsloth import FastLanguageModel++ model, _ = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ )+ try:+ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = ["layers.0.self_attn.q_proj"],+ )+ for different in (["layers.1.self_attn.q_proj"], ["q_proj"]):+ with pytest.raises(TypeError, match = "parameters are different"):+ FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = different,+ )+ finally:+ del model+ torch.cuda.empty_cache()+++def test_flipping_ensure_weight_tying_is_seen_as_a_different_request():+ """Tying is not in check_parameters and leaves both name lists identical, so it has+ to be compared on its own or the caller's request is silently ignored."""+ from unsloth import FastLanguageModel++ model, _ = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ )+ try:+ kwargs = dict(r = 8, lora_alpha = 16, target_modules = list(TARGET_MODULES))+ model = FastLanguageModel.get_peft_model(model, **kwargs)+ assert getattr(+ model.peft_config["default"], "modules_to_tie", None+ ), "model is not tied here; this guard would check nothing"+ with pytest.raises(TypeError, match = "parameters are different"):+ FastLanguageModel.get_peft_model(model, ensure_weight_tying = False, **kwargs)+ # Asking for the mode it already has is still the same request.+ FastLanguageModel.get_peft_model(model, ensure_weight_tying = True, **kwargs)+ finally:+ del model+ torch.cuda.empty_cache()+++def test_a_classification_repeat_call_is_not_tripped_by_peft_added_modules():+ """PeftModelForSequenceClassification.__init__ extends modules_to_save with+ classifier/score unconditionally, so the stored config names modules the caller never+ asked for. An unchanged request must still pass through."""+ from unsloth import FastLanguageModel++ core = [m for m in TARGET_MODULES if m not in ("embed_tokens", "lm_head")]+ model, _ = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ num_labels = 2,+ )+ try:+ model = FastLanguageModel.get_peft_model(+ model, r = 8, lora_alpha = 16, target_modules = list(core)+ )+ saved = model.peft_config["default"].modules_to_save or []+ assert (+ "score" in saved or "classifier" in saved+ ), f"PEFT did not add its classifier modules ({saved}); this guard checks nothing"+ FastLanguageModel.get_peft_model(model, r = 8, lora_alpha = 16, target_modules = list(core))+ # A genuinely different request is still rejected.+ with pytest.raises(TypeError, match = "parameters are different"):+ FastLanguageModel.get_peft_model(model, r = 8, lora_alpha = 16, target_modules = ["q_proj"])+ finally:+ del model+ torch.cuda.empty_cache()+++def test_embedding_only_target_list_raises_instead_of_training_nothing():+ """Redirecting every target would leave an adapter with no trainable LoRA."""+ from unsloth import FastLanguageModel++ model, _ = FastLanguageModel.from_pretrained(+ model_name = MODEL_NAME,+ load_in_4bit = True,+ max_seq_length = 512,+ )+ try:+ with pytest.raises(RuntimeError, match = "target_modules` is now empty"):+ FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = ["embed_tokens", "lm_head"],+ )+ finally:+ del model+ torch.cuda.empty_cache()diff --git a/tests/python/test_vision_lora_targeting.py b/tests/python/test_vision_lora_targeting.pyindex bed26aa297a..e9f1d92dfb3 100644--- a/tests/python/test_vision_lora_targeting.py+++ b/tests/python/test_vision_lora_targeting.py@@ -1,6 +1,7 @@from pathlib import Pathimport re+import pytestimport torch@@ -41,3 +42,380 @@ def test_fast_vision_model_wraps_explicit_targets_when_layer_filters_are_used():assert "target_modules = get_peft_regex(" in sourceassert "target_modules = list(target_modules)" in source+++def test_embedding_redirect_respects_disabled_language_layers():+ from unsloth.models._utils import _redirect_embedding_targets++ targets = ["q_proj", "embed_tokens", "lm_head"]+ adjusted, modules_to_save, moved = _redirect_embedding_targets(+ targets,+ None,+ allow_redirect = False,+ )++ assert adjusted is targets+ assert modules_to_save is None+ assert moved == ()+++def test_embedding_redirect_moves_embeddings_when_lora_targets_remain():+ from unsloth.models._utils import _redirect_embedding_targets++ adjusted, modules_to_save, moved = _redirect_embedding_targets(+ ["q_proj", "embed_tokens", "lm_head"],+ ["embed_tokens"],+ )++ assert adjusted == ["q_proj"]+ assert modules_to_save == ["embed_tokens", "lm_head"]+ assert moved == ("embed_tokens", "lm_head")+++def test_embedding_redirect_always_moves_lm_head():+ """LoRA on lm_head never trains, so it is redirected even when listed alone."""+ from unsloth.models._utils import _redirect_embedding_targets++ adjusted, modules_to_save, moved = _redirect_embedding_targets(["lm_head"], None)++ assert adjusted == []+ assert modules_to_save == ["lm_head"]+ assert moved == ("lm_head",)+++def test_embedding_redirect_raises_when_no_lora_target_remains():+ from unsloth.models._utils import (+ _raise_if_no_lora_targets_left,+ _redirect_embedding_targets,+ )++ adjusted, modules_to_save, moved = _redirect_embedding_targets(+ ["embed_tokens", "lm_head"],+ None,+ )++ assert adjusted == []+ assert modules_to_save == ["embed_tokens", "lm_head"]+ with pytest.raises(RuntimeError, match = "target_modules` is now empty"):+ _raise_if_no_lora_targets_left(adjusted, moved)+++def test_embedding_redirect_keeps_valid_target_lists_unchanged():+ from unsloth.models._utils import (+ _raise_if_no_lora_targets_left,+ _redirect_embedding_targets,+ )++ adjusted, modules_to_save, moved = _redirect_embedding_targets(["q_proj"], None)++ assert adjusted == ["q_proj"]+ assert modules_to_save is None+ assert moved == ()+ _raise_if_no_lora_targets_left(adjusted, moved)+++def test_embedding_redirect_keeps_string_modules_to_save_whole():+ """list() on a str would shred it into single characters."""+ from unsloth.models._utils import _redirect_embedding_targets++ adjusted, modules_to_save, moved = _redirect_embedding_targets(+ ["q_proj", "embed_tokens"],+ "lm_head",+ )++ assert adjusted == ["q_proj"]+ assert modules_to_save == ["lm_head", "embed_tokens"]+ assert moved == ("embed_tokens",)+++def test_embedding_redirect_rejects_embeddings_for_fast_inference():+ from unsloth.models._utils import (+ _raise_if_fast_inference_modules_to_save,+ _redirect_embedding_targets,+ )++ class FastInferenceModel:+ vllm_engine = object()++ adjusted, modules_to_save, moved = _redirect_embedding_targets(+ ["q_proj", "embed_tokens", "lm_head"],+ None,+ )++ assert adjusted == ["q_proj"]+ assert modules_to_save == ["embed_tokens", "lm_head"]+ assert moved == ("embed_tokens", "lm_head")+ with pytest.raises(NotImplementedError, match = "embed_tokens, lm_head"):+ _raise_if_fast_inference_modules_to_save(FastInferenceModel(), modules_to_save)+++def test_fast_inference_guard_ignores_empty_and_inactive_engines():+ from unsloth.models._utils import _raise_if_fast_inference_modules_to_save++ class FastInferenceModel:+ vllm_engine = object()++ class InactiveModel:+ vllm_engine = None++ # An empty list names no trainable module, and vllm_engine = None is not fast inference.+ _raise_if_fast_inference_modules_to_save(FastInferenceModel(), [])+ _raise_if_fast_inference_modules_to_save(FastInferenceModel(), None)+ _raise_if_fast_inference_modules_to_save(InactiveModel(), ["embed_tokens"])+++def test_embedding_redirect_deduplicates_targets():+ from unsloth.models._utils import _redirect_embedding_targets++ adjusted, modules_to_save, moved = _redirect_embedding_targets(+ ["q_proj", "q_proj", "lm_head", "lm_head"],+ None,+ )++ assert adjusted == ["q_proj"]+ assert modules_to_save == ["lm_head"]+ assert moved == ("lm_head",)+++class _Cfg:+ def __init__(self, tie):+ self.tie_word_embeddings = tie+++class _Model:+ def __init__(self, tie):+ self.config = _Cfg(tie)+++def test_ensure_weight_tying_defaults_on_for_a_tied_pair_in_modules_to_save():+ """PEFT copies each saved module, so a tied pair diverges and merges wrong."""+ from unsloth.models._utils import _resolve_ensure_weight_tying++ both = ["embed_tokens", "lm_head"]+ assert _resolve_ensure_weight_tying(_Model(tie = True), both, None) is True+ assert _resolve_ensure_weight_tying(_Model(tie = False), both, None) is False+++def test_ensure_weight_tying_covers_callers_that_pass_modules_to_save_themselves():+ """Studio's CPT path routes both names itself, so nothing is 'moved' by the redirect."""+ from unsloth.models._utils import _redirect_embedding_targets, _resolve_ensure_weight_tying++ target_modules, modules_to_save, moved = _redirect_embedding_targets(+ ["q_proj"],+ ["embed_tokens", "lm_head"],+ )+ assert moved == ()+ assert _resolve_ensure_weight_tying(_Model(tie = True), modules_to_save, None) is True++[email protected]("modules_to_save", [None, [], ["embed_tokens"], ["lm_head"], ["score"]])+def test_ensure_weight_tying_stays_off_without_both_names(modules_to_save):+ from unsloth.models._utils import _resolve_ensure_weight_tying+ assert _resolve_ensure_weight_tying(_Model(tie = True), modules_to_save, None) is False+++def test_tying_leaves_the_output_module_for_peft_to_reconstruct():+ """peft 0.18 ties only what modules_to_save does not name, so naming both there ties+ nothing and trains two copies that diverge."""+ from unsloth.models._utils import _drop_tied_output_module++ tied, untied = _Model(tie = True), _Model(tie = False)+ both = ["embed_tokens", "lm_head"]+ assert _drop_tied_output_module(tied, both, True) == ["embed_tokens"]+ assert _drop_tied_output_module(tied, both, False) == both+ # An untied model has no counterpart for PEFT to rebuild, so dropping lm_head there+ # would leave the head the caller asked to train frozen.+ assert _drop_tied_output_module(untied, both, True) == both+ # Only a real pair is split: tying can be requested with no pair to tie, and dropping+ # the lone head would train nothing (or crash on None).+ assert _drop_tied_output_module(tied, ["embed_tokens", "score"], True) == [+ "embed_tokens",+ "score",+ ]+ assert _drop_tied_output_module(tied, ["lm_head"], True) == ["lm_head"]+ assert _drop_tied_output_module(tied, ["lm_head"], False) == ["lm_head"]+ assert _drop_tied_output_module(tied, None, True) is None+ assert _drop_tied_output_module(tied, [], True) == []++[email protected]("requested", [True, False])+def test_explicit_ensure_weight_tying_always_wins(requested):+ from unsloth.models._utils import _resolve_ensure_weight_tying++ both = ["embed_tokens", "lm_head"]+ assert _resolve_ensure_weight_tying(_Model(tie = True), both, requested) is requested+ assert _resolve_ensure_weight_tying(_Model(tie = False), both, requested) is requested+++def test_ensure_weight_tying_handles_models_without_a_config():+ from unsloth.models._utils import _resolve_ensure_weight_tying+ class Bare:+ pass++ assert _resolve_ensure_weight_tying(Bare(), ["embed_tokens", "lm_head"], None) is False+++def test_target_parameters_alone_is_a_valid_lora_target():+ """PEFT accepts target_parameters with no target_modules (lora/model.py _prepare_adapter_config)."""+ from unsloth.models._utils import _raise_if_no_lora_targets_left+ _raise_if_no_lora_targets_left([], ("embed_tokens", "lm_head"), ["experts.gate_up_proj"])++[email protected]("target_parameters", [None, []])+def test_empty_target_parameters_still_raises(target_parameters):+ from unsloth.models._utils import _raise_if_no_lora_targets_left+ with pytest.raises(RuntimeError, match = "target_modules` is now empty"):+ _raise_if_no_lora_targets_left([], ("embed_tokens",), target_parameters)+++CORE = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]+++class _VllmModel:+ """A model loaded with fast_inference = True carries a live engine."""++ vllm_engine = object()+++def test_fast_inference_leaves_lm_head_alone():+ """Redirecting it would newly raise on GRPO scripts that run today: the pre-existing+ guard refuses any modules_to_save, and LoRA on lm_head never trained here anyway."""+ from unsloth.models._utils import (+ _redirect_embedding_targets,+ _vllm_unmovable_embedding_modules,+ )++ skip = _vllm_unmovable_embedding_modules(_VllmModel(), CORE + ["lm_head"])+ assert skip == ("lm_head",)++ targets, saved, moved = _redirect_embedding_targets(CORE + ["lm_head"], None, skip = skip)+ assert targets == CORE + ["lm_head"], "lm_head must stay a LoRA target under vLLM"+ assert saved is None, "an empty modules_to_save is what keeps the guard quiet"+ assert moved == ()++ # embed_tokens still redirects, so fast inference still refuses it exactly as before.+ targets, saved, moved = _redirect_embedding_targets(+ CORE + ["embed_tokens", "lm_head"],+ None,+ skip = skip,+ )+ assert saved == ["embed_tokens"] and moved == ("embed_tokens",)+ assert targets == CORE + ["lm_head"], "the spared name is kept, not silently dropped"+++def test_without_fast_inference_nothing_is_skipped():+ from unsloth.models._utils import _vllm_unmovable_embedding_modules++ class Plain:+ pass++ assert _vllm_unmovable_embedding_modules(Plain(), CORE + ["lm_head"]) == ()+ # A regex/None target list must not crash the lm_head membership test.+ assert _vllm_unmovable_embedding_modules(_VllmModel(), None) == ("lm_head",)+ assert _vllm_unmovable_embedding_modules(_VllmModel(), "all-linear") == ("lm_head",)+++def test_qualified_embedding_names_are_redirected_too():+ """PEFT resolves model.embed_tokens to the same module, so it must not be left in+ target_modules where LoRA on it never trains."""+ from unsloth.models._utils import (+ _drop_tied_output_module,+ _redirect_embedding_targets,+ _resolve_ensure_weight_tying,+ )++ targets, saved, moved = _redirect_embedding_targets(+ CORE + ["model.embed_tokens", "language_model.lm_head"],+ None,+ )+ assert targets == CORE+ # The caller's spelling is preserved: PEFT matches modules_to_save on the suffix.+ assert saved == ["model.embed_tokens", "language_model.lm_head"]+ assert moved == ("model.embed_tokens", "language_model.lm_head")++ # A qualified pair is still recognised as a tied pair.+ assert _resolve_ensure_weight_tying(_Model(tie = True), saved, None) is True+ # Normalized to the bare name so peft 0.18 recognises it as the embedding to retie.+ assert _drop_tied_output_module(_Model(tie = True), saved, True) == ["embed_tokens"]+++def test_only_embedding_names_are_matched_by_leaf():+ """layers.0.q_proj is a real target and must never be treated as an embedding."""+ from unsloth.models._utils import _embedding_leaf, _redirect_embedding_targets++ assert _embedding_leaf("model.embed_tokens") == "embed_tokens"+ assert _embedding_leaf("lm_head") == "lm_head"+ assert _embedding_leaf("layers.0.q_proj") is None+ assert _embedding_leaf("q_proj") is None+ assert _embedding_leaf(None) is None++ targets, saved, moved = _redirect_embedding_targets(["layers.0.q_proj"], None)+ assert targets == ["layers.0.q_proj"] and saved is None and moved == ()+++def test_tying_normalizes_the_saved_embedding_to_its_bare_name():+ """peft 0.18 ties `tied_weight_keys` minus whole modules_to_save entries, so a+ qualified model.embed_tokens matches nothing and no output module is rebuilt."""+ from unsloth.models._utils import _drop_tied_output_module++ tied = _Model(tie = True)+ assert _drop_tied_output_module(+ tied,+ ["model.embed_tokens", "language_model.lm_head"],+ True,+ ) == ["embed_tokens"]+ assert _drop_tied_output_module(tied, ["embed_tokens", "lm_head"], True) == ["embed_tokens"]+ # Untouched when tying does not apply, and non-embedding names keep their full path.+ assert _drop_tied_output_module(+ tied,+ ["model.embed_tokens", "lm_head"],+ False,+ ) == ["model.embed_tokens", "lm_head"]+ assert _drop_tied_output_module(+ tied,+ ["model.embed_tokens", "lm_head", "custom.score"],+ True,+ ) == ["embed_tokens", "custom.score"]+++def test_tying_needs_the_input_embedding_saved():+ """PEFT rebuilds the output from the input embedding's wrapper, so saving only+ lm_head cannot tie: peft 0.18 raises AttributeError, later versions tie nothing."""+ from unsloth.models._utils import _effective_weight_tying++ tied, untied = _Model(tie = True), _Model(tie = False)+ assert _effective_weight_tying(tied, ["embed_tokens", "lm_head"], None) is True+ assert _effective_weight_tying(tied, ["embed_tokens"], True) is True+ assert _effective_weight_tying(tied, ["model.embed_tokens"], True) is True+ # No input embedding to tie from.+ assert _effective_weight_tying(tied, ["lm_head"], True) is False+ assert _effective_weight_tying(tied, None, True) is False+ assert _effective_weight_tying(tied, ["score"], True) is False+ # Nothing to reconstruct on an untied model, however it is asked for.+ assert _effective_weight_tying(untied, ["embed_tokens", "lm_head"], True) is False+ # An explicit False always wins.+ assert _effective_weight_tying(tied, ["embed_tokens", "lm_head"], False) is False+++class _Composite(torch.nn.Module):+ """Audio tower and language model both expose an embed_tokens leaf."""++ def __init__(self, two_embeddings):+ super().__init__()+ self.language_model = torch.nn.Module()+ self.language_model.embed_tokens = torch.nn.Embedding(8, 4)+ if two_embeddings:+ self.audio_tower = torch.nn.Module()+ self.audio_tower.embed_tokens = torch.nn.Embedding(8, 4)+ self.config = _Cfg(True)+++def test_a_qualified_name_is_not_widened_on_a_composite_model():+ """PEFT suffix-matches, so the bare leaf would wrap the audio tower's embedding too."""+ from unsloth.models._utils import _drop_tied_output_module++ pair = ["language_model.embed_tokens", "lm_head"]+ # Two candidates: keep the caller's scope, and keep the head trainable with it.+ assert _drop_tied_output_module(_Composite(True), list(pair), True) == pair+ # One candidate: rewriting is safe and peft 0.18 needs the bare name to retie.+ assert _drop_tied_output_module(_Composite(False), list(pair), True) == ["embed_tokens"]diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex ab1a2aef500..670cef698b3 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -93,6 +93,18 @@ __all__ = ["get_moe_target_modules","warn_if_zoo_cannot_merge_moe_experts","_select_moe_detection_targets",+ "EMBEDDING_MODULES",+ "_embedding_leaf",+ "_embedding_leaves",+ "_model_ties_embeddings",+ "_effective_weight_tying",+ "_embedding_name_is_unambiguous",+ "_redirect_embedding_targets",+ "_raise_if_no_lora_targets_left",+ "_resolve_ensure_weight_tying",+ "_vllm_unmovable_embedding_modules",+ "_drop_tied_output_module",+ "_raise_if_fast_inference_modules_to_save","make_fast_generate_wrapper","_mark_unsloth_disable_data_parallel","_patch_transformers_trainer_data_parallel",@@ -4470,6 +4482,196 @@ def warn_if_zoo_cannot_merge_moe_experts():)+EMBEDDING_MODULES = frozenset(("embed_tokens", "lm_head"))+++def _embedding_leaf(name):+ """`embed_tokens`/`lm_head` for any spelling of them, else None.++ PEFT matches on the module suffix, so `model.embed_tokens` is the same module.+ Anything else keeps its full name: layers.0.q_proj is a real target.+ """+ if type(name) is not str:+ return None+ leaf = name.rsplit(".", 1)[-1]+ return leaf if leaf in EMBEDDING_MODULES else None+++def _embedding_leaves(names):+ return {leaf for leaf in map(_embedding_leaf, names or ()) if leaf is not None}+++def _vllm_unmovable_embedding_modules(model, target_modules):+ """Names to leave in `target_modules` under fast inference.++ vLLM cannot sync a trainable embedding, so modules_to_save is refused below. Only+ lm_head is spared: LoRA on it never trained here either, so redirecting it would+ newly raise on scripts that run today. embed_tokens still redirects, so still raises.+ """+ if getattr(model, "vllm_engine", None) is None:+ return ()+ if type(target_modules) in (list, tuple) and "lm_head" in _embedding_leaves(target_modules):+ logger.warning_once(+ "Unsloth: Fast inference cannot train `lm_head`, so it is left as an "+ "untrained LoRA target.\nUse `fast_inference = False` to train it."+ )+ return ("lm_head",)+++def _redirect_embedding_targets(+ target_modules,+ modules_to_save,+ *,+ allow_redirect = True,+ skip = (),+):+ """Move embed_tokens/lm_head into modules_to_save. Returns (targets, saved, moved).++ LoRA on either is silently dead here: the fused CE loss reads `lm_head.weight`+ instead of calling the module, and PEFT's `lora_embedding_A/B` are never unfrozen.+ """+ if type(target_modules) not in (list, tuple) or not allow_redirect:+ return target_modules, modules_to_save, ()++ target_modules = list(dict.fromkeys(target_modules))+ moved = [x for x in target_modules if _embedding_leaf(x) and _embedding_leaf(x) not in skip]+ if not moved:+ return target_modules, modules_to_save, ()++ remaining = [x for x in target_modules if not _embedding_leaf(x) or _embedding_leaf(x) in skip]+ # list() on a str would shred it into single characters.+ if modules_to_save is None:+ saved = []+ elif isinstance(modules_to_save, str):+ saved = [modules_to_save]+ else:+ saved = list(modules_to_save)+ saved.extend(x for x in moved if x not in saved)+ return remaining, saved, tuple(moved)+++def _raise_if_no_lora_targets_left(+ target_modules,+ moved,+ target_parameters = None,+):+ """embed_tokens/lm_head go to modules_to_save, so they cannot be the only targets.++ PEFT accepts `target_parameters` (fused MoE experts) with no target_modules at all.+ """+ if (+ moved+ and type(target_modules) in (list, tuple)+ and not target_modules+ and not target_parameters+ ):+ raise RuntimeError(+ f"Unsloth: {', '.join(moved)} are trained as full modules via `modules_to_save`, "+ "not as LoRA targets, so `target_modules` is now empty.\n"+ "Please add at least one projection module, for example "+ '`target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", '+ '"gate_proj", "up_proj", "down_proj"]`.'+ )+++def _model_ties_embeddings(model):+ return bool(getattr(getattr(model, "config", None), "tie_word_embeddings", False))+++def _resolve_ensure_weight_tying(model, modules_to_save, requested):+ """Default `ensure_weight_tying` on when a tied pair lands in modules_to_save.++ PEFT copies each entry, so tied copies diverge and a merge keeps only one; tying+ moves the counterpart to `modules_to_tie`. Keyed on the final modules_to_save so+ callers that pass both names themselves are covered. Caller wins if set.+ """+ if requested is not None:+ return bool(requested)+ if not EMBEDDING_MODULES <= _embedding_leaves(modules_to_save):+ return False+ return _model_ties_embeddings(model)+++def _embedding_name_is_unambiguous(model, name):+ """Whether `name` and its bare leaf select the same single module.++ A composite model can hold two embed_tokens, and PEFT suffix-matches, so the bare+ name would wrap both. Rewriting is only safe when exactly one module matches.+ """+ leaf = _embedding_leaf(name)+ if leaf is None:+ return False+ named_modules = getattr(model, "named_modules", None)+ if named_modules is None:+ return True+ found = 0+ for module_name, _ in named_modules():+ if module_name == leaf or module_name.endswith("." + leaf):+ found += 1+ if found > 1:+ return False+ return found == 1+++def _effective_weight_tying(model, modules_to_save, requested):+ """Whether PEFT will really retie, not just whether it was asked to.++ Tying rebuilds the output from the INPUT embedding's wrapper, so that one must be+ saved: peft 0.18 raises AttributeError otherwise, later versions tie nothing. An+ untied model has no counterpart to rebuild either.+ """+ if not _resolve_ensure_weight_tying(model, modules_to_save, requested):+ return False+ if not _model_ties_embeddings(model):+ return False+ return "embed_tokens" in _embedding_leaves(modules_to_save)+++def _drop_tied_output_module(model, modules_to_save, ensure_weight_tying):+ """Keep the input embedding and leave the tied output for PEFT to reconstruct.++ peft 0.18 ties only `tied_weight_keys - modules_to_save`, so naming both there ties+ nothing and trains two diverging copies. One matrix on 0.18.1 and 0.20.0 alike.++ Gated on the model, not the flag: `ensure_weight_tying` can be passed explicitly on+ an untied model, where PEFT has no counterpart to rebuild and only warns, so dropping+ lm_head would leave the head the caller asked to train frozen.+ """+ if (+ not ensure_weight_tying+ or not _model_ties_embeddings(model)+ or not EMBEDDING_MODULES <= _embedding_leaves(modules_to_save)+ ):+ return modules_to_save+ # Bare leaf, not the caller's spelling: peft 0.18 ties `tied_weight_keys` minus whole+ # `modules_to_save` entries, so a qualified `model.embed_tokens` matches nothing there+ # and it reconstructs no output module, leaving the head frozen. PEFT resolves the+ # bare name by suffix on every version, so normalizing is safe.+ kept = [x for x in modules_to_save if _embedding_leaf(x) != "lm_head"]+ normalized = []+ for entry in kept:+ leaf = _embedding_leaf(entry)+ if leaf is None or entry == leaf:+ normalized.append(entry)+ elif _embedding_name_is_unambiguous(model, entry):+ normalized.append(leaf)+ else:+ # Rewriting would widen the scope to another subtree's embedding. Keep+ # both entries: two copies beats a silently frozen head.+ return modules_to_save+ return normalized+++def _raise_if_fast_inference_modules_to_save(model, modules_to_save):+ """Reject trainable saved modules that vLLM cannot keep synchronized."""+ if getattr(model, "vllm_engine", None) is None or not modules_to_save:+ return+ raise NotImplementedError(+ "Unsloth: Currently fast inference does not work with training "+ f"{', '.join(modules_to_save)}."+ )++def _select_moe_detection_targets(original_target_modules,scoped_target_modules,diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 532df1a2a10..fecc78c0393 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -3086,7 +3086,7 @@ class FastLlamaModel:temporary_location = "_unsloth_temporary_saved_buffers",qat_scheme = None,target_parameters = None, # For MoE expert layers (nn.Parameter)- ensure_weight_tying = False,+ ensure_weight_tying = None, # None = auto (tie when we redirect a tied pair)**kwargs,):if os.environ.get("UNSLOTH_USE_NEW_MODEL", "0") == "1":@@ -3172,27 +3172,57 @@ class FastLlamaModel:bool(peft_config.get("use_dora", False)) == bool(kwargs.get("use_dora", False)))- # Check save_modules- old_target_modules = list(peft_config["target_modules"])- modules_to_save = peft_config["modules_to_save"]- if modules_to_save is None:- modules_to_save = {}- modules_to_save = list(modules_to_save)- old_target_modules += modules_to_save+ # Everything the stored adapter trains, wherever PEFT filed it: tying moves+ # the counterpart to modules_to_tie, which to_dict() drops, so read the+ # config object.+ requested_modules_to_save = modules_to_save+ modules_to_save = list(peft_config["modules_to_save"] or [])+ old_target_modules = list(peft_config["target_modules"]) + modules_to_save+ old_target_modules += list(+ getattr(model.peft_config["default"], "modules_to_tie", None) or []+ )- # Combine all- new_target_modules = list(target_modules) + list(- modules_to_save if modules_to_save is not None else []+ # The new side is what THIS call asks for, through the same redirect. Built+ # from the stored lists instead, a narrowed request would compare equal.+ requested_targets, requested_saved, _ = _redirect_embedding_targets(+ target_modules,+ requested_modules_to_save,+ skip = _vllm_unmovable_embedding_modules(model, target_modules),+ )+ new_target_modules = list(requested_targets) + list(requested_saved or [])+ if isinstance(model, PeftModelForSequenceClassification):+ # PeftModelForSequenceClassification.__init__ extends modules_to_save with+ # these unconditionally, so the stored config names modules the caller+ # never asked for. Mirror it, or an unchanged request looks different.+ new_target_modules += ["classifier", "score"]+ # Tying is not in check_parameters and leaves both lists looking the same, so+ # compare it separately. On what it actually does, not what was asked: on an+ # untied model the request changes nothing either way.+ _requested_ties = _effective_weight_tying(+ model,+ requested_saved,+ ensure_weight_tying,)+ _stored_ties = bool(getattr(model.peft_config["default"], "modules_to_tie", None))+ check_all = check_all and (_requested_ties == _stored_ties)+ if _requested_ties:+ # PEFT files the counterpart under modules_to_tie, which the old side+ # counts, so name it here even when the caller listed only one side.+ new_target_modules += list(EMBEDDING_MODULES)# Per-expert Linear MoE experts (e.g. gpt-oss bnb-4bit) were auto-added to the# saved target_modules when the adapter was first created. Recompute them so a# repeat get_peft_model call with the same args stays idempotent instead of# tripping the mismatch below. No-op for non per-expert-Linear models.new_target_modules += get_moe_target_modules(model, target_modules)- # Now check!- new_target_modules = set(new_target_modules)- check_all = check_all and (len(set(old_target_modules) ^ new_target_modules) == 0)+ # Now check! Fold away PEFT's model.embed_tokens alias, and only that one:+ # layers.0.q_proj is a real target and is not layers.1.q_proj.+ def _leaf_name(module):+ return _embedding_leaf(module) or module++ new_target_modules = {_leaf_name(x) for x in new_target_modules}+ old_target_modules = {_leaf_name(x) for x in old_target_modules}+ check_all = check_all and (len(old_target_modules ^ new_target_modules) == 0)check_all = check_all and ((loftq_config == {} or loftq_config is None)@@ -3315,29 +3345,49 @@ class FastLlamaModel:train_lm_head = Falsetrain_embed_tokens = Falsefinal_modules = []- for module in target_modules:- if module == "embed_tokens":- # logger.warning_once(- # "Unsloth: `embed_tokens` should be placed in `modules_to_save` and not `target_modules`. "\- # "Luckily, we shall do it for you!"- # )+ # LoRA on these never trains (see _redirect_embedding_targets); modules_to_save+ # does, and is what embedding_learning_rate matches.+ target_modules, modules_to_save, _moved_embedding_modules = _redirect_embedding_targets(+ target_modules,+ modules_to_save,+ skip = _vllm_unmovable_embedding_modules(model, target_modules),+ )+ _raise_if_no_lora_targets_left(+ target_modules,+ _moved_embedding_modules,+ target_parameters,+ )+ ensure_weight_tying = _effective_weight_tying(+ model,+ modules_to_save,+ ensure_weight_tying,+ )+ modules_to_save = _drop_tied_output_module(+ model,+ modules_to_save,+ ensure_weight_tying,+ )+ for module in _moved_embedding_modules:+ if _embedding_leaf(module) == "embed_tokens":train_embed_tokens = True- if modules_to_save is None:- modules_to_save = ["embed_tokens"]- else:- modules_to_save.append("embed_tokens")-else:- try:- assert module in accepted_modules- final_modules.append(module)- except AssertionError as e:- final_modules.append(module)- print(- "Unsloth: You added custom modules, but Unsloth hasn't optimized for this.\n"- "Beware - your finetuning might be noticeably slower!"- )- pass+ train_lm_head = True+ if _moved_embedding_modules:+ logger.warning_once(+ f"Unsloth: Moved {', '.join(_moved_embedding_modules)} from `target_modules` "+ f"to `modules_to_save`, so they are trained as full weight matrices.\n"+ f"This uses more VRAM than LoRA. Please list them in `modules_to_save` directly."+ )+ for module in target_modules:+ try:+ assert module in accepted_modules+ final_modules.append(module)+ except AssertionError as e:+ final_modules.append(module)+ print(+ "Unsloth: You added custom modules, but Unsloth hasn't optimized for this.\n"+ "Beware - your finetuning might be noticeably slower!"+ )# Check if we added new tokens!if hasattr(model, "_need_to_train_embeddings"):@@ -3380,9 +3430,11 @@ class FastLlamaModel:# Check modules_to_saveif modules_to_save is not None:for module in modules_to_save:- if module == "lm_head":+ # By leaf: PEFT resolves model.embed_tokens to the same module.+ leaf = _embedding_leaf(module)+ if leaf == "lm_head":train_lm_head = True- elif module == "embed_tokens":+ elif leaf == "embed_tokens":train_embed_tokens = Trueelse:raise TypeError(@@ -3451,6 +3503,9 @@ class FastLlamaModel:ensure_weight_tying = ensure_weight_tying,**kwargs,)+ # Older PEFT has no `ensure_weight_tying`; passing it would TypeError.+ if "ensure_weight_tying" not in inspect.signature(LoraConfig).parameters:+ del arguments["ensure_weight_tying"]if not SUPPORTS_LOFTQ:del arguments["loftq_config"]if not SUPPORTS_RSLORA:diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 0776cce21d7..caa694b6d1b 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -1877,7 +1877,7 @@ class FastBaseModel:temporary_location = "_unsloth_temporary_saved_buffers",qat_scheme = None,target_parameters = None, # For MoE expert layers (nn.Parameter)- ensure_weight_tying = False, # [TODO] Add `ensure_weight_tying` for `modules_to_save` for vision models+ ensure_weight_tying = None, # None = auto (tie when we redirect a tied pair)finetune_audio_layers = False, # placed last to preserve existing positional argument order**kwargs,):@@ -1931,6 +1931,34 @@ class FastBaseModel:# only the auto (None / "all-linear") path relies on the regex, whose mlp# block is the sole remaining MLP-intent signal on fused-expert models._moe_detect_target = target_modules if type(target_modules) in (list, tuple) else None++ # get_peft_regex drops these (no attention/MLP ancestor) and LoRA on them never+ # trains, so redirect before scoping, matching FastLanguageModel.+ target_modules, modules_to_save, _moved = _redirect_embedding_targets(+ target_modules,+ modules_to_save,+ allow_redirect = finetune_language_layers,+ skip = _vllm_unmovable_embedding_modules(model, target_modules),+ )+ _raise_if_no_lora_targets_left(target_modules, _moved, target_parameters)+ ensure_weight_tying = _effective_weight_tying(+ model,+ modules_to_save,+ ensure_weight_tying,+ )+ modules_to_save = _drop_tied_output_module(+ model,+ modules_to_save,+ ensure_weight_tying,+ )+ if _moved:+ logger.warning_once(+ f"Unsloth: Moved {', '.join(_moved)} from `target_modules` to "+ f"`modules_to_save`, so they are trained as full weight matrices.\n"+ f"This uses more VRAM than LoRA. Please list them in `modules_to_save` directly."+ )+ _raise_if_fast_inference_modules_to_save(model, modules_to_save)+if target_modules is None or target_modules == "all-linear":target_modules = get_peft_regex(model,