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): reach fused experts with target_parameters and refuse moe_expert_quant on them (#1421) (#1590)

Srinivasan R83f98b204729
diff --git a/changelog.d/0.75.1/1590.fixed.md b/changelog.d/0.75.1/1590.fixed.md
new file mode 100644
index 00000000..e8225172
--- /dev/null
+++ b/changelog.d/0.75.1/1590.fixed.md
@@ -0,0 +1,2 @@
+- `training.moe_lora: true` now adapts the routed experts of every fused-expert MoE on transformers 5 (by module names alone Mixtral and MiniMax adapted attention only, Qwen2-MoE attention plus its shared expert, Qwen3.5-MoE the shared expert only; Qwen3-MoE, OLMoE, DeepSeek-V3 and GLM-4 were reached only through peft's own name conversion): the fused `mlp.experts.gate_up_proj` / `down_proj` tensors are handed to peft as `target_parameters`, the module targets `auto` resolved are kept beside them (an explicit `lora.target_modules` list is kept too, where `moe_lora` used to replace it), and the console line names the parameters. Because peft's `ParamWrapper` refuses dropout, `moe_lora` with a non-zero `lora.dropout` is now refused on Mixtral and MiniMax too (#1421 by @Srinivasan8888 in #1590).
+- `training.moe_expert_quant` on a fused-expert model is refused at setup, naming the architecture and the fused parameters, instead of printing `applied to 0 expert Linear block(s)` and training in full precision; matching no expert at all is refused the same way (#1421 by @Srinivasan8888 in #1590).
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index eb497482..c8d25c31 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -1224,7 +1224,14 @@ For fused-MoE models trained with `moe_lora: true`, two live toggles:
(QLoRA-on-experts), so PEFT attaches its adapters to the quantized base. The
source weights are genuinely carried into the quantized layer (validated
dequant error 0.0155 vs source on an RTX 3050). CUDA + bitsandbytes are
- required — a friendly `RuntimeError` fires on CPU / without bnb.
+ required — a friendly `RuntimeError` fires on CPU / without bnb. It needs the
+ one-`nn.Linear`-per-expert layout: on a transformers-5 model whose routed
+ experts are fused 3-D parameters (`mlp.experts.gate_up_proj`, which is every
+ in-library MoE family on the declared stack) there is no expert `nn.Linear` to
+ wrap, and the run is refused at setup naming the architecture and the fused
+ parameters, before the CUDA check (#1421; it used to print `applied to 0
+ expert Linear block(s)` and train in full precision). Matching no expert at all
+ is refused the same way.
- `training.train_router_only: true` — freeze every expert parameter and train
only the gating router (applied after LoRA, on the final parameter set).
@@ -1240,20 +1247,23 @@ Both reject silently-no-op combinations: setting either flag without `moe_lora=t
**`moe_lora` on the remaining LoRA tasks (#1099).** #798 left it loading but unread on `ipo`, `bco`, `reward_model`, `ppo` and `embedding`, and `online_dpo` had the same gap. All six build their adapter through the same `build_lora_config` path, so they were wired to the same helper rather than refused. On `embedding` it applies only with `lora.r >= 1`; at `r: 0` that trainer full-fine-tunes and builds no adapter for the flag to select. #1151 closed the remainder: `distill` and `unlearn` build their adapter the same way and are wired to the same helper, and so is `classifier` / `reranker` / `cross_encoder` (one trainer) on its opt-in adapter path. Without `classifier_lora: true` and `lora.r > 0` that trainer full-fine-tunes and builds no adapter, so there the flag is refused at config load; `asr`, which trains only Whisper (no experts), `moe_lora_routing`, which builds no LoRA adapter, and `prm`, which fine-tunes every base parameter, refuse the flag at config load. Two paths refuse it whatever the task: `task: sft` with `modality: vision` or `audio`, whose setup builds its adapter without the MoE step, and `backend: unsloth`. On unsloth the reason depends on the task (#1264): the thirteen tasks with an unsloth setup attach its fixed attention list and never read the flag, while the rest have no unsloth setup at all, so there it is the backend that goes unapplied. Both messages point to `backend: transformers`, where the flag is read. The other `moe_lora` refusals in the same check come first, so `asr`, `prm`, `moe_lora_routing` and SFT vision/audio get one refusal whatever the backend. Every path now either reads `moe_lora` or refuses it, except `backend: mlx`, where it loads and `soup doctor --config` reports it as ignored; a source ratchet keeps a new adapter-building trainer from missing it. `train_router_only` and `moe_expert_quant` require `moe_lora: true`, so on `backend: unsloth` they now fail to load with the same message. `preference` is covered through the trainers it dispatches to, and `tts` through the SFT trainer it subclasses.
-**`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.
+**`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` does not reach every MoE family (measured, v0.75.0).** `get_moe_target_modules` picks module names, and whether peft turns those into adapters on the fused expert parameters depends on the architecture. On tiny stand-ins with transformers 5.16.1 / peft 0.20.0:
+**`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 (an `auto` list is kept, so Qwen3.5's `in_proj_qkv` / `out_proj` stay adapted; not under `stream_layers`, whose setup resolves the targets on a meta skeleton and replaces the list). 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 | expert adapters attach | recipes |
+| family | module names alone (before #1421) | trainer path (now) |
|---|---|---|
-| `qwen3_moe` | yes | 11 |
-| `deepseek_v3` | yes | 8 |
-| `glm4_moe` | yes | 3 |
-| `minimax` | **no — attention-only** | 0 |
-| `mixtral` | **no — attention-only** | — |
-| `kimi_k2` | **not measured** (no stand-in builds here) | 7 |
-
-So `minimax-m3-sft` 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). Neither could have reached the experts anyway: peft has no v4→v5 conversion mapping for the MiniMax model types, so their experts are never targeted and the attach succeeds quietly. Extending target resolution per architecture is #1070. 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.
+| `qwen3_moe` | yes | yes |
+| `deepseek_v3` | yes | yes |
+| `glm4_moe` | yes | yes |
+| `olmoe` | yes | yes |
+| `qwen2_moe` | **no — attention + shared expert** | yes |
+| `qwen3_5_moe_text` | **no — shared expert only** | yes |
+| `minimax` | **no — attention-only** | yes |
+| `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.
**`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 801dacca..3c9e651b 100644
--- a/src/soup_cli/utils/moe.py
+++ b/src/soup_cli/utils/moe.py
@@ -114,6 +114,53 @@ def get_moe_target_modules(model) -> Optional[list[str]]:
return targets
+def find_fused_expert_parameters(model) -> list[str]:
+ """Fused routed-expert tensors, as the suffixes peft's ``target_parameters`` match.
+
+ On transformers 5 an MoE layer holds all its experts as 3-D parameters on one
+ module (``mlp.experts.gate_up_proj`` of shape ``(experts, in, out)``), not as
+ one ``nn.Linear`` per expert, so module-name discovery cannot reach them
+ (#1421). This looks at the parameters: a 3-D tensor whose module path has an
+ ``experts`` component. The suffix starts at the component before ``experts``
+ (``mlp.experts.gate_up_proj``, ``block_sparse_moe.experts.down_proj``), which
+ is what peft matches with ``key.endswith("." + target)``. A shared expert's
+ ``gate_proj.weight`` is 2-D and is not one of these.
+
+ A stand-in with no parameters (a namespace or a mock) yields ``[]``.
+ """
+ try:
+ named = list(model.named_parameters())
+ except Exception: # noqa: BLE001 - a stand-in for a model has no parameters
+ return []
+ found = set()
+ for name, param in named:
+ if getattr(param, "ndim", 0) != 3 or not isinstance(name, str):
+ continue
+ parts = name.split(".")
+ expert_indices = [i for i, part in enumerate(parts[:-1]) if "experts" in part.lower()]
+ if not expert_indices:
+ continue
+ start = max(expert_indices[-1] - 1, 0)
+ found.add(".".join(parts[start:]))
+ return sorted(found)
+
+
+class MoeLoraTargets(list):
+ """The module targets ``moe_lora`` resolved, plus the fused expert parameters.
+
+ A list, so every trainer's ``target_modules`` plumbing is unchanged; the
+ ``target_parameters`` ride along and :func:`peft_wiring.build_lora_config`
+ merges them into the ``LoraConfig`` -- the one call every trainer makes before
+ ``get_peft_model``, the same route :class:`peft_wiring.UnmappedTargets` takes.
+ """
+
+ __slots__ = ("target_parameters",)
+
+ def __init__(self, modules, target_parameters=()):
+ super().__init__(modules)
+ self.target_parameters = list(target_parameters)
+
+
def peft_routes_lora_to_fused_params(model, target_modules) -> bool:
"""Will peft turn THESE targets into ``target_parameters`` on THIS model?
@@ -173,16 +220,19 @@ def peft_routes_lora_to_fused_params(model, target_modules) -> bool:
return bool(getattr(probe, "target_parameters", None))
-def _refuse_dropout_on_fused_experts(model, tcfg, target_modules) -> None:
+def _refuse_dropout_on_fused_experts(model, tcfg, target_modules, fused_parameters=()) -> None:
"""Stop before peft does, naming the flag that caused it (#798).
- Only when peft would really route these targets onto fused parameters. The
- first version of this check asked the model whether fused expert parameters
- existed anywhere, which refused Mixtral and MiniMax configs that peft
- accepts, with a message describing a mechanism that does not apply to them.
+ Only when fused parameters will really be targeted: the ones Soup now names
+ itself (#1421), or the ones peft's own name conversion rewrites the module
+ targets into. Until #1421 Mixtral and MiniMax were not refused, because
+ nothing reached their experts; now that ``moe_lora`` targets them, peft's
+ ``ParamWrapper`` refuses dropout there too.
"""
dropout = getattr(getattr(tcfg, "lora", None), "dropout", 0) or 0
- if dropout == 0 or not peft_routes_lora_to_fused_params(model, target_modules):
+ if dropout == 0:
+ return
+ if not fused_parameters and not peft_routes_lora_to_fused_params(model, target_modules):
return
raise ValueError(
f"training.moe_lora=true needs training.lora.dropout: 0.0 on this model "
@@ -207,13 +257,19 @@ def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
Returns ``target_modules`` unchanged when the flag is off, the model is not
MoE, or no expert modules are found, so a non-MoE base is untouched.
+ Otherwise returns a :class:`MoeLoraTargets`: the module patterns already
+ resolved (an ``auto`` list is kept, so Qwen3.5's ``in_proj_qkv`` /
+ ``out_proj`` survive) plus the attention and expert-FFN names, and, on a
+ transformers-5 model whose routed experts are fused 3-D tensors, those
+ tensors as ``target_parameters`` for peft -- the only way to adapt them, and
+ 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).
+
Raises:
- ValueError: peft would route these targets onto fused expert parameters
- AND ``lora.dropout`` is non-zero. It 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. Architectures peft does not route this way (Mixtral,
- MiniMax) are NOT refused -- they attach fine, and adapt no experts.
+ 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.
"""
if not getattr(tcfg, "moe_lora", False):
return target_modules
@@ -222,12 +278,16 @@ def resolve_moe_lora_targets(model, tcfg, target_modules, console=None):
moe_targets = get_moe_target_modules(model)
if not moe_targets:
return target_modules
- _refuse_dropout_on_fused_experts(model, tcfg, moe_targets)
+ 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_dropout_on_fused_experts(model, tcfg, modules, fused)
if console is not None:
- console.print(
- f"[green]ScatterMoE LoRA:[/] targeting {len(moe_targets)} module patterns"
- )
- return moe_targets
+ 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)
+ return MoeLoraTargets(modules, fused)
def get_moe_info(model) -> dict:
diff --git a/src/soup_cli/utils/moe_quant.py b/src/soup_cli/utils/moe_quant.py
index 6b0668de..a370f409 100644
--- a/src/soup_cli/utils/moe_quant.py
+++ b/src/soup_cli/utils/moe_quant.py
@@ -165,7 +165,15 @@ def _is_router_param(name: str) -> bool:
def _find_expert_linears(model: object) -> list[tuple[str, object]]:
- """Return ``(name, module)`` pairs for every fused-MoE expert ``nn.Linear``.
+ """Return ``(name, module)`` pairs for every MoE expert block.
+
+ Two layouts (#1421): one ``nn.Linear`` per expert under ``...experts.N.<proj>``
+ (the transformers-4 layout, what the quant path can wrap), and the
+ transformers-5 fused block, one module under ``...experts`` whose own
+ parameters are 3-D tensors (``gate_up_proj`` / ``down_proj``). The fused
+ block is returned as itself, not as a Linear, so the caller can tell the
+ two apart with ``isinstance(module, nn.Linear)``; before #1421 it was
+ invisible here and ``moe_expert_quant`` reported success on nothing.
Pure ``nn.Module`` walk — no bitsandbytes / CUDA. Already-quantized
bitsandbytes Linears (subclasses of ``nn.Linear``) are skipped so an
@@ -178,13 +186,18 @@ def _find_expert_linears(model: object) -> list[tuple[str, object]]:
found: list[tuple[str, object]] = []
for name, module in model.named_modules():
- if _EXPERT_NAME_MARKER not in name or not isinstance(module, nn.Linear):
- continue
- if type(module).__name__ in _BNB_LINEAR_CLASS_NAMES:
- continue
- if getattr(module, "base_layer", None) is not None:
- continue
- found.append((name, module))
+ if isinstance(module, nn.Linear):
+ if _EXPERT_NAME_MARKER not in name:
+ continue
+ if type(module).__name__ in _BNB_LINEAR_CLASS_NAMES:
+ continue
+ if getattr(module, "base_layer", None) is not None:
+ continue
+ found.append((name, module))
+ elif "experts" in name.rsplit(".", 1)[-1].lower() and any(
+ getattr(p, "ndim", 0) == 3 for _, p in module.named_parameters(recurse=False)
+ ):
+ found.append((name, module))
return found
@@ -209,6 +222,31 @@ def freeze_experts_train_router(model: object) -> tuple[int, int]:
return experts_frozen, router_trainable
+def _refuse_fused_experts(model: object, quant_format: str) -> None:
+ """A transformers-5 MoE keeps its routed experts as fused 3-D tensors (#1421).
+
+ bitsandbytes quantizes ``nn.Linear`` modules, and a fused ``experts`` block has
+ none, so there is nothing this flag can quantize: say so by name instead of
+ returning 0 and letting the caller print a success line. Checked before the
+ bitsandbytes / CUDA gate, so a CPU host gets the real reason too.
+ """
+ from soup_cli.utils.moe import find_fused_expert_parameters
+
+ fused = find_fused_expert_parameters(model)
+ if not fused:
+ return
+ model_type = getattr(getattr(model, "config", None), "model_type", None) or type(
+ model
+ ).__name__
+ raise ValueError(
+ f"training.moe_expert_quant: {quant_format} cannot quantize this model: "
+ f"{model_type} keeps its routed experts as fused 3-D parameters "
+ f"({', '.join(fused)}), not as one nn.Linear per expert, and bitsandbytes "
+ f"quantizes nn.Linear only. Remove training.moe_expert_quant (the experts "
+ f"stay in the model's load dtype); training.moe_lora still adapts them."
+ )
+
+
def apply_moe_expert_quant(model: object, quant_format: str) -> int:
"""Quantize the fused-MoE expert ``nn.Linear`` blocks in ``model``.
@@ -221,8 +259,14 @@ def apply_moe_expert_quant(model: object, quant_format: str) -> int:
``RuntimeError`` fires (the real per-expert quant validation stays
hardware-gated). Returns the number of expert Linears quantized.
"""
+ import torch.nn as nn
+
canonical = validate_moe_expert_quant(quant_format)
- expert_linears = _find_expert_linears(model)
+ found = _find_expert_linears(model)
+ if any(not isinstance(module, nn.Linear) for _, module in found):
+ # A fused block was found (#1421): nothing here is a Linear to wrap.
+ _refuse_fused_experts(model, canonical)
+ expert_linears = [(name, module) for name, module in found if isinstance(module, nn.Linear)]
if not expert_linears:
return 0
@@ -288,6 +332,16 @@ def apply_moe_expert_quant_if_configured(
if fmt is None:
return
count = apply_moe_expert_quant(model, fmt)
+ if count == 0:
+ # #1421: "applied to 0 expert Linear block(s)" was printed in green.
+ model_type = getattr(getattr(model, "config", None), "model_type", None) or type(
+ model
+ ).__name__
+ raise ValueError(
+ f"training.moe_expert_quant: {fmt} matched no expert nn.Linear in "
+ f"{model_type}, so nothing was quantized. Remove training.moe_expert_quant, "
+ f"or check that the model's experts live under an '.experts.' module path."
+ )
if console is not None:
console.print(
f"[green]MoE expert quant:[/] {fmt} applied to {count} "
diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.py
index c54e1627..892fd0ee 100644
--- a/src/soup_cli/utils/peft_wiring.py
+++ b/src/soup_cli/utils/peft_wiring.py
@@ -468,6 +468,22 @@ 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,
+ 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.
+ """
+ extra = getattr(target_modules, "target_parameters", None)
+ if not extra:
+ return target_parameters
+ merged = list(target_parameters) if isinstance(target_parameters, (list, tuple)) else []
+ merged.extend(name for name in extra if name not in merged)
+ return merged
+
+
def _settle_unmapped(target_modules: Any, target_parameters: Any) -> Any:
"""Refuse an unmappable ``auto`` here, where the final targets are known.
@@ -507,6 +523,7 @@ def build_lora_config(
"""
import peft
+ target_parameters = _with_moe_parameters(target_modules, target_parameters)
target_modules = _settle_unmapped(target_modules, target_parameters)
spec = build_peft_config_spec(
lora_cfg,
diff --git a/tests/test_issue1421_fused_moe_experts.py b/tests/test_issue1421_fused_moe_experts.py
new file mode 100644
index 00000000..70c941bc
--- /dev/null
+++ b/tests/test_issue1421_fused_moe_experts.py
@@ -0,0 +1,425 @@
+"""#1421: fused MoE experts are found by their parameters, not by per-expert module names.
+
+On transformers 5 an MoE layer keeps all its experts as two 3-D parameters on one
+module (``mlp.experts.gate_up_proj`` / ``down_proj``). Soup's discovery looked for one
+``nn.Linear`` per expert, so ``moe_lora`` adapted attention only on Mixtral, MiniMax,
+Qwen2-MoE and Qwen3.5-MoE (the experts were reached only where peft's own name
+conversion happened to rewrite the module names), and ``moe_expert_quant`` printed
+``applied to 0 expert Linear block(s)`` as a success line.
+
+Now ``resolve_moe_lora_targets`` hands the fused parameters to peft as
+``target_parameters``, carried on the targets it returns and merged by
+``build_lora_config`` (the one call every trainer makes before ``get_peft_model``), and
+``moe_expert_quant`` refuses a fused-expert model by name.
+"""
+
+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 import moe as moe_mod # noqa: E402
+from soup_cli.utils.moe import ( # noqa: E402
+ find_fused_expert_parameters,
+ get_moe_target_modules,
+ resolve_moe_lora_targets,
+)
+from soup_cli.utils.moe_quant import ( # noqa: E402
+ apply_moe_expert_quant,
+ apply_moe_expert_quant_if_configured,
+)
+from soup_cli.utils.peft_wiring import ( # noqa: E402
+ build_lora_config,
+ resolve_lora_target_modules,
+)
+
+_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,
+)
+_ROUTED = dict(num_experts=4, num_experts_per_tok=2, moe_intermediate_size=16)
+
+_FUSED_FAMILIES = ("mixtral", "minimax", "qwen2_moe", "qwen3_5_moe", "qwen3_moe", "olmoe")
+#: The families the issue measured at 0 routed-expert adapters on ``main``.
+_WERE_ATTENTION_ONLY = ("mixtral", "minimax", "qwen2_moe", "qwen3_5_moe")
+
+
+def _model(arch: str):
+ tf = transformers
+ 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, **_ROUTED, shared_expert_intermediate_size=16)
+ )
+ if arch == "qwen3_5_moe":
+ return tf.Qwen3_5MoeForCausalLM(
+ tf.Qwen3_5MoeTextConfig(**_SMALL, **_ROUTED, shared_expert_intermediate_size=16)
+ )
+ if arch == "qwen3_moe":
+ return tf.Qwen3MoeForCausalLM(tf.Qwen3MoeConfig(**_SMALL, **_ROUTED))
+ if arch == "olmoe":
+ return tf.OlmoeForCausalLM(tf.OlmoeConfig(**_SMALL, **_ROUTED))
+ 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 under ``experts.N``."""
+
+ 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, dropout: float = 0.0, moe_expert_quant=None):
+ return SimpleNamespace(
+ moe_lora=moe_lora,
+ moe_expert_quant=moe_expert_quant,
+ lora=SimpleNamespace(
+ r=4,
+ alpha=8,
+ dropout=dropout,
+ use_dora=False,
+ use_rslora=False,
+ use_vera=False,
+ rank_pattern=None,
+ alpha_pattern=None,
+ init_strategy="random",
+ target_modules="auto",
+ target_parameters=None,
+ ),
+ )
+
+
+def _attach(model, tcfg):
+ """The calls every MoE-wired trainer makes, in order, then peft's attach."""
+ from peft import get_peft_model
+
+ targets = resolve_lora_target_modules(model, tcfg.lora.target_modules)
+ targets = resolve_moe_lora_targets(model, tcfg, targets, None)
+ return get_peft_model(
+ model, build_lora_config(tcfg.lora, target_modules=targets, task_type="CAUSAL_LM")
+ )
+
+
+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)]
+
+
+def _expert_layers(peft_model) -> list[str]:
+ return [n for n in _tuner_layers(peft_model) if ".experts" in n]
+
+
+class TestFusedExpertsAreFound:
+ @pytest.mark.parametrize("arch", _FUSED_FAMILIES)
+ def test_the_fused_parameters_are_named_as_peft_suffixes(self, arch):
+ found = find_fused_expert_parameters(_model(arch))
+ assert found == ["mlp.experts.down_proj", "mlp.experts.gate_up_proj"], (arch, found)
+
+ def test_the_per_expert_linear_layout_has_none(self):
+ """The control: with one Linear per expert there is nothing fused, and the
+ module-name discovery still finds the projections."""
+ model = _PerExpertLinearMoE()
+ assert find_fused_expert_parameters(model) == []
+ targets = get_moe_target_modules(model)
+ assert {"gate_proj", "up_proj", "down_proj"} <= set(targets)
+
+ def test_a_dense_model_has_none(self):
+ assert find_fused_expert_parameters(_model("dense")) == []
+
+ def test_a_shared_expert_is_not_a_fused_routed_expert(self):
+ """Qwen2-MoE's ``mlp.shared_expert.gate_proj.weight`` is 2-D and lives on an
+ ordinary Linear; only the 3-D routed tensors count."""
+ found = find_fused_expert_parameters(_model("qwen2_moe"))
+ assert not any("shared" in name for name in found), found
+
+ def test_a_model_without_parameters_is_tolerated(self):
+ """Several suites drive the resolver with a namespace or a mock standing in
+ for the model; those have no experts and must not raise."""
+ assert find_fused_expert_parameters(SimpleNamespace(config=None)) == []
+ from unittest.mock import MagicMock
+
+ assert find_fused_expert_parameters(MagicMock()) == []
+
+
+class TestMoeLoraReachesTheExperts:
+ @pytest.mark.parametrize("arch", _FUSED_FAMILIES)
+ def test_routed_experts_get_adapters_on_every_fused_family(self, arch):
+ attached = _attach(_model(arch), _tcfg())
+ experts = _expert_layers(attached)
+ # two parameters per layer, wrapped one inside the other, on two layers
+ assert len(experts) == 4, (arch, experts)
+
+ @pytest.mark.parametrize("arch", _WERE_ATTENTION_ONLY)
+ def test_the_expert_adapters_receive_gradient(self, arch):
+ """The adapters are live, not decorative: one backward pass puts a non-zero
+ gradient on every expert LoRA tensor of the families that trained attention
+ only before this fix."""
+ attached = _attach(_model(arch), _tcfg())
+ ids = torch.randint(1, 64, (1, 6))
+ # no cache: a two-layer Qwen3.5 stand-in is all linear attention, and its
+ # cache object cannot report a sequence length for that
+ attached(input_ids=ids, labels=ids, use_cache=False).loss.backward()
+ expert_lora = [
+ (n, p) for n, p in attached.named_parameters()
+ if p.requires_grad and ".experts" in n and "lora_" in n
+ ]
+ assert len(expert_lora) == 8, [n for n, _ in expert_lora] # A and B, 2 params, 2 layers
+ assert all(p.grad is not None for _, p in expert_lora)
+ # lora_B starts at zero, so lora_A's gradient is zero on the first step by
+ # construction; lora_B's is the one that shows the experts are in the graph.
+ b_grads = [p.grad.abs().sum().item() for n, p in expert_lora if "lora_B" in n]
+ assert len(b_grads) == 4 and all(g > 0 for g in b_grads), b_grads
+
+ def test_qwen35_keeps_the_linear_attention_targets_auto_picks(self):
+ """``auto`` resolves Qwen3.5 to ``q_proj, v_proj, in_proj_qkv, out_proj``;
+ ``moe_lora`` used to replace that list, dropping the linear-attention
+ projections. They are kept, and the experts are added."""
+ attached = _attach(_model("qwen3_5_moe"), _tcfg())
+ layers = _tuner_layers(attached)
+ assert any(n.endswith("linear_attn.in_proj_qkv") for n in layers), layers
+ assert any(n.endswith("linear_attn.out_proj") for n in layers), layers
+ assert _expert_layers(attached)
+
+ def test_without_the_flag_no_expert_is_adapted(self):
+ """The control: the expert adapters are the flag's doing. Explicit module
+ targets, because ``auto`` on Mixtral is peft's own (failing) default and
+ not what is under test here."""
+ tcfg = _tcfg(moe_lora=False)
+ tcfg.lora.target_modules = ["q_proj", "v_proj"]
+ attached = _attach(_model("mixtral"), tcfg)
+ assert _tuner_layers(attached) and not _expert_layers(attached)
+
+ def test_a_dense_model_is_untouched(self):
+ model = _model("dense")
+ targets = resolve_moe_lora_targets(model, _tcfg(), ["q_proj"])
+ assert targets == ["q_proj"]
+ assert getattr(targets, "target_parameters", None) in (None, [])
+
+ def test_the_per_expert_linear_layout_still_resolves_module_names(self):
+ """Control for the old layout: no ``target_parameters`` are invented, and the
+ projections are still named as modules, as before this change."""
+ targets = resolve_moe_lora_targets(_PerExpertLinearMoE(), _tcfg(), ["q_proj"])
+ assert {"gate_proj", "up_proj", "down_proj"} <= set(targets)
+ assert not getattr(targets, "target_parameters", None)
+
+ def test_the_resolved_targets_carry_the_parameters_into_the_lora_config(self):
+ model = _model("mixtral")
+ targets = resolve_moe_lora_targets(model, _tcfg(), ["q_proj"])
+ assert targets.target_parameters == [
+ "mlp.experts.down_proj", "mlp.experts.gate_up_proj"
+ ]
+ config = build_lora_config(_tcfg().lora, target_modules=targets, task_type="CAUSAL_LM")
+ assert set(config.target_parameters) >= set(targets.target_parameters)
+ assert "q_proj" in config.target_modules
+
+ def test_explicit_target_parameters_are_merged_not_replaced(self):
+ model = _model("mixtral")
+ targets = resolve_moe_lora_targets(model, _tcfg(), ["q_proj"])
+ config = build_lora_config(
+ _tcfg().lora, target_modules=targets, task_type="CAUSAL_LM",
+ target_parameters=["model.layers.0.self_attn.q_proj.weight"],
+ )
+ assert "model.layers.0.self_attn.q_proj.weight" in config.target_parameters
+ assert "mlp.experts.gate_up_proj" in config.target_parameters
+
+ def test_the_console_line_names_the_fused_parameters(self):
+ from io import StringIO
+
+ from rich.console import Console
+
+ buf = StringIO()
+ console = Console(file=buf, force_terminal=False, width=400, color_system=None)
+ resolve_moe_lora_targets(_model("mixtral"), _tcfg(), ["q_proj"], console)
+ out = buf.getvalue()
+ assert "ScatterMoE LoRA" in out
+ assert "mlp.experts.gate_up_proj" in out and "mlp.experts.down_proj" in out
+
+
+class TestTheDropoutRefusalFollowsTheTargets:
+ """peft adapts a fused parameter through ``lora.ParamWrapper``, which refuses any
+ dropout. Now that Mixtral and MiniMax are targeted explicitly, they are refused
+ with a non-zero dropout too; #798's test pinned the opposite while their experts
+ were out of reach."""
+
+ @pytest.mark.parametrize("arch", _FUSED_FAMILIES)
+ def test_dropout_on_a_fused_family_is_refused_naming_the_flag(self, arch):
+ with pytest.raises(ValueError) as excinfo:
+ resolve_moe_lora_targets(_model(arch), _tcfg(dropout=0.05), ["q_proj"])
+ message = str(excinfo.value)
+ assert "training.moe_lora=true needs training.lora.dropout: 0.0" in message
+ assert "lora.ParamWrapper does not work with lora_dropout != 0" in message
+
+ def test_the_per_expert_linear_layout_keeps_dropout(self):
+ targets = resolve_moe_lora_targets(_PerExpertLinearMoE(), _tcfg(dropout=0.05), None)
+ assert targets
+
+
+class TestMoeExpertQuantRefusesFusedExperts:
+ def test_the_expert_scan_finds_the_fused_block(self):
+ """The issue's third criterion: ``_find_expert_linears`` is not empty on a
+ transformers-5 fused model. The block comes back as itself, not as a
+ Linear, which is what the quant path keys its refusal on."""
+ from soup_cli.utils.moe_quant import _find_expert_linears
+
+ found = _find_expert_linears(_model("mixtral"))
+ assert [name for name, _ in found] == [
+ "model.layers.0.mlp.experts", "model.layers.1.mlp.experts"
+ ]
+ assert not any(isinstance(module, torch.nn.Linear) for _, module in found)
+
+ def test_a_fused_model_is_refused_by_name_before_any_cuda_check(self):
+ with pytest.raises(ValueError) as excinfo:
+ apply_moe_expert_quant(_model("mixtral"), "nf4")
+ message = str(excinfo.value)
+ assert "moe_expert_quant" in message and "mixtral" in message
+ assert "mlp.experts.gate_up_proj" in message
+ assert "nn.Linear" in message
+
+ def test_the_hook_never_reports_zero_as_success(self):
+ """A model with no expert Linear at all (the dense control) used to print
+ ``applied to 0 expert Linear block(s)``."""
+ with pytest.raises(ValueError, match="matched no expert"):
+ apply_moe_expert_quant_if_configured(_model("dense"), _tcfg(moe_expert_quant="nf4"))
+
+ def test_the_hook_is_a_no_op_when_unset(self):
+ apply_moe_expert_quant_if_configured(_model("mixtral"), _tcfg(moe_expert_quant=None))
+
+ def test_the_per_expert_linear_layout_still_reaches_the_quant_path(self):
+ """Control: the old layout is found by the Linear scan, and the fused-expert
+ refusal does not fire on it. What happens next (the bitsandbytes / CUDA
+ gate, or the real swap) is hardware-dependent and already pinned by
+ ``tests/test_v07120.py``, so it is not repeated here."""
+ from soup_cli.utils.moe_quant import _find_expert_linears, _refuse_fused_experts
+
+ model = _PerExpertLinearMoE()
+ assert len(_find_expert_linears(model)) == 6
+ _refuse_fused_experts(model, "nf4") # no raise: nothing fused here
+
+
+class TestTheIssueScriptThroughTheSftTrainer:
+ """The issue's reproduction, on its tiny Mixtral, through ``SFTTrainerWrapper``."""
+
+ def _setup(self, tmp_path, monkeypatch, *, extra: str = ""):
+ pytest.importorskip("trl")
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import PreTrainedTokenizerFast
+
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.sft import SFTTrainerWrapper
+
+ words = ["<pad>", "<s>", "</s>", "<unk>", "<|user|>", "<|assistant|>", "hello", "hi"]
+ raw = Tokenizer(
+ models.WordLevel(vocab={w: i for i, w in enumerate(words)}, unk_token="<unk>")
+ )
+ raw.pre_tokenizer = pre_tokenizers.Whitespace()
+ tok = PreTrainedTokenizerFast(
+ tokenizer_object=raw, bos_token="<s>", eos_token="</s>",
+ pad_token="<pad>", unk_token="<unk>",
+ )
+ tok.chat_template = (
+ "{% for m in messages %}{{ '<|' + m['role'] + '|> ' + m['content'] + ' </s> ' }}"
+ "{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|> ' }}{% endif %}"
+ )
+ model = transformers.MixtralForCausalLM(
+ transformers.MixtralConfig(
+ vocab_size=len(words), hidden_size=32, intermediate_size=64,
+ num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=1,
+ pad_token_id=0, bos_token_id=1, eos_token_id=2,
+ num_local_experts=4, num_experts_per_tok=2,
+ )
+ )
+ base = tmp_path / "tiny_moe"
+ model.save_pretrained(base)
+ tok.save_pretrained(base)
+ monkeypatch.chdir(tmp_path)
+ cfg = load_config_from_string(
+ "base: ./tiny_moe\ntask: sft\n"
+ "data: {train: ./unused.jsonl, format: chatml, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 1\n quantization: none\n"
+ f" moe_lora: true\n{extra}"
+ " lora: {r: 4, alpha: 8, dropout: 0.0}\n"
+ "output: ./out_moe\n"
+ )
+ chat = [{"role": "user", "content": "hello"}, {"role": "assistant", "content": "hi"}]
+ wrapper = SFTTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": [{"messages": chat}] * 4})
+ return wrapper
+
+ def test_moe_lora_adapts_the_routed_experts(self, tmp_path, monkeypatch):
+ wrapper = self._setup(tmp_path, monkeypatch)
+ adapted = sorted(
+ {n.split(".lora_")[0] for n, p in wrapper.model.named_parameters() if p.requires_grad}
+ )
+ assert any(n.endswith("mlp.experts") or ".mlp.experts." in n for n in adapted), adapted
+
+ def test_moe_expert_quant_is_refused_instead_of_applied_to_zero(self, tmp_path, monkeypatch):
+ with pytest.raises(ValueError, match="fused") as excinfo:
+ self._setup(tmp_path, monkeypatch, extra=" moe_expert_quant: nf4\n")
+ assert "mixtral" in str(excinfo.value)
+
+
+class TestTheAttachPreflightSeesTheExperts:
+ def test_trainer_lora_config_carries_the_fused_parameters(self):
+ """``soup recipes verify`` builds the trainer's adapter config through this
+ helper; it must report the experts the trainer now adapts."""
+ from soup_cli.utils.attach_preflight import trainer_lora_config
+
+ model = _model("mixtral")
+ cfg = SimpleNamespace(task="sft", modality="text", training=_tcfg())
+ peft_config, _targets = trainer_lora_config(model, cfg, None)
+ assert "mlp.experts.gate_up_proj" in peft_config.target_parameters
+
+
+class TestNothingElseMoved:
+ def test_get_moe_target_modules_is_unchanged_for_fused_models(self):
+ """The module-name half keeps its fallback; the fused parameters travel
+ beside it, not instead of it."""
+ targets = get_moe_target_modules(_model("mixtral"))
+ assert targets[:4] == list(moe_mod.STANDARD_TARGET_MODULES)
diff --git a/tests/test_issue798_moe_flags_per_task.py b/tests/test_issue798_moe_flags_per_task.py
index ef622c2b..8a25e33e 100644
--- a/tests/test_issue798_moe_flags_per_task.py
+++ b/tests/test_issue798_moe_flags_per_task.py
@@ -443,13 +443,19 @@ class TestTheDropoutConstraint:
)
@pytest.mark.parametrize("arch", ["mixtral", "minimax"])
- def test_an_architecture_peft_does_not_route_is_not_refused(self, arch):
- """The over-refusal this replaced: peft accepts these at dropout 0.05,
- so Soup must not refuse them. Verified against the real attach below."""
+ def test_an_architecture_peft_does_not_route_is_refused_since_1421(self, arch):
+ """Until #1421 these two were NOT refused: peft's conversion never routed
+ their targets onto the fused experts, so the attach at dropout 0.05
+ succeeded -- and adapted no experts. Now ``moe_lora`` names the fused
+ parameters itself, so the experts are reached on these families too, and
+ peft's ``ParamWrapper`` refuses dropout there exactly as on Qwen3-MoE.
+ ``test_peft_really_accepts_those_two_at_dropout`` below still holds for a
+ module-only attach, which is what it measures."""
from soup_cli.utils.moe import resolve_moe_lora_targets
model = _MOE_STAND_INS[arch]()
- assert resolve_moe_lora_targets(model, self._tcfg(0.05), ["q_proj"]) is not None
+ with pytest.raises(ValueError, match="ParamWrapper"):
+ resolve_moe_lora_targets(model, self._tcfg(0.05), ["q_proj"])
@pytest.mark.parametrize("arch", ["mixtral", "minimax"])
def test_peft_really_accepts_those_two_at_dropout(self, arch):
@@ -631,9 +637,11 @@ class TestPerArchitectureCoverage:
a recipe that looks fixed and is not is worse than one that visibly fails.
"""
- #: What `get_moe_target_modules` + a real peft attach does per family, on
- #: tiny stand-ins. `expert adapters > 0` is the thing `moe_lora` promises.
- EXPECTED = {
+ #: What the module names alone (`get_moe_target_modules` + a real peft
+ #: attach) reach per family, on tiny stand-ins: peft's own name conversion
+ #: decides it. Since #1421 the trainer path below adds the fused parameters
+ #: as `target_parameters`, and every family here gets its expert adapters.
+ MODULE_NAMES_ALONE = {
"qwen3_moe": True,
"deepseek_v3": True,
"glm4_moe": True,
@@ -641,24 +649,47 @@ class TestPerArchitectureCoverage:
"minimax": False,
}
- @pytest.mark.parametrize("arch", sorted(EXPECTED))
- def test_expert_coverage_is_what_the_pr_claims(self, arch):
+ @pytest.mark.parametrize("arch", sorted(MODULE_NAMES_ALONE))
+ def test_expert_coverage_by_module_names_alone(self, arch):
from peft import LoraConfig, TaskType, get_peft_model
from soup_cli.utils.moe import get_moe_target_modules
model = _MOE_STAND_INS[arch]()
attached = get_peft_model(model, LoraConfig(
- r=4, lora_dropout=0.0, target_modules=get_moe_target_modules(model),
+ r=4, lora_dropout=0.0, target_modules=list(get_moe_target_modules(model)),
task_type=TaskType.CAUSAL_LM,
))
experts = [name for name in _adapted(attached) if "expert" in name.lower()]
- assert bool(experts) is self.EXPECTED[arch], (arch, experts)
+ assert bool(experts) is self.MODULE_NAMES_ALONE[arch], (arch, experts)
+
+ @pytest.mark.parametrize("arch", sorted(MODULE_NAMES_ALONE))
+ def test_the_trainer_path_reaches_the_experts_on_every_family(self, arch):
+ """#1421: the two calls every MoE-wired trainer makes, then peft's attach.
+ The fused parameters travel on the resolved targets into the LoraConfig,
+ so Mixtral and MiniMax are no longer attention-only."""
+ from peft import get_peft_model
+
+ from soup_cli.utils.moe import resolve_moe_lora_targets
+ from soup_cli.utils.peft_wiring import build_lora_config
+
+ model = _MOE_STAND_INS[arch]()
+ tcfg = SimpleNamespace(moe_lora=True, lora=SimpleNamespace(
+ r=4, alpha=8, dropout=0.0, use_dora=False, use_rslora=False, use_vera=False,
+ rank_pattern=None, alpha_pattern=None, init_strategy="random",
+ ))
+ targets = resolve_moe_lora_targets(model, tcfg, ["q_proj"], None)
+ attached = get_peft_model(
+ model, build_lora_config(tcfg.lora, target_modules=targets, task_type="CAUSAL_LM")
+ )
+ experts = [name for name in _adapted(attached) if "expert" in name.lower()]
+ assert experts, (arch, _adapted(attached))
def test_the_uncovered_families_are_named_in_the_docs(self):
- """MiniMax gets zero expert adapters, so `minimax-m3-sft` trains
- attention-only. That has to be written down where a user looks, not only
- in a test. (`minimax-m3-dpo` was removed in #1145: DPO cannot build the
+ """`minimax-m3-sft` sets no `moe_lora` (it loads through SFT's vision
+ path, which never runs the MoE step), so it trains attention-only. That
+ has to be written down where a user looks, not only in a test.
+ (`minimax-m3-dpo` was removed in #1145: DPO cannot build the
`minimax_m3_vl` wrapper.)"""
from pathlib import Path