Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(moe): moe_lora keeps a string target_modules, adds the MoE targets, adapts no router (#2095)

Alpamys Makazhan29704fbda381
diff --git a/changelog.d/0.76.0/2072.fixed.md b/changelog.d/0.76.0/2072.fixed.md
index 5fd52ec2..8bd81f9e 100644
--- a/changelog.d/0.76.0/2072.fixed.md
+++ b/changelog.d/0.76.0/2072.fixed.md
@@ -1 +1 @@
-- **Layer streaming with `moe_lora: true` now keeps list attention targets, as resident training does, and its VRAM forecast charges what attaches.** The streaming setup handed the `moe_lora` helper no targets and then replaced the resolved `target_modules` list with its answer (`q_proj`, `k_proj`, `v_proj`, `o_proj`, the expert FFN names and the fused expert parameters). Every name that list does not repeat lost its adapter: on DeepSeek-V3, whose attention has no `k_proj` / `v_proj`, attention kept only `o_proj` and lost `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa` and `kv_b_proj`; on Qwen3.5-MoE the linear-attention `in_proj_qkv` / `out_proj` were dropped; and an explicit `lora.target_modules` list was dropped entirely. The setup now resolves the targets before its meta-skeleton probe and passes them to the same helper the resident trainers use, so when the targets are a list (an explicit list, or what `auto` resolves to on DeepSeek-V3 and Qwen3.5-MoE) a streamed run adapts their union with the MoE targets, in the same order as a resident run of the same config. A string target (`auto` on qwen4_exp resolves to `"all-linear"`, or a regex) is still replaced by the MoE targets, on both paths. The pre-flight VRAM forecast now counts that union and one adapter per routed expert for each fused expert tensor, instead of the configured value: `target_modules: ['o_proj']` was charged one target per layer while the union and every routed expert attached. Runs without `moe_lora` are unchanged. (#2072)
+- **Layer streaming with `moe_lora: true` now keeps list attention targets, as resident training does, and its VRAM forecast charges what attaches.** The streaming setup handed the `moe_lora` helper no targets and then replaced the resolved `target_modules` list with its answer (`q_proj`, `k_proj`, `v_proj`, `o_proj`, the expert FFN names and the fused expert parameters). Every name that list does not repeat lost its adapter: on DeepSeek-V3, whose attention has no `k_proj` / `v_proj`, attention kept only `o_proj` and lost `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa` and `kv_b_proj`; on Qwen3.5-MoE the linear-attention `in_proj_qkv` / `out_proj` were dropped; and an explicit `lora.target_modules` list was dropped entirely. The setup now resolves the targets before its meta-skeleton probe and passes them to the same helper the resident trainers use, so when the targets are a list (an explicit list, or what `auto` resolves to on DeepSeek-V3 and Qwen3.5-MoE) a streamed run adapts their union with the MoE targets, in the same order as a resident run of the same config. A string target (`auto` on qwen4_exp resolves to `"all-linear"`, or a regex) reaches the same helper on both paths, where it keeps its meaning without the MoE routers. The pre-flight VRAM forecast now counts that union and one adapter per routed expert for each fused expert tensor, instead of the configured value: `target_modules: ['o_proj']` was charged one target per layer while the union and every routed expert attached. Runs without `moe_lora` are unchanged. (#2072)
diff --git a/changelog.d/0.76.0/2095.fixed.md b/changelog.d/0.76.0/2095.fixed.md
new file mode 100644
index 00000000..021e996d
--- /dev/null
+++ b/changelog.d/0.76.0/2095.fixed.md
@@ -0,0 +1 @@
+- **`moe_lora: true` keeps a string `target_modules` and adds the MoE targets on top of it, as it already did for a list.** `resolve_moe_lora_targets` merged the MoE names into a list target (#1590) but replaced a string with the MoE list (`q_proj`, `k_proj`, `v_proj`, `o_proj` and the expert FFN names) plus the fused expert parameters, and a string means something to peft. `"all-linear"`, which `target_modules: auto` resolves to on qwen4_exp, adapts every linear layer but the output head, so a qwen4_exp base with `moe_lora` lost the Gated DeltaNet `in_proj_qkv` / `in_proj_z` / `in_proj_a` / `in_proj_b` / `out_proj`, the QSA indexer's `index_qk_proj`, the hyper-connection mixers and the PLE `key_proj` / `value_proj`: 10 adapted modules on a tiny two-layer model, where 32 now attach. Any other string is a regex peft full-matches against each module name, and it was dropped outright. Now `"all-linear"` (in any casing peft accepts) is kept as it is, since it already reaches every module the MoE names reach, and only the fused expert parameters are added. A regex becomes one regex, `(?:<your regex>)|(?:<the MoE names>)`, so peft adapts exactly what either half matches; a leading global flag such as `(?i)` stays with your half, and a regex that does not compile is refused at setup, naming `training.lora.target_modules`. Under `moe_lora` a string never adapts a MoE router or shared-expert gate (a module whose output is routing logits, found from the model's structure, DBRX's and JetMoE's wrapped routers included), even one your regex names: they go to peft's `exclude_modules`. Only where peft would still adapt a router weight with them excluded does the string become an explicit list of what it means without them: `all-linear` on the families peft converts from the transformers-4 layout (qwen3_moe, deepseek_v3, ...), where peft adds the router to it as a parameter `exclude_modules` does not reach, a regex reaching a non-router named `gate` there, and VeRA, whose config has no `exclude_modules`. To adapt a router, name it in an explicit list. A regex that matches no module is warned about. The `ScatterMoE LoRA:` setup line says which of these happened. Lists are unchanged, and so is every run without `moe_lora`. This applies to every resident trainer and, since #2072 hands it the streaming setup's resolved targets, to layer streaming. (#2095)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 2280763d..32ae394d 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -1427,7 +1427,7 @@ Both reject silently-no-op combinations: setting either flag without `moe_lora=t
**`moe_lora` requires `lora.dropout: 0.0` on a fused-expert MoE.** transformers 5.x keeps a Qwen3-MoE's experts as fused 3-D parameters (`mlp.experts.gate_up_proj`), which peft adapts through `lora.ParamWrapper`, and that wrapper raises `lora.ParamWrapper does not work with lora_dropout != 0.` With the schema default of `0.05` the LoRA attach failed outright, so `moe_lora` did not work on any task - including `sft`. Soup now stops at the attach with a message naming the flag, instead of letting peft's reach the user, and all 29 shipped recipes that set `moe_lora` pin `lora.dropout: 0.0`. The check is made against the loaded model, not at config load: whether the experts are fused depends on the checkpoint and the transformers version, and a model with one module per expert takes dropout normally. A dense base is untouched - there the flag is a no-op. Since #1421 the refusal covers every fused-expert family, Mixtral and MiniMax included: their experts are now targeted (next paragraph), so peft's wrapper refuses dropout on them too, where before it attached quietly and adapted no experts.
-**`moe_lora` reaches the fused experts on every family (#1421).** On transformers 5 an MoE layer keeps all its routed experts as two 3-D parameters on one module (`mlp.experts.gate_up_proj` and `down_proj`), not as one `nn.Linear` per expert, so module names cannot address them. Until #1421 `moe_lora` named modules only, and whether those names reached the experts depended on peft's own v4→v5 name conversion, which exists for some architectures and not others. Now `resolve_moe_lora_targets` finds the fused parameters on the loaded model and hands them to peft as `target_parameters`, beside the module targets it already resolved (list targets are kept: what `auto` resolves to, so Qwen3.5's `in_proj_qkv` / `out_proj` stay adapted, and an explicit `lora.target_modules` list; a string target such as qwen4_exp's `"all-linear"` or a regex is replaced by the MoE targets; `stream_layers` does the same, resolving the targets before its meta-skeleton probe and handing them to the same helper). Measured on tiny stand-ins with transformers 5.16.1 / peft 0.20.0, routed-expert adapters per family, by module names alone and through the trainer path:
+**`moe_lora` reaches the fused experts on every family (#1421).** On transformers 5 an MoE layer keeps all its routed experts as two 3-D parameters on one module (`mlp.experts.gate_up_proj` and `down_proj`), not as one `nn.Linear` per expert, so module names cannot address them. Until #1421 `moe_lora` named modules only, and whether those names reached the experts depended on peft's own v4→v5 name conversion, which exists for some architectures and not others. Now `resolve_moe_lora_targets` finds the fused parameters on the loaded model and hands them to peft as `target_parameters`, beside the module targets it already resolved (list targets are kept: what `auto` resolves to, so Qwen3.5's `in_proj_qkv` / `out_proj` stay adapted, and an explicit `lora.target_modules` list; a string target such as qwen4_exp's `"all-linear"` or a regex keeps its meaning, without the MoE routers (see below); `stream_layers` does the same, resolving the targets before its meta-skeleton probe and handing them to the same helper). Measured on tiny stand-ins with transformers 5.16.1 / peft 0.20.0, routed-expert adapters per family, by module names alone and through the trainer path:
| family | module names alone (before #1421) | trainer path (now) |
|---|---|---|
@@ -1443,6 +1443,31 @@ Both reject silently-no-op combinations: setting either flag without `moe_lora=t
`minimax-m3-sft` still trains attention-only LoRA: it sets no `moe_lora`, since it loads through SFT's vision path, which never runs the MoE step, and `minimax-m3-dpo` was removed because DPO cannot build the `minimax_m3_vl` wrapper (#1145). The seven `kimi-k2.x` recipes that set `moe_lora` are untested rather than known-good — no tiny stand-in for those configs exists in the installed transformers. A checkpoint that still keeps one `nn.Linear` per expert (the transformers-4 layout) is handled as before: the projections are named as modules and no `target_parameters` are added. `moe_lora` together with `lora.use_vera: true` is refused on a fused-expert model (#1197): VeRA wraps `nn.Linear` modules only and has no `target_parameters` path, so the flag would adapt attention (and a shared expert) exactly as VeRA without it; set `use_vera: false` to adapt the experts with LoRA, or drop `moe_lora`. The per-expert-Linear layout is not refused, VeRA wraps those.
+**A string `target_modules` keeps its meaning under `moe_lora`.** A list target is extended with the MoE names (above). A string is not a list to extend, and it used to be replaced by the MoE list. peft reads a string in one of two ways, and each is now kept:
+
+- `"all-linear"` (in any casing; it is what `target_modules: auto` resolves to on qwen4_exp) means every `nn.Linear` and `Conv1D` except the output embedding, which already includes every module the MoE names reach, so the fused expert parameters are added as `target_parameters`. On qwen4_exp that keeps the Gated DeltaNet, QSA indexer, hyper-connection and PLE projections the MoE list does not name.
+- Any other string is a regex that peft full-matches against each module name. It becomes one regex, `(?:<your regex>)|(?:(?:.*\.)?(?:q_proj|k_proj|…))`, whose second half is peft's list rule for the MoE names, so peft adapts exactly what either half matches, plus the fused expert parameters. A leading global flag such as `(?i)` or `(?x)` stays at the front and applies to your half only. A regex that does not compile is refused at setup, naming `training.lora.target_modules`. A bare module name written as a string (`target_modules: in_proj_qkv`) is still a full-match regex, so it matches no nested module: the setup prints a warning that the regex matches no module and only the `moe_lora` targets attach. Write a list instead.
+
+**Under `moe_lora` a string never adapts a router.** No module whose output is routing logits gets an adapter from a string target. That covers the router (one logit per expert: `mlp.gate` on qwen3_moe, deepseek_v3 and qwen4_exp, `ffn.router` on DBRX, `mlp.router` and the attention's `experts.router` on JetMoE) and the shared-expert gate (the single logit that scales the shared expert, `shared_expert_gate`). They are found from the model's structure:
+
+- Under a module that holds `experts`, a router is a child whose output dimension is the expert count, and a shared-expert gate is a child whose output dimension is 1. The count comes from the experts' 3-D tensors or per-expert modules, or from the config where the experts are stacked 2-D tensors (DBRX).
+- Where there is no `experts` child (JetMoE), a router is a child named `router` or `gate` that sits beside a 3-D expert tensor with as many experts as it has outputs.
+- A router that wraps one `nn.Linear` (DBRX, JetMoE) is kept out through that Linear.
+
+A dense `gate_proj` is never taken for one, and neither is an attention `gate`. They stay out even when your regex names them. Router LoRA is a training-stability risk that a string would otherwise switch on without saying so. To adapt a router anyway, name it in an explicit `target_modules` list, which `moe_lora` extends and never filters.
+
+How the gates are kept out is decided per string, by asking peft's own handling of it:
+
+- The string is kept, and the gates it would reach go to peft's `exclude_modules`. This applies to `all-linear` where peft adapts it as written (qwen4_exp, DBRX, JetMoE) and to a regex on any family. On the families peft converts from the transformers-4 layout (`qwen3_moe`, `deepseek_v3`, `glm4_moe`, `olmoe`, `mixtral`, `minimax` and the rest of transformers' conversion mapping), peft resolves a regex to the last names of the modules it matches, skipping excluded ones. So a regex naming one layer's `q_a_proj` reaches every layer's, with or without `moe_lora`.
+- `all-linear` on those converted families becomes an explicit list. There peft adds the router's old name `gate` to `all-linear` whatever is excluded, and adapts the router weight `mlp.gate.weight` as a parameter, which `exclude_modules` does not reach. The list is what the string means without the gates, plus the MoE names: a leaf name (`q_proj`) where it reaches nothing outside that meaning, the full module path otherwise. A regex on those families becomes such a list only if it reaches a non-router whose last name is `gate`, which peft would rewrite onto every router.
+- With `lora.use_vera: true` a string becomes such a list whenever it would reach a gate, because peft's `VeraConfig` has no `exclude_modules`.
+
+On the converted families peft also renames every target ending in an old expert projection name (`gate_proj`, `up_proj`, `down_proj`) to the fused expert tensor. A dense or shared-expert `nn.Linear` with that name (deepseek_v3's first dense layer and its shared experts) is therefore not adapted as a module, with a list target too.
+
+Without `moe_lora` a string reaches peft unchanged, router included where peft includes it.
+
+The `ScatterMoE LoRA:` setup line says which happened: `keeping target_modules 'all-linear'` or `targeting the target_modules regex or the N MoE module patterns (one combined regex)`, followed by `excluding K MoE router/gate module(s)` when any are excluded; or, for a string turned into a list, `targeting 'all-linear' as a list of N target names` (or `the target_modules regex as a list of N target names`) with the gates it leaves out. Layer streaming hands its resolved targets to the same helper (#2072), so all of this holds under `stream_layers` too.
+
**`target_modules: auto` on a MoE base.** Until #1070 `resolve_lora_target_modules` had no mapping for any MoE architecture Soup ships, so `auto` resolved to `None` and peft refused with `No target_modules passed but also no target_parameters found`. Those architectures now resolve to their attention projections (see `docs/peft-and-efficiency.md`); a MoE architecture neither Soup nor peft maps is refused at setup, naming it. With `moe_lora: true` the targets come from the model scan instead, and that is applied *before* the refusal is decided, so `moe_lora` still works on an unmapped MoE such as `qwen2_moe`.
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 2b84f513..9b288ec0 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -1052,8 +1052,8 @@ class StreamingSetupMixin:
# The attention targets (``auto`` resolved, or the user's list), first:
# they need only the config, and the moe_lora helper below must EXTEND a
# list target, as it does on the resident trainers since #1590 (a string
- # target -- qwen4_exp's "all-linear", a regex -- it replaces, on both
- # paths). Handing it ``None`` and replacing the list with its answer
+ # target -- qwen4_exp's "all-linear", a regex -- it keeps, without the MoE
+ # routers, on both paths). Handing it ``None`` and replacing the list with its answer
# dropped every name the MoE list does not repeat -- MLA's q_a/q_b/kv_a/kv_b
# projections, Qwen3.5's in_proj_qkv / out_proj -- and an explicit list.
target_modules = resolve_lora_target_modules(
diff --git a/src/soup_cli/utils/moe.py b/src/soup_cli/utils/moe.py
index f781a8f9..01acd50c 100644
--- a/src/soup_cli/utils/moe.py
+++ b/src/soup_cli/utils/moe.py
@@ -4,6 +4,7 @@ Supports: Qwen3 MoE (30B-A3B), Mixtral (8x7B, 8x22B), DeepSeek V3, DBRX,
OLMoE, JetMoE, and other models using MoE / sparse expert architectures.
"""
+import re
from typing import Optional
# Known MoE architecture config keys that indicate expert layers
@@ -161,6 +162,109 @@ class MoeLoraTargets(list):
self.target_parameters = list(target_parameters)
+class MoeLoraTargetString(str):
+ """A string ``target_modules`` ``moe_lora`` kept, plus what rides along with it.
+
+ The string twin of :class:`MoeLoraTargets`: peft's ``"all-linear"`` as written,
+ or a user regex joined with the MoE module names into one regex. A ``str``, so
+ every trainer and peft read it as the string target it is. The fused expert
+ ``target_parameters`` and the MoE router / gate modules the string would
+ otherwise reach (``exclude_modules``) ride along to
+ :func:`peft_wiring.build_lora_config`, which hands peft a plain ``str``.
+ """
+
+ __slots__ = ("target_parameters", "exclude_modules")
+
+ def __new__(cls, value, target_parameters=(), exclude_modules=()):
+ instance = super().__new__(cls, value)
+ instance.target_parameters = list(target_parameters)
+ instance.exclude_modules = list(exclude_modules)
+ return instance
+
+
+#: peft's shorthand for every ``nn.Linear`` / ``Conv1D`` but the output head
+#: (``peft.utils.constants.INCLUDE_LINEAR_LAYERS_SHORTHAND``), which peft compares
+#: lower-cased, so ``ALL-LINEAR`` is the same target.
+ALL_LINEAR = "all-linear"
+
+#: A run of global inline flags at the start of a regex: ``(?i)``, ``(?x)(?s)``.
+_LEADING_GLOBAL_FLAGS = re.compile(r"(?:\(\?[aiLmsux]+\))+")
+
+
+def _names_as_full_match_regex(names) -> str:
+ """peft's LIST rule as one full-match regex: the key is a name or ends ``.<name>``."""
+ return r"(?:.*\.)?(?:" + "|".join(re.escape(name) for name in names) + ")"
+
+
+def _join_regex_with_names(user_regex: str, names) -> str:
+ """``(?:<user regex>)|(?:<names>)``: what either half matches, as peft full-matches.
+
+ peft matches a string ``target_modules`` with ``re.fullmatch`` and a list entry
+ with ``key == name or key.endswith("." + name)``; no ``target_modules`` value
+ mixes the two, so the names are spelled as the regex equivalent of that rule.
+ Python accepts global inline flags (``(?i)``, ``(?x)``) only at the start of a
+ pattern, so a leading run of them is hoisted out of the user's group, and the
+ names half is shielded from them with ``(?-imsx:...)``. Under ``(?x)`` a newline
+ closes the user's half first, so a trailing ``# comment`` cannot swallow the
+ closing parenthesis. ``user_regex`` has passed :func:`_check_user_regex`.
+ """
+ flags_match = _LEADING_GLOBAL_FLAGS.match(user_regex)
+ flags = flags_match.group(0) if flags_match else ""
+ body = user_regex[len(flags):]
+ if "x" in flags:
+ body += "\n"
+ names_regex = _names_as_full_match_regex(names)
+ names_group = f"(?-imsx:{names_regex})" if flags else f"(?:{names_regex})"
+ return f"{flags}(?:{body})|{names_group}"
+
+
+def _check_user_regex(user_regex: str) -> None:
+ """Refuse a regex that does not compile, by its field name.
+
+ Rather than let it surface from peft, joined with names the user never wrote.
+ """
+ try:
+ re.compile(user_regex)
+ except re.error as exc:
+ raise ValueError(
+ f"training.lora.target_modules is not a valid regular expression ({exc}). "
+ "peft full-matches a string target_modules against every module name, and "
+ "training.moe_lora adds the MoE module names to it. Fix the regex, or give "
+ "target_modules as a list of module names."
+ ) from exc
+
+
+#: Printed when a regex target full-matches no module path. The regex itself is not
+#: printed: a character class such as ``[qkv]`` is a Rich tag.
+_NO_MODULE_MATCHED = (
+ "[yellow]training.lora.target_modules is a regex that matches no module of this "
+ "model:[/] peft full-matches it against each module's full path, so only "
+ "moe_lora's own targets attach. To name modules by their last name, give "
+ "target_modules as a list."
+)
+
+
+def _matches_a_module(model, user_regex: str) -> bool:
+ try:
+ names = [name for name, _ in model.named_modules() if name]
+ except Exception: # noqa: BLE001 - a stand-in for a model has no modules
+ return True
+ return any(re.fullmatch(user_regex, name) for name in names)
+
+
+def _string_target_kind(target_modules) -> Optional[str]:
+ """``"all-linear"``, ``"regex"``, or ``None`` for a target that is not a string.
+
+ ``auto`` is Soup's unresolved placeholder ("decide for me"), not a peft target,
+ so it is treated like no targets at all, as before.
+ """
+ if not isinstance(target_modules, str) or target_modules == "auto":
+ return None
+ if target_modules.lower() == ALL_LINEAR:
+ return "all-linear"
+ return "regex"
+
+
def peft_routes_lora_to_fused_params(model, target_modules) -> bool:
"""Will peft turn THESE targets into ``target_parameters`` on THIS model?
@@ -198,26 +302,335 @@ def peft_routes_lora_to_fused_params(model, target_modules) -> bool:
# answers every attribute, so peft's lookup succeeds against nothing real and
# the probe comes back True for a model that has no experts at all; a real
# architecture always has a plain string here.
- model_type = getattr(getattr(model, "config", None), "model_type", None)
- if not isinstance(model_type, str):
- return False
+ return bool(_peft_converted_parameters(model, target_modules))
+
+
+def _peft_config_converter():
+ """peft's private v4->v5 conversion, as ``(model, targets, excluded) -> parameters``.
+ ``None`` where peft or that private path is not importable. The probe config is a
+ throwaway, so the conversion's in-place rewrite touches nothing the caller owns.
+ """
try:
from peft import LoraConfig
from peft.utils.transformers_weight_conversion import (
convert_peft_config_for_transformers,
)
except ImportError:
- return False
+ return None
- # A throwaway config, so the conversion's in-place rewrite touches nothing
- # the caller owns.
- probe = LoraConfig(r=8, target_modules=list(target_modules or []))
- try:
+ def convert(model, target_modules, exclude_modules):
+ probe = LoraConfig(
+ r=8, target_modules=target_modules, exclude_modules=list(exclude_modules) or None
+ )
convert_peft_config_for_transformers(probe, model, None)
+ return set(getattr(probe, "target_parameters", None) or ())
+
+ return convert
+
+
+def _peft_all_linear_expander():
+ """peft's private ``all-linear`` expansion, as ``model -> module names``.
+
+ ``None`` where peft or that private path is not importable.
+ """
+ try:
+ from peft import LoraConfig
+ from peft.tuners.tuners_utils import _maybe_include_all_linear_layers
+ except ImportError:
+ return None
+
+ def expand(model):
+ probe = LoraConfig(r=8, target_modules=ALL_LINEAR)
+ return set(_maybe_include_all_linear_layers(probe, model).target_modules)
+
+ return expand
+
+
+def _peft_converted_parameters(model, target_modules, exclude_modules=()) -> Optional[set]:
+ """The ``target_parameters`` peft's v4->v5 conversion makes of these targets.
+
+ Empty when the model has no plain-string ``model_type`` (a stub answers every
+ attribute, so peft's lookup would succeed against nothing real). ``None`` when
+ the answer is unknown: peft, or its private conversion, is not importable, or
+ the conversion raises.
+ """
+ model_type = getattr(getattr(model, "config", None), "model_type", None)
+ if not isinstance(model_type, str):
+ return set()
+ convert = _peft_config_converter()
+ if convert is None:
+ return None
+ # A string stays a string: peft's conversion resolves ``"all-linear"`` or a
+ # regex against the model, where ``list()`` of it would be one target per
+ # character. The exclusions go in too: peft's resolution of a regex skips an
+ # excluded module, its ``all-linear`` does not.
+ if not isinstance(target_modules, str):
+ target_modules = list(target_modules or [])
+ try:
+ return convert(model, target_modules, exclude_modules)
except Exception: # noqa: BLE001 - a probe must never break the run
- return False
- return bool(getattr(probe, "target_parameters", None))
+ return None
+
+
+def _named_children(module) -> dict:
+ try:
+ return dict(module.named_children())
+ except Exception: # noqa: BLE001 - a stand-in for a module has no children
+ return {}
+
+
+def _parameters(module, *, recurse: bool) -> dict:
+ try:
+ return dict(module.named_parameters(recurse=recurse))
+ except Exception: # noqa: BLE001 - a stand-in for a module has no parameters
+ return {}
+
+
+#: Config keys that state a model's TOTAL routed-expert count (never its top-k).
+_EXPERT_COUNT_KEYS = ("num_experts", "num_local_experts", "n_routed_experts", "moe_num_experts")
+
+#: Fewer experts than this is no routing at all.
+_MIN_EXPERTS = 2
+
+
+def _config_expert_counts(model) -> set:
+ """The expert counts the config states, its sub-configs one level down included.
+
+ DBRX keeps its count in ``config.ffn_config.moe_num_experts`` and its experts as
+ 2-D tensors (experts x hidden stacked into one dimension), so no shape gives it.
+ """
+ counts = set()
+ for config in _candidate_configs(model):
+ holders = [config]
+ holders.extend(
+ value for value in getattr(config, "__dict__", {}).values()
+ if hasattr(value, "__dict__")
+ )
+ for holder in holders:
+ for key in _EXPERT_COUNT_KEYS:
+ value = getattr(holder, key, None)
+ if isinstance(value, int) and not isinstance(value, bool):
+ counts.add(value)
+ return {count for count in counts if count >= _MIN_EXPERTS}
+
+
+def _experts_counts(experts) -> set:
+ """Expert counts an ``experts`` module shows: 3-D leading dims, or its per-expert list."""
+ counts = {
+ int(param.shape[0])
+ for param in _parameters(experts, recurse=True).values()
+ if getattr(param, "ndim", 0) == 3
+ }
+ children = list(_named_children(experts).values())
+ if len({type(child) for child in children}) == 1:
+ counts.add(len(children))
+ return {count for count in counts if count >= _MIN_EXPERTS}
+
+
+def _output_dim(module) -> Optional[int]:
+ """``out_features``, the rows of the module's own 2-D ``weight``, or its sole Linear's.
+
+ DBRX's ``DbrxRouter`` and JetMoE's ``JetMoeTopKGating`` wrap one ``nn.Linear``.
+ """
+ out_features = getattr(module, "out_features", None)
+ if isinstance(out_features, int):
+ return out_features
+ weight = _parameters(module, recurse=False).get("weight")
+ if weight is not None and getattr(weight, "ndim", 0) == 2:
+ return int(weight.shape[0])
+ children = list(_named_children(module).values())
+ if len(children) == 1:
+ out_features = getattr(children[0], "out_features", None)
+ if isinstance(out_features, int):
+ return out_features
+ return None
+
+
+#: The names a router goes by when its block has no ``experts`` child (JetMoE).
+_ROUTER_NAMES = ("router", "gate")
+
+
+def find_moe_gates(model) -> list[str]:
+ """Module paths of every MoE router and shared-expert gate, found by structure.
+
+ A router's output is one logit per routed expert; a shared-expert gate's is the
+ single logit that scales the shared expert (``shared_expert_gate`` on Qwen2-MoE,
+ Qwen3-Next and qwen4_exp). Both are routing logits, so under ``moe_lora`` neither
+ gets an adapter from a string target. Two layouts:
+
+ * a block with an ``experts`` child: the router is another child whose output
+ dimension is the expert count, the shared-expert gate one whose output
+ dimension is 1. The count is read from the experts (the leading dimension of
+ their 3-D tensors, or the number of per-expert modules) or, where the experts
+ are stacked 2-D tensors (DBRX), from the config.
+ * a block without one (JetMoE's ``mlp`` and its attention's mixture): a child
+ named ``router`` or ``gate`` whose output dimension is the leading dimension of
+ a sibling's own 3-D expert tensor.
+
+ A module's output dimension is its ``out_features``, the rows of its own 2-D
+ ``weight`` (the transformers-5 ``TopKRouter`` holds a bare parameter), or the
+ ``out_features`` of its sole child (a router that wraps one ``nn.Linear``).
+
+ Only the second layout looks at names, so there a ``gate_proj`` is never a
+ candidate, nor is an attention ``gate`` with no expert tensor beside it. The
+ first is decided by output dimension alone: a direct child of an ``experts``
+ block with one output, or one per expert, is taken whatever its name, a
+ ``gate_proj`` included (no known family has one there). Leaving such a module
+ unadapted is the safer error; a name guard would adapt a router that happened
+ to carry the name. Model order; a stand-in with no modules yields ``[]``.
+ """
+ try:
+ named = list(model.named_modules())
+ except Exception: # noqa: BLE001 - a stand-in for a model has no modules
+ return []
+ config_counts = _config_expert_counts(model)
+ gates = []
+ for path, module in named:
+ children = _named_children(module)
+ prefix = f"{path}." if path else ""
+ experts = children.get("experts")
+ if experts is not None:
+ counts = _experts_counts(experts) or config_counts
+ if not counts:
+ continue
+ for name, child in children.items():
+ if name != "experts" and (
+ _output_dim(child) in counts or _output_dim(child) == 1
+ ):
+ gates.append(prefix + name)
+ continue
+ expert_dims = {
+ int(param.shape[0])
+ for name, child in children.items()
+ if name not in _ROUTER_NAMES
+ for param in _parameters(child, recurse=False).values()
+ if getattr(param, "ndim", 0) == 3 and int(param.shape[0]) >= _MIN_EXPERTS
+ }
+ for name in _ROUTER_NAMES:
+ if name in children and _output_dim(children[name]) in expert_dims:
+ gates.append(prefix + name)
+ return gates
+
+
+def _in_a_gate(name, gates) -> bool:
+ """The module is a gate, or inside one (a router's wrapped ``nn.Linear``)."""
+ return any(name == gate or name.startswith(f"{gate}.") for gate in gates)
+
+
+def _gate_parameter_keys(model, gates) -> list[str]:
+ modules = dict(model.named_modules())
+ return [
+ f"{gate}.{name}"
+ for gate in gates
+ for name in _parameters(modules.get(gate), recurse=True)
+ ]
+
+
+def _lands_on(produced, parameter_keys) -> bool:
+ """Would these ``target_parameters`` adapt any of these parameters?
+
+ The same match peft's ``_inject_parameters`` makes: the key, or a ``.<name>``
+ suffix of it.
+ """
+ return any(
+ key == name or key.endswith(f".{name}") for key in parameter_keys for name in produced
+ )
+
+
+def _all_linear_modules(model) -> Optional[set]:
+ """peft's own ``all-linear``: every ``nn.Linear`` / ``Conv1D`` but the output head.
+
+ ``None`` when peft's private expansion is not importable, or raises (a private
+ signature is not a promise): the caller then fails closed, as for the conversion.
+ """
+ expand = _peft_all_linear_expander()
+ if expand is None:
+ return None
+ try:
+ return expand(model)
+ except Exception: # noqa: BLE001 - a changed private helper must not break setup
+ return None
+
+
+def _linear_modules_by_type(model) -> set:
+ """peft's ``all-linear`` rule without peft: Linear / Conv1D modules but the output head."""
+ head = None
+ get_head = getattr(model, "get_output_embeddings", None)
+ if callable(get_head):
+ try:
+ head = get_head()
+ except Exception: # noqa: BLE001 - a model without an output head
+ head = None
+ return {
+ name
+ for name, module in model.named_modules()
+ if name
+ and module is not head
+ and (
+ isinstance(getattr(module, "out_features", None), int)
+ or type(module).__name__ == "Conv1D"
+ )
+ }
+
+
+def _compact_names(module_names, meant) -> list[str]:
+ """``meant`` as list entries, a leaf name where it reaches nothing else.
+
+ peft matches a list entry by ``key == entry or key.endswith("." + entry)``. A
+ leaf name is used when every module it reaches is in ``meant`` (so it never
+ names a router, the output head or anything outside the string's meaning);
+ otherwise that leaf's modules are listed by full path. Model order, no
+ duplicates.
+ """
+ meant_set = set(meant)
+ by_leaf: dict = {}
+ for name in meant:
+ by_leaf.setdefault(name.rsplit(".", 1)[-1], []).append(name)
+ entries = []
+ for leaf, paths in by_leaf.items():
+ reach = {name for name in module_names if name == leaf or name.endswith(f".{leaf}")}
+ if reach <= meant_set:
+ entries.append(leaf)
+ else:
+ entries.extend(paths)
+ return entries
+
+
+def _materialise(model, kind, target_modules, gates, moe_targets) -> list[str]:
+ """The string as an explicit list: its modules but the gates, then the MoE names.
+
+ ``all-linear`` is peft's own expansion (or, without peft's private helper, the
+ same rule applied by type); a regex is the modules it full-matches. peft's
+ conversion rewrites a list entry by its last name, so an entry that would still
+ land on a gate's parameter that way (a non-router module whose leaf is the
+ router's v4 name, ``gate``) is dropped rather than let it adapt every router.
+ The list is probed once; entries are probed one by one only when it lands. With
+ no answer from peft, an entry whose leaf name is a gate's is dropped.
+ """
+ module_names = [name for name, _ in model.named_modules() if name]
+ if kind == "all-linear":
+ linear = _all_linear_modules(model)
+ if linear is None:
+ linear = _linear_modules_by_type(model)
+ meant = [name for name in module_names if name in linear]
+ else:
+ meant = [name for name in module_names if re.fullmatch(target_modules, name)]
+ meant = [name for name in meant if not _in_a_gate(name, gates)]
+ entries = _compact_names(module_names, meant)
+ entries.extend(name for name in moe_targets if name not in entries)
+ gate_keys = _gate_parameter_keys(model, gates)
+ produced = _peft_converted_parameters(model, entries)
+ if produced is None:
+ gate_leaves = {gate.rsplit(".", 1)[-1] for gate in gates}
+ return [entry for entry in entries if entry.rsplit(".", 1)[-1] not in gate_leaves]
+ if not _lands_on(produced, gate_keys):
+ return entries
+ return [
+ entry
+ for entry in entries
+ if not _lands_on(_peft_converted_parameters(model, [entry]) or (), gate_keys)
+ ]
def _refuse_dropout_on_fused_experts(model, tcfg, target_modules, fused_parameters=()) -> None:
@@ -286,12 +699,35 @@ def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
the one that does not depend on peft's per-architecture name conversion
(#1421: Mixtral, MiniMax, Qwen2-MoE and Qwen3.5-MoE got attention-only LoRA).
+ A STRING target is not a list to extend, and it used to be replaced by the
+ MoE list, which lost what peft makes of it. It is kept, as a
+ :class:`MoeLoraTargetString` carrying the same ``target_parameters``:
+
+ * ``"all-linear"`` (what ``auto`` resolves to on qwen4_exp) as written: peft
+ expands it to every ``nn.Linear`` / ``Conv1D`` but the output head, which
+ already includes every module the MoE names reach. Replacing it dropped
+ qwen4_exp's Gated DeltaNet, indexer, hyper-connection and PLE projections:
+ 10 linears attached on a tiny model, where 32 do now.
+ * any other string, a regex peft full-matches against each module name, as
+ one regex of the union: ``(?:<user regex>)|(?:<the MoE names>)``.
+
+ Either way no MoE router or shared-expert gate (:func:`find_moe_gates`) gets an
+ adapter from the string, even one the user's regex names: they go to peft's
+ ``exclude_modules``, or, where peft's own conversion would still adapt a router
+ weight with them excluded (``all-linear`` on the families peft converts) and
+ with VeRA, the string becomes an explicit list of what it means without them,
+ plus the MoE names (:func:`_string_targets`). To adapt a router, name it in an
+ explicit ``target_modules`` list. Without ``moe_lora`` a string reaches peft
+ untouched, router included where peft includes it. A regex that matches no
+ module is announced, since only the MoE targets would attach.
+
Raises:
ValueError: fused expert parameters will be targeted AND ``lora.use_vera``
is set (VeRA cannot reach them, #1197), or AND ``lora.dropout`` is
non-zero (peft adapts them through ``lora.ParamWrapper``, which refuses
any dropout). Either way the user gets the flag named, not peft's
- message or a quiet attention-only adapter.
+ message or a quiet attention-only adapter. Also when a string target
+ is a regex that does not compile.
"""
if not getattr(tcfg, "moe_lora", False):
return target_modules
@@ -301,18 +737,115 @@ def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
if not moe_targets:
return target_modules
fused = find_fused_expert_parameters(model)
- modules = list(target_modules) if isinstance(target_modules, list) else []
- modules.extend(name for name in moe_targets if name not in modules)
+ kind = _string_target_kind(target_modules)
+ gates, excluded, listed = [], [], False
+ if kind is None:
+ modules = list(target_modules) if isinstance(target_modules, list) else []
+ modules.extend(name for name in moe_targets if name not in modules)
+ else:
+ if kind == "regex":
+ _check_user_regex(target_modules)
+ if console is not None and not _matches_a_module(model, target_modules):
+ console.print(_NO_MODULE_MATCHED)
+ modules, gates, excluded, listed = _string_targets(
+ model, tcfg, kind, target_modules, moe_targets
+ )
_refuse_vera_on_fused_experts(tcfg, fused)
_refuse_dropout_on_fused_experts(model, tcfg, modules, fused)
if console is not None:
- line = f"[green]ScatterMoE LoRA:[/] targeting {len(modules)} module patterns"
- if fused:
- line += f" and {len(fused)} fused expert parameter(s): {', '.join(fused)}"
- console.print(line)
+ console.print(
+ _announcement(kind, listed, modules, moe_targets, fused, gates, excluded)
+ )
+ if kind is not None and not listed:
+ return MoeLoraTargetString(modules, fused, excluded)
return MoeLoraTargets(modules, fused)
+def _string_targets(model, tcfg, kind, target_modules, moe_targets):
+ """A string target under ``moe_lora``: its meaning, without any MoE gate.
+
+ Returns ``(modules, gates, excluded, listed)``. ``modules`` is the string kept
+ (``all-linear`` as written, or the regex joined with the MoE names) with the gate
+ modules it would reach in ``excluded``, for peft's ``exclude_modules``; or, when
+ that cannot keep the gates out, an explicit list (``listed``).
+
+ Decided per string, by asking peft's own conversion of it with those exclusions
+ applied. On the families peft converts from the transformers-4 layout
+ (qwen3_moe, deepseek_v3, ...) peft adds the router's v4 name to ``all-linear``
+ whatever is excluded, and adapts the router weight as a ``target_parameters``
+ entry, which ``exclude_modules`` does not reach; a regex it resolves module by
+ module, skipping what is excluded, so a regex stays a string unless it reaches a
+ non-router whose leaf name is the router's (``gate``). With VeRA, whose
+ ``VeraConfig`` has no ``exclude_modules``, any exclusion means a list. So does
+ an unanswered question (peft's private helpers missing): fail closed.
+ """
+ if kind == "all-linear":
+ kept = target_modules
+ else:
+ kept = _join_regex_with_names(target_modules, moe_targets)
+ gates = find_moe_gates(model)
+ if not gates:
+ return kept, gates, [], False
+ if kind == "all-linear":
+ reached = _all_linear_modules(model)
+ else:
+ reached = {name for name, _ in model.named_modules() if name and re.fullmatch(kept, name)}
+ if reached is None:
+ return _materialise(model, kind, target_modules, gates, moe_targets), gates, [], True
+ excluded = [
+ name for name, _ in model.named_modules() if name in reached and _in_a_gate(name, gates)
+ ]
+ if getattr(getattr(tcfg, "lora", None), "use_vera", False):
+ if excluded:
+ return _materialise(model, kind, target_modules, gates, moe_targets), gates, [], True
+ return kept, gates, [], False
+ produced = _peft_converted_parameters(model, kept, excluded)
+ if produced is None or _lands_on(produced, _gate_parameter_keys(model, gates)):
+ return _materialise(model, kind, target_modules, gates, moe_targets), gates, [], True
+ return kept, gates, excluded, False
+
+
+def _announcement(kind, listed, modules, moe_targets, fused, gates, excluded) -> str:
+ """The setup line: what ``moe_lora`` did to the targets, never the user's regex.
+
+ The regex is not printed: a character class such as ``[qkv]`` is a Rich tag.
+ A string turned into a list is counted, not listed.
+ """
+ patterns = f"the {len(moe_targets)} MoE module patterns"
+ without = f"{len(gates)} MoE router/gate module(s)"
+ joiner = " and"
+ if listed and kind == "all-linear":
+ line = (
+ f"[green]ScatterMoE LoRA:[/] targeting 'all-linear' as a list of "
+ f"{len(modules)} target names: every linear layer but the output head, "
+ f"without the {without}, plus {patterns}"
+ )
+ elif listed:
+ line = (
+ f"[green]ScatterMoE LoRA:[/] targeting the target_modules regex as a list of "
+ f"{len(modules)} target names: the modules it matches, without the {without}, "
+ f"plus {patterns}"
+ )
+ elif kind == "all-linear":
+ line = (
+ f"[green]ScatterMoE LoRA:[/] keeping target_modules 'all-linear' (it already "
+ f"covers {patterns})"
+ )
+ joiner = " and adding"
+ elif kind == "regex":
+ line = (
+ f"[green]ScatterMoE LoRA:[/] targeting the target_modules regex or {patterns} "
+ f"(one combined regex)"
+ )
+ else:
+ line = f"[green]ScatterMoE LoRA:[/] targeting {len(modules)} module patterns"
+ if excluded:
+ line += f", excluding {len(excluded)} MoE router/gate module(s)"
+ if fused:
+ line += f"{joiner} {len(fused)} fused expert parameter(s): {', '.join(fused)}"
+ return line
+
+
def get_moe_info(model) -> dict:
"""Extract MoE architecture details from a model config.
diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.py
index 2380ca74..673528a7 100644
--- a/src/soup_cli/utils/peft_wiring.py
+++ b/src/soup_cli/utils/peft_wiring.py
@@ -547,8 +547,9 @@ def build_peft_config_spec(
def _with_moe_parameters(target_modules: Any, target_parameters: Any) -> Any:
"""Add the fused expert parameters ``moe_lora`` resolved (#1421).
- ``resolve_moe_lora_targets`` returns a ``MoeLoraTargets`` list that carries
- them as ``target_parameters``; merging here, rather than at each call site,
+ ``resolve_moe_lora_targets`` returns a ``MoeLoraTargets`` list (or, for a
+ string target, a ``MoeLoraTargetString``) that carries them as
+ ``target_parameters``; merging here, rather than at each call site,
is what makes every MoE-wired trainer adapt the experts without passing a new
argument. An explicit ``lora.target_parameters`` list is kept and extended.
"""
@@ -599,14 +600,23 @@ def build_lora_config(
"""
import peft
+ # The MoE router / gate modules a string target kept under ``moe_lora`` would
+ # otherwise reach (only ever with LoRA: VeRA gets an explicit list instead).
+ exclude_modules = list(getattr(target_modules, "exclude_modules", None) or ())
target_parameters = _with_moe_parameters(target_modules, target_parameters)
target_modules = _settle_unmapped(target_modules, target_parameters)
+ if isinstance(target_modules, str):
+ # A ``MoeLoraTargetString`` has handed over what rides along with it above;
+ # peft, and the adapter_config.json it saves, get the plain string.
+ target_modules = str(target_modules)
spec = build_peft_config_spec(
lora_cfg,
target_modules=target_modules,
target_parameters=target_parameters,
task_type=task_type,
)
+ if exclude_modules:
+ spec["init_kwargs"]["exclude_modules"] = exclude_modules
config_cls = getattr(peft, spec["peft_cls"])
return config_cls(**spec["init_kwargs"])
diff --git a/tests/test_moe_lora_string_targets.py b/tests/test_moe_lora_string_targets.py
new file mode 100644
index 00000000..d64d4eff
--- /dev/null
+++ b/tests/test_moe_lora_string_targets.py
@@ -0,0 +1,1357 @@
+"""``moe_lora`` keeps a STRING ``target_modules`` and adds the MoE targets on top.
+
+``resolve_moe_lora_targets`` merges the MoE names into a LIST target (#1590), but it
+kept only lists: a string was replaced by the MoE list (``q/k/v/o`` and the expert
+FFN names) plus the fused expert ``target_parameters``. peft gives a string two
+meanings, and both were lost:
+
+* ``"all-linear"``, peft's shorthand for every ``nn.Linear`` but the output head.
+ ``target_modules: auto`` resolves to it on qwen4_exp, so ``moe_lora`` on a qwen4_exp
+ base dropped the Gated DeltaNet ``in_proj_*`` / ``out_proj``, the QSA indexer, the
+ hyper-connection mixers and the PLE projections. On the tiny model below that is 10
+ adapted modules under ``moe_lora`` before this fix and 32 after it: the 34 linears
+ ``all-linear`` adapts without ``moe_lora``, minus the 2 ``shared_expert_gate``,
+ whose output is a routing logit.
+* any other string, which peft full-matches against every module name as a regex.
+
+Now ``"all-linear"`` is kept as it is (it already reaches every module the MoE names
+reach) with the fused expert parameters added, and a regex becomes the one regex
+``(?:<user regex>)|(?:<the MoE names under peft's list rule>)``. Lists are unchanged.
+
+No MoE router or shared-expert gate gets an adapter from a string under ``moe_lora``
+(a module whose output is routing logits): they go to peft's ``exclude_modules``, or,
+on the families where peft's v4->v5 conversion would still adapt the router weight as
+a parameter (qwen3_moe, deepseek_v3, mixtral, ...), the string becomes an explicit
+list of what it means without them. Without ``moe_lora`` a string reaches peft as
+before, router included where peft includes it.
+"""
+
+from __future__ import annotations
+
+import functools
+import re
+import warnings
+from io import StringIO
+from types import SimpleNamespace
+
+import pytest
+
+from soup_cli.utils import moe as moe_mod
+from soup_cli.utils.moe import (
+ MoeLoraTargets,
+ MoeLoraTargetString,
+ resolve_moe_lora_targets,
+)
+
+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
+
+#: The names ``get_moe_target_modules`` returns for :class:`_FakeMoE`.
+_MOE_NAMES = ["q_proj", "k_proj", "v_proj", "o_proj", "down_proj", "gate_proj", "up_proj"]
+_FUSED = ["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]
+_NAMES_REGEX = r"(?:.*\.)?(?:q_proj|k_proj|v_proj|o_proj|down_proj|gate_proj|up_proj)"
+
+#: Module names a regex is checked against: the MoE names, the qwen4_exp linears the
+#: MoE list does not name, a router, the output head, and near-misses of both halves.
+_KEYS = (
+ "lm_head",
+ "q_proj",
+ "model.layers.0.self_attn.q_proj",
+ "model.layers.0.self_attn.Q_PROJ",
+ "model.layers.0.self_attn.q_proj_extra",
+ "model.layers.0.self_attnq_proj",
+ "model.layers.0.mlp.gate",
+ "model.layers.0.mlp.shared_expert.gate_proj",
+ "model.layers.0.mlp.shared_expert_gate",
+ "model.layers.0.linear_attn.in_proj_qkv",
+ "model.layers.0.linear_attn.in_proj_z",
+ "model.layers.0.linear_attn.out_proj",
+ "model.layers.1.self_attn.indexer.index_qk_proj",
+ "model.decoder.block.0.SelfAttention.q",
+ "model.decoder.block.0.EncDecAttention.v",
+ "model.encoder.block.0.SelfAttention.q",
+)
+
+
+def _plain(text: str) -> str:
+ return " ".join(_ANSI_RE.sub("", text).split())
+
+
+class _FakeMoE:
+ """Enough of a model for the helper: an MoE config, module names, 3-D experts."""
+
+ def __init__(self, *, fused: bool = True):
+ self.config = SimpleNamespace(model_type="qwen4_exp_text", num_experts=4)
+ self._fused = fused
+
+ def named_modules(self):
+ names = (
+ "",
+ "model.layers.0.self_attn.q_proj",
+ "model.layers.0.linear_attn.in_proj_qkv",
+ "model.layers.0.mlp.shared_expert.gate_proj",
+ "model.layers.0.mlp.shared_expert.up_proj",
+ "model.layers.0.mlp.shared_expert.down_proj",
+ "lm_head",
+ )
+ return [(name, None) for name in names]
+
+ def named_parameters(self):
+ if not self._fused:
+ return []
+ return [
+ (f"model.layers.0.{suffix}", SimpleNamespace(ndim=3)) for suffix in _FUSED
+ ]
+
+
+def _tcfg(
+ target_modules="auto", *, moe_lora: bool = True, dropout: float = 0.0, use_vera=False
+):
+ return SimpleNamespace(
+ moe_lora=moe_lora,
+ moe_expert_quant=None,
+ lora=SimpleNamespace(
+ r=4,
+ alpha=8,
+ dropout=dropout,
+ use_dora=False,
+ use_rslora=False,
+ use_vera=use_vera,
+ rank_pattern=None,
+ alpha_pattern=None,
+ init_strategy="random",
+ target_modules=target_modules,
+ target_parameters=None,
+ ),
+ )
+
+
+def _resolve(target_modules, *, fused: bool = True, console=None, **tcfg):
+ return resolve_moe_lora_targets(
+ _FakeMoE(fused=fused), _tcfg(**tcfg), target_modules, console
+ )
+
+
+def _announced(target_modules, *, fused: bool = True) -> str:
+ from rich.console import Console
+
+ buf = StringIO()
+ _resolve(target_modules, fused=fused, console=Console(file=buf, width=400))
+ return _plain(buf.getvalue())
+
+
+# --------------------------------------------------------------------------- #
+# "all-linear" #
+# --------------------------------------------------------------------------- #
+
+
+class TestAllLinearIsKept:
+ def test_all_linear_is_kept_and_the_fused_parameters_ride_along(self):
+ targets = _resolve("all-linear")
+
+ assert isinstance(targets, MoeLoraTargetString)
+ assert targets == "all-linear"
+ assert targets.target_parameters == _FUSED
+
+ @pytest.mark.parametrize("spelling", ["all-linear", "ALL-LINEAR", "All-Linear"])
+ def test_every_spelling_peft_accepts_is_kept_as_written(self, spelling):
+ """peft lower-cases the string before comparing it with its shorthand."""
+ targets = _resolve(spelling)
+
+ assert targets == spelling
+ assert "|" not in targets
+
+ def test_the_shorthand_is_peft_s_own(self):
+ pytest.importorskip("peft")
+ from peft.utils.constants import INCLUDE_LINEAR_LAYERS_SHORTHAND
+
+ assert moe_mod.ALL_LINEAR == INCLUDE_LINEAR_LAYERS_SHORTHAND
+
+ def test_a_per_expert_linear_checkpoint_keeps_it_with_no_parameters(self):
+ targets = _resolve("all-linear", fused=False)
+
+ assert targets == "all-linear"
+ assert targets.target_parameters == []
+
+ def test_build_lora_config_hands_peft_a_plain_string_and_the_parameters(self):
+ pytest.importorskip("peft")
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ targets = _resolve("all-linear")
+ config = build_lora_config(_tcfg().lora, target_modules=targets, task_type=None)
+
+ assert type(config.target_modules) is str
+ assert config.target_modules == "all-linear"
+ assert sorted(config.target_parameters) == _FUSED
+
+
+# --------------------------------------------------------------------------- #
+# A regex #
+# --------------------------------------------------------------------------- #
+
+
+def _peft_list_rule(names, key: str) -> bool:
+ """How peft matches a LIST ``target_modules`` (``check_target_module_exists``)."""
+ return key in names or any(key.endswith(f".{name}") for name in names)
+
+
+class TestARegexBecomesOneRegexOfTheUnion:
+ def test_the_documented_shape(self):
+ targets = _resolve(r".*\.linear_attn\.in_proj_qkv")
+
+ assert isinstance(targets, MoeLoraTargetString)
+ assert targets == rf"(?:.*\.linear_attn\.in_proj_qkv)|(?:{_NAMES_REGEX})"
+ assert targets.target_parameters == _FUSED
+
+ @pytest.mark.parametrize(
+ "user_regex",
+ [
+ r".*\.linear_attn\.in_proj_qkv",
+ r".*\.linear_attn\.in_proj_(qkv|z)",
+ r".*\.in_proj_z|.*\.out_proj",
+ r".*\.[qkv]_proj",
+ r"^model\.layers\.0\..*_proj$",
+ r".*decoder.*(SelfAttention|EncDecAttention).*(q|v)$",
+ r"model\.layers\.(\d+)\.self_attn\.q_proj",
+ r"(?i).*\.IN_PROJ_QKV",
+ r"(?i)(?s).*\.IN_PROJ_Z",
+ "(?x) .* \\. linear_attn \\. in_proj_qkv # the Gated DeltaNet input",
+ "in_proj_qkv",
+ ],
+ )
+ def test_it_full_matches_exactly_what_either_half_matches(self, user_regex):
+ """Every spelling peft would full-match: flags, anchors, groups, comments."""
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ joined = str(_resolve(user_regex))
+ for key in _KEYS:
+ expected = bool(re.fullmatch(user_regex, key)) or _peft_list_rule(
+ _MOE_NAMES, key
+ )
+ assert bool(re.fullmatch(joined, key)) is expected, key
+
+ def test_a_leading_case_flag_stays_with_the_user_half(self):
+ joined = str(_resolve(r"(?i).*\.IN_PROJ_QKV"))
+
+ assert re.fullmatch(joined, "model.layers.0.linear_attn.in_proj_qkv")
+ assert not re.fullmatch(joined, "model.layers.0.self_attn.Q_PROJ")
+ assert re.fullmatch(joined, "model.layers.0.self_attn.q_proj")
+
+ def test_a_trailing_verbose_comment_does_not_swallow_the_names(self):
+ joined = str(_resolve("(?x) .* \\. in_proj_qkv # input projection"))
+
+ assert re.fullmatch(joined, "model.layers.0.self_attn.q_proj")
+ assert re.fullmatch(joined, "model.layers.0.linear_attn.in_proj_qkv")
+
+ def test_the_names_half_is_peft_s_list_rule_for_a_dotted_name_too(self):
+ """A list entry may be a dotted suffix; its dot is a dot, not any character."""
+ names = ["self_attn.q_proj", "w1"]
+ names_regex = moe_mod._names_as_full_match_regex(names)
+ for key in (
+ "model.layers.0.self_attn.q_proj",
+ "model.layers.0.self_attnXq_proj",
+ "self_attn.q_proj",
+ "model.layers.0.mlp.experts.0.w1",
+ "model.layers.0.mlp.experts.0.xw1",
+ ):
+ assert bool(re.fullmatch(names_regex, key)) is _peft_list_rule(names, key), key
+
+ def test_an_invalid_regex_is_refused_naming_the_field(self):
+ with pytest.raises(ValueError, match=r"training\.lora\.target_modules is not a valid"):
+ _resolve(r".*\.(q_proj")
+
+ def test_peft_full_matches_the_joined_regex_as_the_union(self):
+ """peft's own matcher, on peft's own configs, agrees key by key."""
+ pytest.importorskip("peft")
+ from peft import LoraConfig
+ from peft.tuners.tuners_utils import check_target_module_exists
+
+ user_regex = r".*\.linear_attn\.in_proj_(qkv|z)"
+ joined = LoraConfig(target_modules=str(_resolve(user_regex)))
+ alone = LoraConfig(target_modules=user_regex)
+ names = LoraConfig(target_modules=list(_MOE_NAMES))
+ for key in _KEYS:
+ expected = bool(check_target_module_exists(alone, key)) or bool(
+ check_target_module_exists(names, key)
+ )
+ assert bool(check_target_module_exists(joined, key)) is expected, key
+
+
+# --------------------------------------------------------------------------- #
+# What did not change #
+# --------------------------------------------------------------------------- #
+
+
+class TestWhatDidNotChange:
+ @pytest.mark.parametrize("target_modules", ["all-linear", r".*\.in_proj_qkv"])
+ def test_without_moe_lora_a_string_is_returned_untouched(self, target_modules):
+ assert _resolve(target_modules, moe_lora=False) is target_modules
+
+ def test_a_dense_model_returns_a_string_untouched(self):
+ dense = SimpleNamespace(config=SimpleNamespace(model_type="llama"))
+ assert resolve_moe_lora_targets(dense, _tcfg(), "all-linear") == "all-linear"
+
+ def test_a_list_is_extended_as_before(self):
+ targets = _resolve(["in_proj_qkv", "q_proj"])
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert list(targets) == ["in_proj_qkv", "q_proj"] + [
+ name for name in _MOE_NAMES if name != "q_proj"
+ ]
+ assert targets.target_parameters == _FUSED
+
+ @pytest.mark.parametrize("unresolved", [None, "auto"])
+ def test_no_targets_and_the_unresolved_sentinel_get_the_moe_list(self, unresolved):
+ """``auto`` is Soup's placeholder, not a peft regex: it means "decide for me"."""
+ targets = _resolve(unresolved)
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert list(targets) == _MOE_NAMES
+
+ def test_an_unmapped_auto_gets_the_moe_list(self):
+ from soup_cli.utils.peft_wiring import UnmappedTargets
+
+ targets = _resolve(UnmappedTargets(["qwen2_moe"]))
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert list(targets) == _MOE_NAMES
+
+
+# --------------------------------------------------------------------------- #
+# The announcement #
+# --------------------------------------------------------------------------- #
+
+
+class TestTheAnnouncementSaysWhatAttaches:
+ def test_a_list_line_is_unchanged(self):
+ assert _announced(["in_proj_qkv"]) == (
+ "ScatterMoE LoRA: targeting 8 module patterns and 2 fused expert "
+ "parameter(s): mlp.experts.down_proj, mlp.experts.gate_up_proj"
+ )
+
+ def test_all_linear_says_it_is_kept_and_what_is_added(self):
+ assert _announced("all-linear") == (
+ "ScatterMoE LoRA: keeping target_modules 'all-linear' (it already covers "
+ "the 7 MoE module patterns) and adding 2 fused expert parameter(s): "
+ "mlp.experts.down_proj, mlp.experts.gate_up_proj"
+ )
+
+ def test_all_linear_without_fused_experts_adds_nothing(self):
+ assert _announced("all-linear", fused=False) == (
+ "ScatterMoE LoRA: keeping target_modules 'all-linear' (it already covers "
+ "the 7 MoE module patterns)"
+ )
+
+ def test_a_regex_says_it_was_joined_with_the_names(self):
+ assert _announced(r".*\.in_proj_qkv") == (
+ "ScatterMoE LoRA: targeting the target_modules regex or the 7 MoE module "
+ "patterns (one combined regex) and 2 fused expert parameter(s): "
+ "mlp.experts.down_proj, mlp.experts.gate_up_proj"
+ )
+
+ def test_a_regex_without_fused_experts(self):
+ assert _announced(r".*\.in_proj_qkv", fused=False) == (
+ "ScatterMoE LoRA: targeting the target_modules regex or the 7 MoE module "
+ "patterns (one combined regex)"
+ )
+
+ def test_the_user_regex_is_not_printed_as_markup(self):
+ """A character class is a Rich tag; the line never carries the user's text."""
+ line = _announced(r".*\.[qkv]_proj|.*\.[/]")
+
+ assert "[qkv]" not in line
+ assert line.startswith("ScatterMoE LoRA: targeting the target_modules regex")
+
+
+# --------------------------------------------------------------------------- #
+# Stand-ins: the transformers-4 layout, one nn.Linear per expert #
+# --------------------------------------------------------------------------- #
+
+
+def _per_expert_linear_moe(
+ torch,
+ *,
+ model_type="mixtral",
+ shared_gate=False,
+ attn_gate=False,
+ dense_out=False,
+ layers=1,
+ experts=2,
+ block_gate_proj=None,
+):
+ """One ``nn.Linear`` per expert and an ``nn.Linear`` router, as ``model_type``.
+
+ peft converts a ``mixtral`` from this layout (its ``all-linear`` there adds the
+ router weight); a ``qwen2_moe`` it does not. ``shared_gate`` adds a one-logit
+ ``shared_expert_gate``; ``attn_gate`` a non-router ``nn.Linear`` whose leaf name is
+ the router's, ``gate``; ``dense_out`` an attention ``nn.Linear`` no MoE name
+ reaches; ``block_gate_proj`` (an output size) a ``gate_proj`` beside the router,
+ whose path starts with the router's.
+ """
+
+ class _PerExpertLinearMoE(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = SimpleNamespace(model_type=model_type, num_local_experts=experts)
+ blocks = []
+ for _ in range(layers):
+ attention = {name: torch.nn.Linear(8, 8) for name in ("q_proj", "v_proj")}
+ if attn_gate:
+ attention["gate"] = torch.nn.Linear(8, 8)
+ if dense_out:
+ attention["dense_out"] = torch.nn.Linear(8, 8)
+ per_expert = torch.nn.ModuleList(
+ torch.nn.ModuleDict(
+ {
+ "gate_proj": torch.nn.Linear(8, 16),
+ "up_proj": torch.nn.Linear(8, 16),
+ "down_proj": torch.nn.Linear(16, 8),
+ }
+ )
+ for _ in range(experts)
+ )
+ block = {"gate": torch.nn.Linear(8, experts), "experts": per_expert}
+ if block_gate_proj is not None:
+ block["gate_proj"] = torch.nn.Linear(8, block_gate_proj)
+ if shared_gate:
+ block["shared_expert_gate"] = torch.nn.Linear(8, 1)
+ blocks.append(
+ torch.nn.ModuleDict(
+ {
+ "self_attn": torch.nn.ModuleDict(attention),
+ "block_sparse_moe": torch.nn.ModuleDict(block),
+ }
+ )
+ )
+ self.layers = torch.nn.ModuleList(blocks)
+
+ return _PerExpertLinearMoE()
+
+
+def _jetmoe_like(torch):
+ """JetMoE's layout without its experts child, plus the near-misses it must ignore.
+
+ ``mlp.router`` wraps one ``nn.Linear`` beside a 3-D expert tensor; ``mlp.gate_proj``
+ is a dense projection with the same output size; ``attn.gate`` is an attention
+ gate with no expert tensor beside it. ``mixture`` is JetMoE's attention layout: an
+ ``experts`` module that is not a per-expert list (three different children, so
+ not three experts), whose router sits inside it, beside a ``kv_proj`` with three
+ outputs.
+ """
+
+ class _Router(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.layer = torch.nn.Linear(8, 4, bias=False)
+
+ class _ParallelExperts(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(4, 16, 8))
+
+ class _JetMoeLike(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = SimpleNamespace(model_type="jetmoe", num_local_experts=4)
+ self.mlp = torch.nn.ModuleDict(
+ {
+ "input_linear": _ParallelExperts(),
+ "router": _Router(),
+ "gate_proj": torch.nn.Linear(8, 4),
+ }
+ )
+ self.attn = torch.nn.ModuleDict(
+ {"gate": torch.nn.Linear(8, 4), "q_proj": torch.nn.Linear(8, 8)}
+ )
+ mixture = torch.nn.ModuleDict(
+ {
+ "input_linear": _ParallelExperts(),
+ "output_linear": _ParallelExperts(),
+ "router": _Router(),
+ }
+ )
+ self.mixture = torch.nn.ModuleDict(
+ {"experts": mixture, "kv_proj": torch.nn.Linear(8, 3)}
+ )
+
+ return _JetMoeLike()
+
+
+def _peft_attach(model, peft_config):
+ from peft import get_peft_model
+
+ tuner = get_peft_model(model, peft_config).base_model
+ return set(tuner.targeted_module_names), set(tuner.targeted_parameter_names)
+
+
+def _stand_in_attach(tcfg, target_modules, **layout):
+ """Resolve on one stand-in, attach the config ``build_lora_config`` makes to another."""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("transformers")
+ pytest.importorskip("peft")
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ targets = resolve_moe_lora_targets(
+ _per_expert_linear_moe(torch, **layout), tcfg, target_modules
+ )
+ peft_config = build_lora_config(tcfg.lora, target_modules=targets, task_type=None)
+ modules, params = _peft_attach(_per_expert_linear_moe(torch, **layout), peft_config)
+ return targets, peft_config, modules, params
+
+
+_ROUTER = "layers.0.block_sparse_moe.gate"
+_SHARED_GATE = "layers.0.block_sparse_moe.shared_expert_gate"
+
+
+class TestTheDropoutRefusalReadsAStringAsAString:
+ def test_dropout_with_fused_experts_is_refused_for_a_string(self):
+ with pytest.raises(ValueError, match=r"training\.lora\.dropout: 0\.0"):
+ _resolve("all-linear", dropout=0.05)
+
+ def test_the_probe_reads_a_string_as_a_string(self):
+ """peft rewrites ``all-linear`` into target_parameters on a ``mixtral``-type
+ model (the router and the expert names); ``list()`` of the string would be one
+ target per character, which peft rewrites into nothing."""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("transformers")
+ pytest.importorskip("peft")
+
+ model = _per_expert_linear_moe(torch)
+ assert moe_mod.find_fused_expert_parameters(model) == []
+ assert moe_mod.peft_routes_lora_to_fused_params(model, "all-linear") is True
+
+ def test_without_the_router_all_linear_keeps_dropout_on_that_family(self):
+ """The router was the one target peft wraps in ``lora.ParamWrapper`` there."""
+ torch = pytest.importorskip("torch")
+ targets, _, modules, params = _stand_in_attach(_tcfg(dropout=0.05), "all-linear")
+ from peft import LoraConfig, get_peft_model
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert _ROUTER not in modules and not params
+ # ...where peft's own all-linear, router included, refuses the dropout.
+ with pytest.raises(ValueError, match="ParamWrapper"):
+ get_peft_model(
+ _per_expert_linear_moe(torch),
+ LoraConfig(r=4, target_modules="all-linear", lora_dropout=0.05),
+ )
+
+ def test_a_regex_on_that_family_stays_a_string_and_keeps_dropout(self):
+ targets, peft_config, modules, params = _stand_in_attach(
+ _tcfg(dropout=0.05), r".*\.self_attn\.v_proj"
+ )
+
+ assert isinstance(targets, MoeLoraTargetString)
+ assert not peft_config.exclude_modules
+ assert "layers.0.self_attn.v_proj" in modules
+ assert _ROUTER not in modules and not params
+
+
+class TestTheGatesStayOutOnStandIns:
+ def test_a_shared_expert_gate_is_left_out_of_the_list(self):
+ targets, _, modules, params = _stand_in_attach(_tcfg(), "all-linear", shared_gate=True)
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert "shared_expert_gate" not in targets
+ assert not {_ROUTER, _SHARED_GATE} & modules and not params
+ assert "layers.0.block_sparse_moe.experts.1.down_proj" in modules
+
+ def test_a_non_router_named_gate_is_dropped_rather_than_reach_the_routers(self):
+ """peft's conversion rewrites any entry ending ``.gate`` into ``gate.weight``,
+ which lands on every router: such an entry cannot be kept without them."""
+ targets, _, modules, params = _stand_in_attach(_tcfg(), "all-linear", attn_gate=True)
+
+ assert not [entry for entry in targets if entry.rsplit(".", 1)[-1] == "gate"]
+ assert _ROUTER not in modules and not params
+ assert "layers.0.self_attn.q_proj" in modules
+
+ def test_a_regex_reaching_a_non_router_named_gate_becomes_a_list(self):
+ """Kept, the regex would make peft rewrite ``self_attn.gate`` onto the router."""
+ targets, _, modules, params = _stand_in_attach(
+ _tcfg(), r".*\.self_attn\.(q_proj|gate)", attn_gate=True
+ )
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert "q_proj" in targets
+ assert not [entry for entry in targets if entry.rsplit(".", 1)[-1] == "gate"]
+ assert _ROUTER not in modules and not params
+
+ def test_exclude_modules_keeps_linear_gates_out_where_peft_does_not_convert(self):
+ targets, peft_config, modules, params = _stand_in_attach(
+ _tcfg(), "all-linear", model_type="qwen2_moe", shared_gate=True
+ )
+
+ assert isinstance(targets, MoeLoraTargetString) and targets == "all-linear"
+ assert set(peft_config.exclude_modules) == {_ROUTER, _SHARED_GATE}
+ assert not {_ROUTER, _SHARED_GATE} & modules and not params
+ assert "layers.0.block_sparse_moe.experts.0.gate_proj" in modules
+
+ @pytest.mark.parametrize("model_type", ["qwen2_moe", "mixtral"])
+ def test_a_gate_proj_beside_the_router_is_still_adapted(self, model_type):
+ """``…block_sparse_moe.gate_proj`` starts with the router's path, not inside it."""
+ gate_proj = "layers.0.block_sparse_moe.gate_proj"
+ targets, peft_config, modules, params = _stand_in_attach(
+ _tcfg(), "all-linear", model_type=model_type, block_gate_proj=16
+ )
+
+ assert gate_proj in modules
+ assert _ROUTER not in modules and not params
+ if model_type == "qwen2_moe":
+ assert isinstance(targets, MoeLoraTargetString)
+ assert list(peft_config.exclude_modules) == [_ROUTER]
+
+ def test_vera_gets_a_list_because_vera_has_no_exclude_modules(self):
+ targets, peft_config, modules, _ = _stand_in_attach(
+ _tcfg(use_vera=True), "all-linear", model_type="qwen2_moe", shared_gate=True
+ )
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert type(peft_config).__name__ == "VeraConfig"
+ assert not {_ROUTER, _SHARED_GATE} & modules
+ assert "layers.0.self_attn.q_proj" in modules
+
+ def test_vera_keeps_a_regex_that_reaches_no_gate(self):
+ targets, peft_config, modules, _ = _stand_in_attach(
+ _tcfg(use_vera=True), r".*\.self_attn\.q_proj", model_type="qwen2_moe",
+ shared_gate=True,
+ )
+
+ assert isinstance(targets, MoeLoraTargetString)
+ assert type(peft_config.target_modules) is str
+ assert not {_ROUTER, _SHARED_GATE} & modules
+ assert "layers.0.self_attn.q_proj" in modules
+
+ def test_a_listed_regex_is_what_it_full_matches_not_a_prefix(self):
+ """VeRA lists this regex (it reaches the router); ``dense`` is only a prefix."""
+ targets, _, modules, _ = _stand_in_attach(
+ _tcfg(use_vera=True),
+ r"layers\.0\.self_attn\.dense|.*\.block_sparse_moe\.gate",
+ model_type="qwen2_moe",
+ dense_out=True,
+ )
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert not [entry for entry in targets if entry.endswith("dense_out")]
+ assert "layers.0.self_attn.dense_out" not in modules and _ROUTER not in modules
+
+ def test_a_leaf_that_reaches_beyond_the_regex_is_listed_by_path(self):
+ targets, _, modules, _ = _stand_in_attach(
+ _tcfg(use_vera=True),
+ r"layers\.0\.self_attn\.dense_out|.*\.block_sparse_moe\.gate",
+ model_type="qwen2_moe",
+ dense_out=True,
+ layers=2,
+ )
+
+ assert "layers.0.self_attn.dense_out" in targets
+ assert "dense_out" not in targets
+ assert "layers.0.self_attn.dense_out" in modules
+ assert "layers.1.self_attn.dense_out" not in modules
+
+ def test_the_list_is_announced_with_its_count(self):
+ from rich.console import Console
+
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("peft")
+ buf = StringIO()
+ resolve_moe_lora_targets(
+ _per_expert_linear_moe(torch, attn_gate=True),
+ _tcfg(),
+ r".*\.self_attn\.(q_proj|gate)",
+ Console(file=buf, width=400),
+ )
+
+ assert _plain(buf.getvalue()) == (
+ "ScatterMoE LoRA: targeting the target_modules regex as a list of 7 target "
+ "names: the modules it matches, without the 1 MoE router/gate module(s), plus "
+ "the 7 MoE module patterns"
+ )
+
+
+class TestFailClosedWithoutPeftsPrivateHelpers:
+ """No answer from peft means a list, never a string peft might route to a router."""
+
+ def test_without_the_all_linear_expander_the_string_becomes_a_list(self, monkeypatch):
+ monkeypatch.setattr(moe_mod, "_peft_all_linear_expander", lambda: None)
+ modules, params, targets = _attach_uncached("qwen4_exp", "auto")
+ expected_modules, expected_params, _ = _expected("qwen4_exp", "auto")
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert modules == expected_modules and params == expected_params
+
+ def test_an_all_linear_expander_that_raises_fails_closed(self, monkeypatch):
+ """A private helper whose signature changed raises; setup lists, not crashes."""
+
+ def changed_signature(_model):
+ raise TypeError("_maybe_include_all_linear_layers() missing 1 required argument")
+
+ monkeypatch.setattr(moe_mod, "_peft_all_linear_expander", lambda: changed_signature)
+ modules, params, targets = _attach_uncached("qwen4_exp", "auto")
+ expected_modules, expected_params, gates = _expected("qwen4_exp", "auto")
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert modules == expected_modules and params == expected_params
+ assert not gates & modules
+
+ def test_without_the_conversion_the_string_becomes_a_list(self, monkeypatch):
+ monkeypatch.setattr(moe_mod, "_peft_config_converter", lambda: None)
+ modules, params, targets = _attach_uncached("qwen4_exp", "auto")
+ expected_modules, expected_params, _ = _expected("qwen4_exp", "auto")
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert modules == expected_modules and params == expected_params
+
+ def test_a_peft_without_the_private_modules_fails_closed(self, monkeypatch):
+ """The import guards: a peft that lacks either private module answers nothing."""
+ import sys
+
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ model = _read_only("qwen4_exp")
+ monkeypatch.setitem(sys.modules, "peft.tuners.tuners_utils", None)
+ monkeypatch.setitem(sys.modules, "peft.utils.transformers_weight_conversion", None)
+
+ assert moe_mod._peft_all_linear_expander() is None
+ assert moe_mod._peft_config_converter() is None
+ targets = resolve_moe_lora_targets(model, _tcfg(), "all-linear")
+ monkeypatch.undo()
+ modules, params = _peft_attach(
+ _build("qwen4_exp"),
+ build_lora_config(_tcfg().lora, target_modules=targets, task_type=None),
+ )
+ expected_modules, expected_params, _ = _expected("qwen4_exp", "auto")
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert modules == expected_modules and params == expected_params
+
+ def test_without_the_conversion_a_gate_named_entry_is_dropped(self, monkeypatch):
+ monkeypatch.setattr(moe_mod, "_peft_config_converter", lambda: None)
+ targets, _, modules, params = _stand_in_attach(_tcfg(), "all-linear", attn_gate=True)
+
+ assert not [entry for entry in targets if entry.rsplit(".", 1)[-1] == "gate"]
+ assert _ROUTER not in modules and not params
+
+
+class TestARegexThatMatchesNothingIsAnnounced:
+ def test_a_bare_name_written_as_a_string_is_warned_about(self):
+ line = _announced("in_proj_qkv")
+
+ assert line.startswith(
+ "training.lora.target_modules is a regex that matches no module of this model:"
+ )
+ assert "only moe_lora's own targets attach" in line
+
+ def test_a_regex_that_matches_says_nothing_extra(self):
+ assert not _announced(r".*\.in_proj_qkv").startswith("training.lora")
+
+
+# --------------------------------------------------------------------------- #
+# End to end: tiny real models, the trainer's sequence, real get_peft_model #
+# --------------------------------------------------------------------------- #
+
+_SMALL = dict(
+ vocab_size=64,
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ num_key_value_heads=1,
+ pad_token_id=0,
+)
+
+
+def _build(arch: str):
+ torch = pytest.importorskip("torch")
+ transformers = pytest.importorskip("transformers")
+ pytest.importorskip("peft")
+ torch.manual_seed(0)
+ if arch == "qwen4_exp":
+ try:
+ from transformers import Qwen4ExpConfig, Qwen4ExpTextConfig
+ except ImportError:
+ pytest.skip("installed Transformers release does not include qwen4_exp")
+ text = Qwen4ExpTextConfig(
+ vocab_size=64,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ num_key_value_heads=1,
+ head_dim=8,
+ linear_conv_kernel_dim=2,
+ linear_key_head_dim=4,
+ linear_value_head_dim=4,
+ linear_num_key_heads=2,
+ linear_num_value_heads=2,
+ moe_intermediate_size=8,
+ shared_expert_intermediate_size=8,
+ num_experts_per_tok=1,
+ num_experts=2,
+ layer_types=["linear_attention", "full_attention"],
+ max_position_embeddings=64,
+ hc_count=2,
+ hc_lowrank=4,
+ ple_layer_ids=[1],
+ use_cache=False,
+ indexer_n_heads=1,
+ indexer_kv_heads=1,
+ indexer_head_dim=8,
+ indexer_budget=8,
+ indexer_compress_ratio=2,
+ eos_token_id=1,
+ pad_token_id=0,
+ )
+ return transformers.AutoModelForCausalLM.from_config(
+ Qwen4ExpConfig(text_config=text.to_dict())
+ )
+ if arch == "qwen3_moe":
+ return transformers.Qwen3MoeForCausalLM(
+ transformers.Qwen3MoeConfig(
+ **_SMALL, num_experts=4, num_experts_per_tok=2, moe_intermediate_size=16
+ )
+ )
+ if arch == "deepseek_v3":
+ return transformers.DeepseekV3ForCausalLM(
+ transformers.DeepseekV3Config(
+ vocab_size=64,
+ hidden_size=32,
+ intermediate_size=64,
+ moe_intermediate_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ n_routed_experts=4,
+ num_experts_per_tok=2,
+ n_shared_experts=1,
+ n_group=1,
+ topk_group=1,
+ first_k_dense_replace=1,
+ q_lora_rank=16,
+ kv_lora_rank=16,
+ qk_rope_head_dim=8,
+ qk_nope_head_dim=8,
+ v_head_dim=8,
+ pad_token_id=0,
+ )
+ )
+ if arch == "dbrx":
+ return transformers.DbrxForCausalLM(
+ transformers.DbrxConfig(
+ d_model=32,
+ n_heads=2,
+ n_layers=2,
+ max_seq_len=64,
+ vocab_size=64,
+ attn_config={"kv_n_heads": 1, "rope_theta": 10000.0},
+ ffn_config={"ffn_hidden_size": 16, "moe_num_experts": 4, "moe_top_k": 2},
+ )
+ )
+ if arch == "jetmoe":
+ return transformers.JetMoeForCausalLM(
+ transformers.JetMoeConfig(
+ vocab_size=64,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_key_value_heads=2,
+ kv_channels=8,
+ intermediate_size=16,
+ num_local_experts=4,
+ num_experts_per_tok=2,
+ max_position_embeddings=64,
+ )
+ )
+ if arch == "dense":
+ return transformers.LlamaForCausalLM(transformers.LlamaConfig(**_SMALL))
+ raise KeyError(arch)
+
+
[email protected]_cache(maxsize=None)
+def _read_only(arch: str):
+ """One model per architecture for the checks that only read it."""
+ return _build(arch)
+
+
+def _attach_uncached(arch: str, target_modules, *, moe_lora: bool = True):
+ """``attach_preflight.trainer_lora_config`` (the trainer's sequence), then peft."""
+ from soup_cli.utils.attach_preflight import trainer_lora_config
+
+ model = _build(arch)
+ cfg = SimpleNamespace(
+ task="sft", modality="text", training=_tcfg(target_modules, moe_lora=moe_lora)
+ )
+ peft_config, targets = trainer_lora_config(model, cfg)
+ modules, params = _peft_attach(model, peft_config)
+ return frozenset(modules), frozenset(params), targets
+
+
[email protected]_cache(maxsize=None)
+def _attach(arch: str, target_modules, *, moe_lora: bool):
+ """Cached: each test reads the same few attaches, and a result is frozen sets."""
+ return _attach_uncached(arch, target_modules, moe_lora=moe_lora)
+
+
+#: The families among these that peft converts from the transformers-4 layout. There
+#: peft resolves a regex to the last names of the modules it matches, and renames a
+#: target whose last name is a v4 expert projection into the fused expert parameter,
+#: so an ``nn.Linear`` with that leaf name (deepseek_v3's dense MLP and its shared
+#: experts) is not adapted as a module, whatever the target: peft's behaviour, the
+#: same with a list.
+_PEFT_CONVERTS = {"qwen3_moe", "deepseek_v3"}
+_V4_EXPERT_NAMES = {"gate_proj", "up_proj", "down_proj"}
+
+
[email protected]_cache(maxsize=None)
+def _expected(arch: str, target_modules):
+ """What should attach, worked out from the model alone.
+
+ The string's meaning without the gates (each ``*Router`` module and each
+ ``shared_expert_gate``), plus the modules the MoE names reach under peft's list
+ rule; the parameters are every routed-expert tensor. ``all-linear`` means every
+ ``nn.Linear`` but ``lm_head``; a regex the modules it full-matches, or, on a
+ family peft converts, every ``nn.Linear`` sharing a last name with one of those.
+ Returns ``(modules, parameters, gates)``.
+ """
+ torch = pytest.importorskip("torch")
+ model = _read_only(arch)
+ named = list(model.named_modules())
+ linear = {
+ name for name, module in named
+ if isinstance(module, torch.nn.Linear) and name != "lm_head"
+ }
+ gates = {
+ name for name, module in named
+ if "router" in type(module).__name__.lower() or name.endswith(".shared_expert_gate")
+ }
+ if target_modules in ("auto", "all-linear"):
+ meant = linear
+ else:
+ matched = {
+ name for name, _ in named if name and re.fullmatch(target_modules, name)
+ } - gates
+ if arch in _PEFT_CONVERTS:
+ leaves = {name.rsplit(".", 1)[-1] for name in matched}
+ meant = {name for name in linear if name.rsplit(".", 1)[-1] in leaves}
+ else:
+ meant = matched
+ names = moe_mod.get_moe_target_modules(model)
+ modules = (meant | {name for name in linear if _peft_list_rule(names, name)}) - gates
+ if arch in _PEFT_CONVERTS:
+ modules = {name for name in modules if name.rsplit(".", 1)[-1] not in _V4_EXPERT_NAMES}
+ parameters = {
+ name for name, param in model.named_parameters()
+ if param.ndim == 3 and ".experts." in name
+ }
+ return frozenset(modules), frozenset(parameters), frozenset(gates)
+
+
+#: (arch, target_modules). ``auto`` on qwen4_exp is the reported case: it resolves to
+#: ``"all-linear"``, which peft does not convert there. qwen3_moe and deepseek_v3 are
+#: families peft converts.
+_PLAIN_CASES = [
+ ("qwen4_exp", "auto"),
+ ("qwen3_moe", "all-linear"),
+ ("deepseek_v3", "all-linear"),
+ ("qwen4_exp", r".*\.linear_attn\.in_proj_(qkv|z)"),
+ ("qwen3_moe", r"model\.layers\.0\.self_attn\.q_proj"),
+ ("deepseek_v3", r".*\.self_attn\.(q_a_proj|kv_a_proj_with_mqa)"),
+ ("deepseek_v3", r"model\.layers\.0\.self_attn\.q_a_proj"),
+]
+#: A regex that names the routers itself: under moe_lora they are still left out.
+_ROUTER_NAMING_CASES = [
+ ("qwen3_moe", r".*\.mlp\.gate|.*\.self_attn\.q_proj"),
+ ("deepseek_v3", r".*\.mlp\.gate|.*\.self_attn\.q_a_proj"),
+ ("qwen4_exp", r".*\.mlp\.(gate|shared_expert_gate)|.*\.in_proj_z"),
+]
+_STRING_CASES = _PLAIN_CASES + _ROUTER_NAMING_CASES
+
+
+class TestTheGatesAreFoundByStructure:
+ @pytest.mark.parametrize(
+ ("arch", "gates"),
+ [
+ ("qwen3_moe", {"model.layers.0.mlp.gate", "model.layers.1.mlp.gate"}),
+ ("deepseek_v3", {"model.layers.1.mlp.gate"}),
+ (
+ "qwen4_exp",
+ {
+ "model.layers.0.mlp.gate",
+ "model.layers.0.mlp.shared_expert_gate",
+ "model.layers.1.mlp.gate",
+ "model.layers.1.mlp.shared_expert_gate",
+ },
+ ),
+ # DbrxRouter wraps one nn.Linear; its experts are stacked 2-D tensors, so
+ # the count comes from config.ffn_config.moe_num_experts.
+ ("dbrx", {"transformer.blocks.0.ffn.router", "transformer.blocks.1.ffn.router"}),
+ # JetMoE has no experts child: each router sits beside 3-D expert tensors,
+ # in the MLP and in the attention's mixture of experts.
+ (
+ "jetmoe",
+ {
+ "model.layers.0.mlp.router",
+ "model.layers.0.self_attention.experts.router",
+ "model.layers.1.mlp.router",
+ "model.layers.1.self_attention.experts.router",
+ },
+ ),
+ ],
+ )
+ def test_every_router_and_shared_expert_gate(self, arch, gates):
+ found = moe_mod.find_moe_gates(_read_only(arch))
+
+ assert set(found) == gates
+ assert len(found) == len(gates)
+
+ def test_the_per_expert_layout(self):
+ torch = pytest.importorskip("torch")
+ model = _per_expert_linear_moe(torch, shared_gate=True, attn_gate=True)
+
+ assert moe_mod.find_moe_gates(model) == [_ROUTER, _SHARED_GATE]
+
+ def test_a_router_beside_expert_tensors_but_no_dense_or_attention_gate(self):
+ torch = pytest.importorskip("torch")
+
+ assert moe_mod.find_moe_gates(_jetmoe_like(torch)) == [
+ "mlp.router",
+ "mixture.experts.router",
+ ]
+
+ def test_fused_experts_give_the_count_when_the_config_states_none(self):
+ """The 3-D expert tensors alone say how many experts there are."""
+ torch = pytest.importorskip("torch")
+
+ class _Experts(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.gate_up_proj = torch.nn.Parameter(torch.zeros(3, 16, 8))
+ self.down_proj = torch.nn.Parameter(torch.zeros(3, 8, 8))
+
+ class _TopKRouter(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(3, 8))
+
+ class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = SimpleNamespace(model_type="custom_moe")
+ self.mlp = torch.nn.ModuleDict(
+ {"gate": _TopKRouter(), "experts": _Experts(), "up": torch.nn.Linear(8, 4)}
+ )
+
+ assert moe_mod.find_moe_gates(_Model()) == ["mlp.gate"]
+
+ def test_in_an_experts_block_the_output_decides_not_the_name(self):
+ """A child with one output per expert is taken there, a ``gate_proj`` too.
+
+ The documented trade-off: leaving such a module unadapted is the safer error.
+ With any other output size the same ``gate_proj`` is not a gate.
+ """
+ torch = pytest.importorskip("torch")
+ gate_proj = "layers.0.block_sparse_moe.gate_proj"
+
+ assert gate_proj in moe_mod.find_moe_gates(
+ _per_expert_linear_moe(torch, block_gate_proj=2)
+ )
+ assert gate_proj not in moe_mod.find_moe_gates(
+ _per_expert_linear_moe(torch, block_gate_proj=16)
+ )
+
+ def test_a_single_expert_block_routes_nothing(self):
+ torch = pytest.importorskip("torch")
+ model = _per_expert_linear_moe(torch, experts=1, shared_gate=True)
+
+ assert moe_mod.find_moe_gates(model) == []
+
+ def test_a_dense_model_and_a_stand_in_have_none(self):
+ assert moe_mod.find_moe_gates(_read_only("dense")) == []
+ assert moe_mod.find_moe_gates(_FakeMoE()) == []
+
+
+class TestTheStringMinusTheGatesAttaches:
+ @pytest.mark.parametrize(("arch", "target_modules"), _STRING_CASES)
+ def test_the_adapted_set_is_the_expected_one(self, arch, target_modules):
+ modules, params, _ = _attach(arch, target_modules, moe_lora=True)
+ expected_modules, expected_params, _ = _expected(arch, target_modules)
+
+ assert expected_params
+ assert modules == expected_modules
+ assert params == expected_params
+
+ @pytest.mark.parametrize(("arch", "target_modules"), _STRING_CASES)
+ def test_no_router_gate_or_output_head_is_adapted(self, arch, target_modules):
+ modules, params, _ = _attach(arch, target_modules, moe_lora=True)
+ _, _, gates = _expected(arch, target_modules)
+
+ assert gates
+ assert not gates & modules
+ assert not {param.rsplit(".", 1)[0] for param in params} & gates
+ assert not any(name.endswith("lm_head") for name in modules)
+
+ @pytest.mark.parametrize("arch", ["dbrx", "jetmoe"])
+ def test_a_router_that_wraps_a_linear_is_left_out(self, arch):
+ """DBRX and JetMoE: all-linear is kept, the routers' Linears are excluded."""
+ torch = pytest.importorskip("torch")
+ modules, params, targets = _attach(arch, "all-linear", moe_lora=True)
+ model = _read_only(arch)
+ linear = {
+ name for name, module in model.named_modules()
+ if isinstance(module, torch.nn.Linear) and name != "lm_head"
+ }
+ router_linears = {name for name in linear if ".router." in name}
+
+ assert router_linears
+ assert isinstance(targets, MoeLoraTargetString) and targets == "all-linear"
+ assert set(targets.exclude_modules) == router_linears
+ assert modules == linear - router_linears
+ assert not any(".router." in param for param in params)
+
+ @pytest.mark.parametrize(("arch", "target_modules"), _PLAIN_CASES)
+ def test_without_moe_lora_the_string_reaches_peft_untouched(self, arch, target_modules):
+ """The same attach as handing peft the resolved string directly, as on main."""
+ from peft import LoraConfig
+
+ from soup_cli.utils.peft_wiring import resolve_lora_target_modules
+
+ modules, params, targets = _attach(arch, target_modules, moe_lora=False)
+ model = _build(arch)
+ string = resolve_lora_target_modules(model, target_modules)
+ direct = _peft_attach(
+ model, LoraConfig(r=4, lora_alpha=8, lora_dropout=0.0, target_modules=string)
+ )
+
+ assert type(targets) is str and targets == string
+ assert (set(modules), set(params)) == direct
+
+ def test_an_explicit_list_naming_the_router_is_honoured(self):
+ """A list is extended, never filtered: listing ``gate`` adapts the router."""
+ _, params, targets = _attach_uncached("qwen3_moe", ["q_proj", "gate"])
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert list(targets)[:2] == ["q_proj", "gate"]
+ assert {"model.layers.0.mlp.gate.weight", "model.layers.1.mlp.gate.weight"} <= params
+
+ def test_without_moe_lora_peft_still_adapts_the_routers(self):
+ _, qwen3_params, _ = _attach("qwen3_moe", "all-linear", moe_lora=False)
+ dbrx_modules, _, _ = _attach("dbrx", "all-linear", moe_lora=False)
+
+ assert {"model.layers.0.mlp.gate.weight", "model.layers.1.mlp.gate.weight"} <= (
+ qwen3_params
+ )
+ assert "transformer.blocks.0.ffn.router.layer" in dbrx_modules
+
+ def test_qwen4_exp_gets_back_every_linear_the_moe_list_dropped(self):
+ modules, _, targets = _attach("qwen4_exp", "auto", moe_lora=True)
+ moe_modules, _, _ = _attach("qwen4_exp", None, moe_lora=True)
+ leaves = {name.rsplit(".", 1)[-1] for name in modules}
+
+ assert targets == "all-linear"
+ assert len(modules) == 32 and len(moe_modules) == 10
+ assert {
+ "in_proj_qkv",
+ "in_proj_z",
+ "in_proj_a",
+ "in_proj_b",
+ "out_proj",
+ "index_qk_proj",
+ "input_mix_weight_down",
+ "input_mix_weight_up",
+ "block_inject_weight",
+ "key_proj",
+ "value_proj",
+ } <= leaves
+ assert "shared_expert_gate" not in leaves
+
+ def test_the_regex_reaches_peft_as_one_plain_string(self):
+ from soup_cli.utils.attach_preflight import trainer_lora_config
+
+ user_regex = r".*\.linear_attn\.in_proj_(qkv|z)"
+ cfg = SimpleNamespace(
+ task="sft", modality="text", training=_tcfg(user_regex, moe_lora=True)
+ )
+ peft_config, _ = trainer_lora_config(_build("qwen4_exp"), cfg)
+
+ assert type(peft_config.target_modules) is str
+ assert peft_config.target_modules == rf"(?:{user_regex})|(?:{_NAMES_REGEX})"
+ assert not peft_config.exclude_modules
+ assert sorted(peft_config.target_parameters) == _FUSED
+
+
+class TestThePerStringChoice:
+ def test_qwen4_exp_keeps_the_string_and_excludes_the_shared_gates(self):
+ """peft does not convert qwen4_exp: the string stays, ``exclude_modules`` acts."""
+ from soup_cli.utils.attach_preflight import trainer_lora_config
+
+ cfg = SimpleNamespace(task="sft", modality="text", training=_tcfg("auto"))
+ peft_config, targets = trainer_lora_config(_build("qwen4_exp"), cfg)
+
+ assert isinstance(targets, MoeLoraTargetString) and targets == "all-linear"
+ assert peft_config.target_modules == "all-linear"
+ assert set(peft_config.exclude_modules) == {
+ "model.layers.0.mlp.shared_expert_gate",
+ "model.layers.1.mlp.shared_expert_gate",
+ }
+
+ def test_exclude_modules_is_what_keeps_the_shared_gates_out(self):
+ """The same config, minus ``exclude_modules``, adapts both shared gates."""
+ from soup_cli.utils.attach_preflight import trainer_lora_config
+
+ cfg = SimpleNamespace(task="sft", modality="text", training=_tcfg("auto"))
+ peft_config, _ = trainer_lora_config(_build("qwen4_exp"), cfg)
+ peft_config.exclude_modules = None
+ modules, _ = _peft_attach(_build("qwen4_exp"), peft_config)
+
+ assert {
+ "model.layers.0.mlp.shared_expert_gate",
+ "model.layers.1.mlp.shared_expert_gate",
+ } <= modules
+
+ @pytest.mark.parametrize("arch", ["qwen3_moe", "deepseek_v3"])
+ def test_all_linear_on_a_family_peft_converts_becomes_a_list(self, arch):
+ _, _, targets = _attach(arch, "all-linear", moe_lora=True)
+
+ assert isinstance(targets, MoeLoraTargets)
+ assert "gate" not in targets
+
+ @pytest.mark.parametrize(
+ ("arch", "routers"),
+ [
+ ("qwen3_moe", {"model.layers.0.mlp.gate", "model.layers.1.mlp.gate"}),
+ ("deepseek_v3", {"model.layers.1.mlp.gate"}),
+ ],
+ )
+ def test_a_regex_naming_the_routers_stays_a_string_and_excludes_them(self, arch, routers):
+ """peft's resolution of a regex skips an excluded module, so no list is needed."""
+ regex = dict(_ROUTER_NAMING_CASES)[arch]
+ _, params, targets = _attach(arch, regex, moe_lora=True)
+
+ assert isinstance(targets, MoeLoraTargetString)
+ assert set(targets.exclude_modules) == routers
+ assert not {f"{router}.weight" for router in routers} & params
+
+ @pytest.mark.parametrize("arch", ["qwen3_moe", "deepseek_v3"])
+ def test_a_regex_reaching_no_router_stays_a_string(self, arch):
+ _, _, targets = _attach(arch, dict(_PLAIN_CASES[4:])[arch], moe_lora=True)
+
+ assert isinstance(targets, MoeLoraTargetString)
+ assert not targets.exclude_modules
+
+ def test_the_list_uses_leaf_names_in_model_order(self):
+ _, _, targets = _attach("qwen3_moe", "all-linear", moe_lora=True)
+
+ # The attention leaves in model order, then the MoE names it does not repeat
+ # (``get_moe_target_modules``'s fallback order on a fused-only model).
+ assert list(targets) == [
+ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj",
+ ]
+
+
+class TestTheAnnouncementOnRealModels:
+ @staticmethod
+ def _line(arch, target_modules):
+ from rich.console import Console
+
+ from soup_cli.utils.peft_wiring import resolve_lora_target_modules
+
+ model = _read_only(arch)
+ buf = StringIO()
+ resolve_moe_lora_targets(
+ model,
+ _tcfg(target_modules),
+ resolve_lora_target_modules(model, target_modules),
+ Console(file=buf, width=400),
+ )
+ return _plain(buf.getvalue())
+
+ def test_a_list_made_of_all_linear_is_counted(self):
+ assert self._line("qwen3_moe", "all-linear") == (
+ "ScatterMoE LoRA: targeting 'all-linear' as a list of 7 target names: every "
+ "linear layer but the output head, without the 2 MoE router/gate module(s), "
+ "plus the 7 MoE module patterns and 2 fused expert parameter(s): "
+ "mlp.experts.down_proj, mlp.experts.gate_up_proj"
+ )
+
+ def test_a_kept_regex_counts_the_routers_it_excludes(self):
+ assert self._line("qwen3_moe", dict(_ROUTER_NAMING_CASES)["qwen3_moe"]) == (
+ "ScatterMoE LoRA: targeting the target_modules regex or the 7 MoE module "
+ "patterns (one combined regex), excluding 2 MoE router/gate module(s) and 2 "
+ "fused expert parameter(s): mlp.experts.down_proj, mlp.experts.gate_up_proj"
+ )
+
+ def test_a_kept_string_counts_what_it_excludes(self):
+ assert self._line("qwen4_exp", "auto") == (
+ "ScatterMoE LoRA: keeping target_modules 'all-linear' (it already covers the 7 "
+ "MoE module patterns), excluding 2 MoE router/gate module(s) and adding 2 fused "
+ "expert parameter(s): mlp.experts.down_proj, mlp.experts.gate_up_proj"
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Layer streaming hands its resolved targets to the same helper (#2072) #
+# --------------------------------------------------------------------------- #
+
+
+class TestLayerStreamingTakesTheSamePath:
+ """The streamed LoRA config attaches what the resident one does, string or list.
+
+ Driven through the shared streaming harness of ``test_stream_moe_lora_targets``:
+ the setup's meta-skeleton probe is the tiny real model, so the resolver and this
+ helper see a real architecture.
+ """
+
+ @staticmethod
+ def _resident(build, lora):
+ from soup_cli.utils.attach_preflight import trainer_lora_config
+
+ cfg = SimpleNamespace(
+ task="sft", modality="text", training=SimpleNamespace(moe_lora=True, lora=lora)
+ )
+ peft_config, _ = trainer_lora_config(build(), cfg)
+ return _peft_attach(build(), peft_config)
+
+ @pytest.mark.parametrize(
+ ("label", "real_helpers", "kept"),
+ [
+ ("qwen3_5_moe", True, True),
+ # The harness swaps peft's ``LoraConfig`` for a stub, which peft's own
+ # conversion cannot run on: the helper gets no answer, and fails closed to
+ # a list.
+ ("qwen3_5_moe", False, False),
+ ("deepseek_v3-q_lora_rank-int", True, False),
+ ],
+ ids=["qwen3_5_moe-kept-string", "qwen3_5_moe-no-peft-helpers-list", "deepseek_v3-list"],
+ )
+ def test_all_linear_streams_as_it_attaches_resident(
+ self, tmp_path, monkeypatch, label, real_helpers, kept
+ ):
+ pytest.importorskip("torch")
+ pytest.importorskip("peft")
+ from tests import test_stream_moe_lora_targets as harness
+
+ if real_helpers:
+ # Bound to the real peft now, before the harness stubs it.
+ expand = moe_mod._peft_all_linear_expander()
+ convert = moe_mod._peft_config_converter()
+ monkeypatch.setattr(moe_mod, "_peft_all_linear_expander", lambda: expand)
+ monkeypatch.setattr(moe_mod, "_peft_config_converter", lambda: convert)
+ stream_arch, build = harness._BASES[label]
+ lora = harness._lora("all-linear")
+ streamed, _probes = harness._streamed(tmp_path, monkeypatch, stream_arch, build(), lora)
+ kwargs = dict(vars(streamed))
+ monkeypatch.undo() # the harness stubs peft; attach with the real one
+ from peft import LoraConfig
+
+ streamed_set = _peft_attach(build(), LoraConfig(**kwargs))
+ resident_set = self._resident(build, lora)
+ gates = moe_mod.find_moe_gates(build())
+ modules, params = streamed_set
+
+ assert gates
+ assert streamed_set == resident_set
+ assert not [name for name in modules if moe_mod._in_a_gate(name, gates)]
+ assert not [param for param in params if moe_mod._in_a_gate(param, gates)]
+ assert any(".mlp.experts." in param for param in params)
+ if kept:
+ assert kwargs["target_modules"] == "all-linear"
+ assert kwargs["exclude_modules"]
+ assert all(moe_mod._in_a_gate(name, gates) for name in kwargs["exclude_modules"])
+ else:
+ assert isinstance(kwargs["target_modules"], list)
+ assert "gate" not in kwargs["target_modules"]
diff --git a/tests/test_stream_moe_lora_targets.py b/tests/test_stream_moe_lora_targets.py
index 26206bc4..843b82f0 100644
--- a/tests/test_stream_moe_lora_targets.py
+++ b/tests/test_stream_moe_lora_targets.py
@@ -13,8 +13,8 @@ REPLACED the resolved list with the helper's answer. So under ``stream_layers``:
The replace was never a decision about streaming: #426 copied SFT's block from
before #1590, when ``auto`` still meant ``None`` and there was no list to keep.
-(The helper keeps LIST targets only; a string target such as qwen4_exp's
-``"all-linear"`` is replaced by the MoE names on both paths, as before.)
+(A string target such as qwen4_exp's ``"all-linear"`` reaches the same helper on both
+paths too; ``tests/test_moe_lora_string_targets.py`` covers it, streaming included.)
These tests drive the real streaming setup through the shared harness, with real
tiny models as the probe, and compare what it builds with what the resident