Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Pass str target_modules (regex or "all-linear") to PEFT on the Llama path (#13567)

Daniel Hanb71d711b66be
diff --git a/tests/test_peft_str_target_modules.py b/tests/test_peft_str_target_modules.py
new file mode 100644
index 00000000000..5fe6903f684
--- /dev/null
+++ b/tests/test_peft_str_target_modules.py
@@ -0,0 +1,165 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+import re
+
+import pytest
+
+import unsloth # noqa: F401
+import unsloth.models.llama as llama_module
+from peft import get_peft_model
+from unsloth.models.llama import FastLlamaModel
+
+
+def _tiny_llama(layers = 2):
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ config = LlamaConfig(
+ vocab_size = 64,
+ hidden_size = 16,
+ intermediate_size = 32,
+ num_hidden_layers = layers,
+ num_attention_heads = 2,
+ num_key_value_heads = 2,
+ )
+ model = LlamaForCausalLM(config)
+ model.max_seq_length = 64
+ model._saved_temp_tokenizer = None
+ return model
+
+
+class _Captured(Exception):
+ pass
+
+
+def _lora_config_for(target_modules, monkeypatch):
+ def capture(model, lora_config, *args, **kwargs):
+ raise _Captured(lora_config)
+
+ monkeypatch.setattr(llama_module, "_get_peft_model", capture)
+ with pytest.raises(_Captured) as info:
+ FastLlamaModel.get_peft_model(
+ _tiny_llama(),
+ r = 4,
+ target_modules = target_modules,
+ use_gradient_checkpointing = False,
+ )
+ return info.value.args[0]
+
+
+def _lora_modules(lora_config):
+ wrapped = get_peft_model(_tiny_llama(), lora_config)
+ return sorted(
+ name.removeprefix("base_model.model.").removesuffix(".lora_A")
+ for name, _ in wrapped.named_modules()
+ if name.endswith(".lora_A")
+ )
+
+
+def test_regex_string_targets_exactly_the_matched_modules(monkeypatch):
+ wanted = ["model.layers.0.self_attn.q_proj", "model.layers.1.mlp.down_proj"]
+ regex = r"(?:.*\.)?(?:" + "|".join(re.escape(name) for name in wanted) + r")"
+ config = _lora_config_for(regex, monkeypatch)
+ assert config.target_modules == regex
+ assert _lora_modules(config) == wanted
+
+
+def test_all_linear_string_is_passed_to_peft(monkeypatch):
+ config = _lora_config_for("all-linear", monkeypatch)
+ assert config.target_modules == "all-linear"
+ assert len(_lora_modules(config)) == 2 * 7
+
+
+def test_list_targets_unchanged(monkeypatch):
+ config = _lora_config_for(["q_proj", "v_proj"], monkeypatch)
+ assert config.target_modules == {"q_proj", "v_proj"}
+ assert len(_lora_modules(config)) == 2 * 2
+
+
+def test_add_moe_target_modules_keeps_each_form():
+ from unsloth.models._utils import add_moe_target_modules
+
+ experts = ["gate_up_projs.0", "gate_up_projs.1", "down_projs.0"]
+ assert add_moe_target_modules(["q_proj"], experts) == ["q_proj"] + experts
+ assert add_moe_target_modules(["q_proj", "down_projs.0"], experts) == [
+ "q_proj",
+ "down_projs.0",
+ "gate_up_projs.0",
+ "gate_up_projs.1",
+ ]
+ assert add_moe_target_modules("all-linear", experts) == "all-linear"
+ assert add_moe_target_modules(".*q_proj", []) == ".*q_proj"
+ combined = add_moe_target_modules(".*q_proj", experts)
+ assert re.fullmatch(combined, "model.layers.0.self_attn.q_proj")
+ assert re.fullmatch(combined, "model.layers.3.mlp.experts.down_projs.7")
+ assert not re.fullmatch(combined, "model.layers.0.mlp.experts.router")
+
+
+def _prewrapped(
+ target_modules,
+ layers = 2,
+ **extra,
+):
+ from peft import LoraConfig
+ config = LoraConfig(
+ r = 16, lora_alpha = 16, target_modules = target_modules, task_type = "CAUSAL_LM", **extra
+ )
+ return get_peft_model(_tiny_llama(layers), config)
+
+
+REGEX = r".*\.layers\.0\.self_attn\.q_proj"
+
+
+ "target_modules, layers",
+ [("all-linear", 2), ("all-linear", 4), (REGEX, 2)],
+ # 4 layers = 28 Linears: past PEFT's 20-module threshold, the stored list is compacted to suffixes.
+ ids = ["all_linear", "all_linear_compacted", "regex"],
+)
+def test_repeat_call_with_same_str_keeps_the_adapter(target_modules, layers):
+ model = _prewrapped(target_modules, layers)
+ again = FastLlamaModel.get_peft_model(
+ model, r = 16, target_modules = target_modules, use_gradient_checkpointing = False
+ )
+ assert again is model
+
+
+ "stored, requested",
+ [
+ (["q_proj", "v_proj"], "all-linear"),
+ (REGEX, r".*\.layers\.1\.self_attn\.q_proj"),
+ ],
+ ids = ["narrower_then_all_linear", "other_regex"],
+)
+def test_repeat_call_with_different_str_is_refused(stored, requested):
+ with pytest.raises(TypeError, match = "new parameters are different"):
+ FastLlamaModel.get_peft_model(
+ _prewrapped(stored), r = 16, target_modules = requested, use_gradient_checkpointing = False
+ )
+
+
+def test_all_linear_matches_an_adapter_on_every_linear():
+ model = _prewrapped(
+ ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], 4
+ )
+ again = FastLlamaModel.get_peft_model(
+ model, r = 16, target_modules = "all-linear", use_gradient_checkpointing = False
+ )
+ assert again is model
+
+
+def test_all_linear_repeat_honours_exclude_modules():
+ model = _prewrapped("all-linear", 4, exclude_modules = ["down_proj"])
+ again = FastLlamaModel.get_peft_model(
+ model,
+ r = 16,
+ target_modules = "all-linear",
+ exclude_modules = ["down_proj"],
+ use_gradient_checkpointing = False,
+ )
+ assert again is model
+ with pytest.raises(TypeError, match = "new parameters are different"):
+ FastLlamaModel.get_peft_model(
+ model, r = 16, target_modules = "all-linear", use_gradient_checkpointing = False
+ )
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 5e47316357c..a7018de4c7e 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -114,6 +114,7 @@ __all__ = [
"skip_swapped_checkpoint_keys",
"get_moe_target_parameters",
"get_moe_target_modules",
+ "add_moe_target_modules",
"get_moe_expert_submodule_leaves",
"moe_expert_submodule_regex",
"widen_target_regex_to_expert_submodules",
@@ -8931,6 +8932,21 @@ def get_moe_target_modules(model, target_modules = None) -> List[str]:
return sorted(targets)
+def add_moe_target_modules(target_modules, moe_module_targets):
+ """Extend target_modules with get_moe_target_modules' per-expert suffixes, in whichever form PEFT was given: a leaf list, or one regex string (fullmatched against the module path)."""
+ if not moe_module_targets:
+ return target_modules
+ if isinstance(target_modules, str):
+ # PEFT's "all-linear" already reaches every expert Linear; wrapping it in a regex would drop that meaning.
+ if target_modules == "all-linear":
+ return target_modules
+ leaves = sorted({t.rsplit(".", 1)[0] for t in moe_module_targets})
+ expert_alt = r".*\.experts\.(?:" + "|".join(re.escape(leaf) for leaf in leaves) + r")\.\d+"
+ return f"(?:{target_modules})|(?:{expert_alt})"
+ target_modules = list(target_modules)
+ return target_modules + [t for t in moe_module_targets if t not in target_modules]
+
+
_EXPERT_SUBMODULE_PATTERN = re.compile(r"(?:^|\.)(?:experts\.\d+|shared_experts?)\.([A-Za-z_]\w*)$")
_EXPERT_BLOCK_PATTERN = re.compile(r"(?:^|\.)(?:experts\.\d+|shared_experts?)$")
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index c91291946c7..18322792fd5 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -2542,6 +2542,36 @@ def _fused_lora_skip_reason(
)
+def _resolve_all_linear(
+ model,
+ target_modules,
+ exclude_modules = None,
+):
+ """(modules "all-linear" resolves to, modules the adapter wraps) on a wrapped model, both as full paths."""
+ try:
+ from peft.tuners.tuners_utils import (
+ BaseTunerLayer,
+ _ExcludedModule,
+ _maybe_include_all_linear_layers,
+ check_target_module_exists,
+ )
+ except ImportError:
+ return None
+ base = model.get_base_model()
+ config = LoraConfig(target_modules = target_modules, exclude_modules = exclude_modules)
+ config = _maybe_include_all_linear_layers(config, base)
+ # A trained lm_head sits in a modules_to_save wrapper whose copies are Linear too; PEFT excluded it at creation.
+ resolved = {
+ name
+ for name in config.target_modules
+ if ".original_module" not in name
+ and ".modules_to_save." not in name
+ and not isinstance(check_target_module_exists(config, name), _ExcludedModule)
+ }
+ wrapped = {name for name, module in base.named_modules() if isinstance(module, BaseTunerLayer)}
+ return resolved, wrapped
+
+
_DEFAULT_TARGET_MODULES = [
"q_proj",
"k_proj",
@@ -3939,10 +3969,10 @@ class FastLlamaModel:
# 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 []
- )
+
+ # A str target_modules is one regex: compare it whole, not character by character.
+ def _as_list(targets):
+ return [targets] if isinstance(targets, str) else list(targets or [])
# 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.
@@ -3951,7 +3981,20 @@ class FastLlamaModel:
requested_modules_to_save,
skip = _vllm_unmovable_embedding_modules(model, target_modules),
)
- new_target_modules = list(requested_targets) + list(requested_saved or [])
+ stored_targets = peft_config["target_modules"]
+ if isinstance(requested_targets, str) and requested_targets.lower() == "all-linear":
+ # PEFT stores "all-linear" expanded and, past 20 modules, compacted: compare resolved vs wrapped.
+ resolved = _resolve_all_linear(
+ model, requested_targets, kwargs.get("exclude_modules")
+ )
+ if resolved is not None:
+ requested_targets, stored_targets = resolved
+
+ old_target_modules = _as_list(stored_targets) + modules_to_save
+ old_target_modules += list(
+ getattr(model.peft_config["default"], "modules_to_tie", None) or []
+ )
+ new_target_modules = _as_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
@@ -4134,16 +4177,20 @@ class FastLlamaModel:
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!"
- )
+ if isinstance(target_modules, str):
+ # A str is one PEFT regex or "all-linear"; iterating it yields characters that suffix-match `layers.1`.
+ final_modules = target_modules
+ else:
+ 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!"
+ )
if hasattr(model, "_need_to_train_embeddings"):
# embed_tokens/lm_head may already be trained, either as LoRA targets in final_modules or via
@@ -4227,8 +4274,12 @@ class FastLlamaModel:
)
if _moe_module_targets:
- _added = [t for t in _moe_module_targets if t not in final_modules]
- final_modules.extend(_added)
+ _added = [
+ t
+ for t in _moe_module_targets
+ if isinstance(final_modules, str) or t not in final_modules
+ ]
+ final_modules = add_moe_target_modules(final_modules, _moe_module_targets)
if _added:
print(
f"Unsloth: Detected MoE model with per-expert Linear experts. "
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index dc0d8ec444b..3366203e081 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -4668,18 +4668,7 @@ class FastBaseModel:
)
if _moe_module_targets:
- if isinstance(target_modules, (list, tuple)):
- target_modules = list(target_modules) + [
- target for target in _moe_module_targets if target not in target_modules
- ]
- elif isinstance(target_modules, str):
- _expert_leaves = sorted({t.rsplit(".", 1)[0] for t in _moe_module_targets})
- _expert_alt = (
- r".*\.experts\.(?:"
- + "|".join(re.escape(leaf) for leaf in _expert_leaves)
- + r")\.\d+"
- )
- target_modules = f"(?:{target_modules})|(?:{_expert_alt})"
+ target_modules = add_moe_target_modules(target_modules, _moe_module_targets)
print(
f"Unsloth: Detected MoE model with per-expert Linear experts. "
f"Enabling LoRA on {len(_moe_module_targets)} expert projection modules."