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): refuse moe_lora with lora.use_vera on a fused-expert MoE (#1197) (#1723)

Srinivasan R46fc7c0d7f24
diff --git a/changelog.d/0.75.1/1723.fixed.md b/changelog.d/0.75.1/1723.fixed.md
new file mode 100644
index 00000000..e41609d6
--- /dev/null
+++ b/changelog.d/0.75.1/1723.fixed.md
@@ -0,0 +1 @@
+- **`training.moe_lora: true` with `lora.use_vera: true` is refused on a fused-expert MoE (#1197 by @Srinivasan8888 in #1723).** VeRA wraps `nn.Linear` modules only and has no `target_parameters` path, so on a transformers-5 MoE whose routed experts are 3-D tensors (Qwen3-MoE, Qwen2-MoE, Mixtral, MiniMax) the flag adapted the attention projections exactly as VeRA without it did, while printing the ScatterMoE targeting line. The combination now stops at setup, before the dropout rule, naming both flags, the fused parameters and the two ways out (`use_vera: false` to adapt the experts with LoRA, or drop `moe_lora`). A dense base and a checkpoint that keeps one `nn.Linear` per expert are not refused.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 73341940..f5c86179 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -1294,7 +1294,7 @@ Both reject silently-no-op combinations: setting either flag without `moe_lora=t
| `mixtral` | **no — attention-only** | yes |
| `kimi_k2` | **not measured** (no stand-in builds here) | not measured |
-`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.
+`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.
**`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/utils/moe.py b/src/soup_cli/utils/moe.py
index 3c9e651b..f781a8f9 100644
--- a/src/soup_cli/utils/moe.py
+++ b/src/soup_cli/utils/moe.py
@@ -244,6 +244,27 @@ def _refuse_dropout_on_fused_experts(model, tcfg, target_modules, fused_paramete
)
+def _refuse_vera_on_fused_experts(tcfg, fused_parameters) -> None:
+ """``moe_lora`` + ``lora.use_vera`` can reach no fused expert (#1197).
+
+ VeRA (peft ``VeraConfig``) wraps ``nn.Linear`` modules only and has no
+ ``target_parameters`` path, so on a model whose routed experts are fused 3-D
+ tensors the flag would adapt attention (and a shared expert) exactly as VeRA
+ without it, while announcing expert targets. Refused on every such family,
+ Mixtral and MiniMax included, as ruled on the issue; a checkpoint with one
+ ``nn.Linear`` per expert is not refused, VeRA wraps those.
+ """
+ if not fused_parameters or not getattr(getattr(tcfg, "lora", None), "use_vera", False):
+ return
+ raise ValueError(
+ "training.moe_lora=true does nothing with lora.use_vera: true on this model: its "
+ f"routed experts are fused 3-D parameters ({', '.join(fused_parameters)}), and VeRA "
+ "wraps nn.Linear modules only, so the experts would get no adapter and only the "
+ "attention projections would train. Set lora.use_vera: false to adapt the experts "
+ "with LoRA, or remove moe_lora to keep VeRA on the attention projections."
+ )
+
+
def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
"""Return MoE-aware LoRA targets when ``training.moe_lora`` asks for them.
@@ -266,10 +287,11 @@ def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
(#1421: Mixtral, MiniMax, Qwen2-MoE and Qwen3.5-MoE got attention-only LoRA).
Raises:
- ValueError: fused expert parameters will be targeted AND ``lora.dropout``
- is non-zero. peft adapts those through ``lora.ParamWrapper``, which
- refuses any dropout; letting the attach proceed gets the user peft's
- message with no mention of the flag that caused it.
+ 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.
"""
if not getattr(tcfg, "moe_lora", False):
return target_modules
@@ -281,6 +303,7 @@ def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
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)
+ _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"
diff --git a/tests/test_issue1197_vera_moe_lora.py b/tests/test_issue1197_vera_moe_lora.py
new file mode 100644
index 00000000..0c5e1776
--- /dev/null
+++ b/tests/test_issue1197_vera_moe_lora.py
@@ -0,0 +1,189 @@
+"""#1197: ``moe_lora`` with ``lora.use_vera`` is refused on a fused-expert MoE.
+
+VeRA (peft ``VeraConfig``) wraps ``nn.Linear`` modules only and has no
+``target_parameters`` path, so on a transformers-5 MoE, whose routed experts are 3-D
+tensors on one ``experts`` module, ``moe_lora: true`` + ``use_vera: true`` adapted the
+attention projections (and a shared expert) exactly as VeRA without the flag did, while
+printing the ScatterMoE line. The maintainer's ruling: refuse when VeRA would wrap no
+routed expert, on every such family, Mixtral and MiniMax included. A checkpoint that
+keeps one ``nn.Linear`` per expert is not refused: VeRA wraps those.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+torch = pytest.importorskip("torch")
+transformers = pytest.importorskip("transformers")
+pytest.importorskip("peft")
+
+from soup_cli.utils.moe import resolve_moe_lora_targets # noqa: E402
+from soup_cli.utils.peft_wiring import build_lora_config, build_peft_config_spec # noqa: E402
+
+_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,
+)
+_FUSED = ("qwen3_moe", "mixtral", "minimax", "qwen2_moe")
+
+
+def _model(arch: str):
+ tf = transformers
+ if arch == "qwen3_moe":
+ return tf.Qwen3MoeForCausalLM(tf.Qwen3MoeConfig(
+ **_SMALL, num_experts=4, num_experts_per_tok=2, moe_intermediate_size=16))
+ if arch == "mixtral":
+ return tf.MixtralForCausalLM(tf.MixtralConfig(
+ **_SMALL, num_local_experts=4, num_experts_per_tok=2))
+ if arch == "minimax":
+ return tf.MiniMaxForCausalLM(tf.MiniMaxConfig(
+ **_SMALL, num_local_experts=4, num_experts_per_tok=2))
+ if arch == "qwen2_moe":
+ return tf.Qwen2MoeForCausalLM(tf.Qwen2MoeConfig(
+ **_SMALL, num_experts=4, num_experts_per_tok=2, moe_intermediate_size=16,
+ shared_expert_intermediate_size=16))
+ if arch == "dense":
+ return tf.LlamaForCausalLM(tf.LlamaConfig(**_SMALL))
+ raise KeyError(arch)
+
+
+class _PerExpertLinearMoE(torch.nn.Module):
+ """The transformers-4 layout: one ``nn.Linear`` per expert, which VeRA can wrap."""
+
+ def __init__(self):
+ super().__init__()
+ self.config = SimpleNamespace(model_type="mixtral", num_local_experts=2)
+ experts = 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(2)
+ ])
+ self.layers = torch.nn.ModuleList([torch.nn.ModuleDict({
+ "self_attn": torch.nn.ModuleDict(
+ {name: torch.nn.Linear(8, 8) for name in ("q_proj", "v_proj")}),
+ "block_sparse_moe": torch.nn.ModuleDict(
+ {"gate": torch.nn.Linear(8, 2), "experts": experts}),
+ })])
+
+
+def _tcfg(*, moe_lora: bool = True, use_vera: bool = True, dropout: float = 0.0):
+ return SimpleNamespace(
+ moe_lora=moe_lora,
+ 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="auto", target_parameters=None,
+ ),
+ )
+
+
+def _tuner_layers(peft_model) -> list[str]:
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ return [n for n, m in peft_model.named_modules() if isinstance(m, BaseTunerLayer)]
+
+
+class TestTheFactBehindTheRefusal:
+ def test_vera_cannot_reach_a_fused_expert(self):
+ """Measured, not assumed: VeRA over the module names ``moe_lora`` resolves
+ attaches to attention only on a fused Qwen3-MoE, 0 layers on ``experts``."""
+ from peft import get_peft_model
+
+ model = _model("qwen3_moe")
+ targets = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ config = build_lora_config(_tcfg().lora, target_modules=targets, task_type="CAUSAL_LM")
+ assert type(config).__name__ == "VeraConfig"
+ attached = get_peft_model(model, config)
+ layers = _tuner_layers(attached)
+ assert len(layers) == 8 # q/k/v/o on two layers
+ assert not [n for n in layers if ".experts" in n]
+
+ def test_the_vera_spec_has_no_target_parameters(self):
+ """The only route to a fused parameter is ``target_parameters``, and peft's
+ ``VeraConfig`` has none, so a carried list could not help VeRA."""
+ spec = build_peft_config_spec(
+ _tcfg().lora, target_modules=["q_proj"], task_type="CAUSAL_LM",
+ target_parameters=["mlp.experts.gate_up_proj"],
+ )
+ assert spec["peft_cls"] == "VeraConfig"
+ assert "target_parameters" not in spec["init_kwargs"]
+
+
+class TestVeraOnFusedExpertsIsRefused:
+ @pytest.mark.parametrize("arch", _FUSED)
+ def test_refused_naming_both_flags_and_the_parameters(self, arch):
+ with pytest.raises(ValueError) as excinfo:
+ resolve_moe_lora_targets(_model(arch), _tcfg(), ["q_proj"])
+ message = str(excinfo.value)
+ assert "training.moe_lora=true" in message and "lora.use_vera" in message
+ assert "mlp.experts.gate_up_proj" in message and "mlp.experts.down_proj" in message
+ assert "nn.Linear" in message
+ assert "use_vera: false" in message
+ assert "remove moe_lora" in message
+
+ def test_refused_before_the_dropout_rule_speaks(self):
+ """With both problems present the VeRA one is named: fixing dropout alone
+ would not make the flag do anything."""
+ with pytest.raises(ValueError, match="use_vera"):
+ resolve_moe_lora_targets(_model("mixtral"), _tcfg(dropout=0.05), ["q_proj"])
+
+ def test_through_a_real_trainer_setup(self, monkeypatch):
+ """The refusal reaches ``DPOTrainerWrapper._setup_transformers`` with only the
+ loaders stubbed (the maintainer's measurement on #1197 used this path)."""
+ pytest.importorskip("trl")
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.dpo import DPOTrainerWrapper
+
+ tokenizer = SimpleNamespace(
+ pad_token=None, eos_token="</s>", pad_token_id=0, chat_template="{{ x }}"
+ )
+ monkeypatch.setattr(
+ transformers.AutoTokenizer, "from_pretrained", lambda *a, **k: tokenizer
+ )
+ monkeypatch.setattr(
+ transformers.AutoModelForCausalLM, "from_pretrained",
+ lambda *a, **k: _model("qwen3_moe"),
+ )
+ cfg = load_config_from_string(
+ "base: org/tiny-moe\ntask: dpo\nbackend: transformers\n"
+ "data:\n train: x.jsonl\n format: dpo\n"
+ "training:\n quantization: none\n moe_lora: true\n"
+ " lora:\n r: 4\n alpha: 8\n dropout: 0.0\n use_vera: true\n"
+ )
+ wrapper = object.__new__(DPOTrainerWrapper)
+ wrapper.config = cfg
+ wrapper.device = "cpu"
+ wrapper.trust_remote_code = False
+ wrapper._trust_remote_code = False
+ wrapper.model = None
+ wrapper.tokenizer = None
+ with pytest.raises(ValueError, match="lora.use_vera"):
+ wrapper._setup_transformers(cfg, cfg.training)
+
+
+class TestWhatIsNotRefused:
+ @pytest.mark.parametrize("arch", _FUSED)
+ def test_lora_on_the_same_model_still_reaches_the_experts(self, arch):
+ """The control that gives the message its way out: with ``use_vera: false``
+ the fused parameters travel as ``target_parameters`` (#1590)."""
+ targets = resolve_moe_lora_targets(_model(arch), _tcfg(use_vera=False), ["q_proj"])
+ assert targets.target_parameters == ["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]
+
+ def test_vera_without_the_flag_is_untouched(self):
+ assert resolve_moe_lora_targets(_model("qwen3_moe"), _tcfg(moe_lora=False), ["q_proj"]) == [
+ "q_proj"
+ ]
+
+ def test_vera_on_a_per_expert_linear_layout_is_not_refused(self):
+ """VeRA wraps those experts, so the flag does what it says there."""
+ targets = resolve_moe_lora_targets(_PerExpertLinearMoE(), _tcfg(), ["q_proj"])
+ assert {"gate_proj", "up_proj", "down_proj"} <= set(targets)
+ assert not targets.target_parameters
+
+ def test_vera_on_a_dense_model_is_the_documented_no_op(self):
+ assert resolve_moe_lora_targets(_model("dense"), _tcfg(), ["q_proj"]) == ["q_proj"]