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(config): refuse use_mod on routes that never apply routing (#1757)

Matt Van Horna58f203e12a5
diff --git a/changelog.d/0.76.0/1757.fixed.md b/changelog.d/0.76.0/1757.fixed.md
new file mode 100644
index 00000000..c9b8d664
--- /dev/null
+++ b/changelog.d/0.76.0/1757.fixed.md
@@ -0,0 +1 @@
+- **`training.use_mod: true` is refused at config load on routes that never install a Mixture-of-Depths router (#1752).** The flag was accepted on every task. Only the resident LoRA arm of the transformers SFT setup (which `tts` reaches) and the transformers pretrain setup (after its LISA/LoRA split, so LISA is included) call the router. Full fine-tuning, LISA and Spectrum on SFT, vision, audio, layer streaming, unsloth and MLX SFT all trained without one. Those requests now fail at load, naming `training.use_mod`, the task, the settings that leave the applying path, and a valid change or `use_mod: false`. Transformers SFT LoRA, TTS LoRA, pretrain LoRA and pretrain LISA still apply it. Pretrain does not inherit SFT's modality or streaming restrictions. The MLX SFT trainer keeps its own warning for the field, but a config can no longer reach it, so `soup doctor --config` lists no row for it. **This is a breaking change** for configs that set `use_mod: true` on a route that never applied it — that run was already training a different model than requested. `use_mod: false` and an omitted flag are unchanged, and an out-of-range `mod_capacity_factor` is still rejected by its own check (#1752 by @mvanhorn in #1757).
diff --git a/docs/commands.md b/docs/commands.md
index e3357be9..a2d4057a 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -375,7 +375,7 @@ soup train --config grpo.yaml # training.echo_trap_enabled: true [echo_trap_thr
soup train # task='moe_lora_routing' + mole_task_adapters MoLE per-token gate over N frozen task LoRAs (gate-only train) — LIVE (v0.71.12)
soup train # task='distill' + distill_mode=token|sequence Token logit-KL or sequence-level teacher-continuation KD — LIVE (v0.71.12)
soup train # task=classifier|reranker|cross_encoder + lora LoRA-adapter classifier (frozen encoder) — LIVE (v0.71.12)
-soup train # use_mod | expand_layers Mixture-of-Depths / LLaMA Pro (Llama/Qwen/Mistral) — LIVE (v0.71.12)
+soup train # use_mod | expand_layers Mixture-of-Depths / LLaMA Pro (Llama/Qwen/Mistral) — LIVE (v0.71.12). use_mod is applied only on the resident transformers LoRA route of task sft or tts (text, no layer streaming, lora.r >= 1, no LISA or Spectrum) and on transformers pretrain (LoRA or LISA); every other route is refused at config load (#1752)
soup train # use_longlora LongLoRA S² is refused at config load: the override leaked future tokens and applied no S² grouping; use rope_scaling_type with plain LoRA (#1240)
soup train # task='tts' + tts_family + modality='audio_out' Codec-string SFT + emotion templating — LIVE (v0.71.20); native Sesame CSM with raw audio + 32 Mimi codebooks (#265); Spark/Oute raw-audio refused
soup train # task in {sft,tts} + moe_expert_quant=nf4|int8_rowwise [+moe_lora] bnb per-expert quant of fused-MoE experts (CUDA); refused on other tasks, which never applied it (#798) — LIVE (v0.71.20)
diff --git a/docs/config-reference.md b/docs/config-reference.md
index 0c72fa2e..c06eece1 100644
--- a/docs/config-reference.md
+++ b/docs/config-reference.md
@@ -121,7 +121,7 @@ Sections:
| `training.lr_groups` | `list[dict[str, str \| float]] \| null` | `null` | | Staged, not applied: a per-module LR override (list of {pattern, lr} entries or a {pattern: lr} dict, capped at 32) that no optimizer reads; setting it warns at load, then is refused (#761). (v0.41.0) |
| `training.expand_layers` | `int \| null` | `null` | `>= 1`, `<= 64` | LLaMA Pro: append N zero-init transformer blocks and freeze the original ones, so only the new blocks train. A LoRA rank is refused with it, since get_peft_model would freeze the new blocks again (#1326): set lora.r: 0 and quantization: none on task: sft. |
| `training.freeze_trainable_layers` | `int \| null` | `null` | | LLaMA Pro: applies only together with expand_layers, must equal it, and is refused otherwise. It freezes every parameter of the original model so only the appended blocks train; it does not select top-N or bottom-N layers. Magnitude capped at 1000. (v0.41.0) |
-| `training.use_mod` | `bool` | `false` | | Enable Mixture-of-Depths selective-token routing (arXiv:2404.02258). Live in v0.71.12 #84 for SFT + Pretrain on Llama / Qwen / Mistral; each decoder layer gets a router that passes only the top-k tokens (k = floor(seq_len \* mod_capacity_factor)) through the block. |
+| `training.use_mod` | `bool` | `false` | | Enable Mixture-of-Depths selective-token routing (arXiv:2404.02258). Each decoder layer gets a router that passes only the top-k tokens (k = floor(seq_len \* mod_capacity_factor)) through the block. Applied on the resident transformers LoRA path for sft and tts (not vision, audio, layer streaming, LISA, Spectrum, lora.r=0, unsloth, or mlx) and on transformers pretrain including LISA; refused at config load anywhere else (#1752). Unsupported architectures warn and skip. (v0.71.12 #84) |
| `training.mod_capacity_factor` | `float` | `0.125` | `> 0.0`, `<= 1.0` | Fraction of tokens routed through each block when use_mod=True. Bounded (0, 1]; default 0.125 (per the MoD paper). (v0.71.12 #84) |
| `training.load_in_8bit` | `bool \| null` | `null` | | Friendly alias for quantization='8bit' / 'none'. When True, rewrites quantization to '8bit' if currently 'none'/'4bit'. Conflicts with load_in_16bit. (v0.41.0) |
| `training.load_in_16bit` | `bool \| null` | `null` | | Friendly alias: when True, sets quantization='none' (full bf16/fp16 LoRA). Conflicts with load_in_8bit. (v0.41.0) |
diff --git a/docs/training.md b/docs/training.md
index 1b854b09..7269910d 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -2218,7 +2218,30 @@ the trained router, see `soup serve --mole` in [Serving and Export](serving-and-
Two architecture transforms that were schema-only are now live on Llama / Qwen / Mistral:
Mixture-of-Depths on SFT and pretrain, LLaMA Pro on SFT only
-([#1813](https://github.com/MakazhanAlpamys/Soup/issues/1813)). Both apply at trainer setup:
+([#1813](https://github.com/MakazhanAlpamys/Soup/issues/1813)). Both apply at trainer setup.
+
+`training.use_mod: true` installs a per-layer top-k token router
+(`mod_capacity_factor`, default 0.125). It is applied only on the routes
+below. Every other active request is refused at config load, naming
+`training.use_mod`, the task, the settings that leave the applying path, and
+what to change or `use_mod: false` (#1752).
+
+| Config | `use_mod: true` |
+| --- | --- |
+| `task: sft`, `backend: transformers`, `modality: text`, no layer streaming, `lora.r` >= 1, LISA off, no `unfrozen_parameters` | applied |
+| `task: tts`, `modality: audio_out`, `backend: transformers`, `lora.r` >= 1 | applied (`tts` trains through that SFT LoRA arm) |
+| `task: pretrain`, `backend: transformers`, LoRA or LISA | applied |
+| `task: sft` with `modality: vision` or `audio`, `stream_layers: true`, LISA, nonempty `unfrozen_parameters`, or `lora.r: 0` | refused |
+| `task: sft` or `tts` with `backend: unsloth`, or `task: sft` with `backend: mlx` | refused |
+| `task: tts` with `lora.r: 0` | refused |
+| `task: pretrain` with `backend: unsloth` | refused |
+| any other task | refused |
+
+Pretrain follows its own dispatch. Modality and streaming are not MoD
+refusals there, and a pretrain LISA run still installs the router. A config
+that is already invalid — `backend: mlx` on `tts` or `pretrain`,
+`stream_layers` outside its task list, or `lora.r: 0` on `pretrain` without
+LISA — keeps that earlier error instead of this one.
```yaml
training:
@@ -2240,11 +2263,12 @@ training:
r: 0
```
-`use_mod` attaches AFTER `get_peft_model`, so the new routers are trainable. `expand_layers`
+`use_mod` attaches AFTER `get_peft_model` on the SFT/TTS LoRA arm, and after the LISA/LoRA
+split on pretrain, so the new routers are trainable. `expand_layers`
runs BEFORE it, and `get_peft_model` would freeze the appended blocks again, so a LoRA rank is
refused with `expand_layers` and the blocks train with `lora.r: 0`
([#1326](https://github.com/MakazhanAlpamys/Soup/issues/1326)). Unsupported architectures
-warn + skip. Pick one of MoD / LLaMA Pro per run. (v0.71.12)
+warn + skip. Pick one of MoD / LLaMA Pro per run. (v0.71.12; `use_mod` route gate #1752)
LongLoRA S² (`use_longlora: true`) is refused at config load
([#1240](https://github.com/MakazhanAlpamys/Soup/issues/1240)). Its override rolled the
diff --git a/src/soup_cli/config/backend_support.py b/src/soup_cli/config/backend_support.py
index 77fbded2..c5476a31 100644
--- a/src/soup_cli/config/backend_support.py
+++ b/src/soup_cli/config/backend_support.py
@@ -160,12 +160,6 @@ _MLX_SFT: tuple[SupportEntry, ...] = (
"NEFT noise is applied on the transformers training path, not MLX",
trainer_reads=True,
),
- SupportEntry(
- "training.use_mod",
- IGNORED,
- "Mixture-of-Depths routing is wired on the transformers path, not MLX",
- trainer_reads=True,
- ),
SupportEntry(
"training.moe_lora",
IGNORED,
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 1d7de5b7..815e0c7c 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -1341,9 +1341,13 @@ class TrainingConfig(BaseModel):
default=False,
description=(
"Enable Mixture-of-Depths selective-token routing (arXiv:2404.02258). "
- "Live in v0.71.12 #84 for SFT + Pretrain on Llama / Qwen / Mistral; "
- "each decoder layer gets a router that passes only the top-k tokens "
- "(k = floor(seq_len * mod_capacity_factor)) through the block."
+ "Each decoder layer gets a router that passes only the top-k tokens "
+ "(k = floor(seq_len * mod_capacity_factor)) through the block. Applied "
+ "on the resident transformers LoRA path for sft and tts (not vision, "
+ "audio, layer streaming, LISA, Spectrum, lora.r=0, unsloth, or mlx) "
+ "and on transformers pretrain including LISA; refused at config load "
+ "anywhere else (#1752). Unsupported architectures warn and skip. "
+ "(v0.71.12 #84)"
),
)
mod_capacity_factor: float = Field(
@@ -4955,6 +4959,16 @@ FREEZE_APPLYING_TASKS: frozenset[str] = frozenset({"sft", "tts"})
#: within these tasks on every path that does not reach those two methods.
ROPE_SCALING_APPLYING_TASKS: frozenset[str] = frozenset({"sft", "tts", "pretrain"})
+#: #1752 — the tasks whose trainer installs a Mixture-of-Depths router. The
+#: call sits in the LoRA arm of ``SFTTrainerWrapper._setup_transformers``
+#: (``tts`` reaches it through ``super()``) and in
+#: ``PretrainTrainerWrapper._setup_transformers`` after the LISA/LoRA split,
+#: so pretrain LISA is included. Every other task is refused. Within sft and
+#: tts, vision, audio, layer streaming, unsloth, MLX, LISA, Spectrum and
+#: ``lora.r == 0`` never reach that arm and are refused too. Pretrain branches
+#: on the backend only, so those SFT gates are not applied to it.
+MOD_APPLYING_TASKS: frozenset[str] = frozenset({"sft", "tts", "pretrain"})
+
#: #1820 — the tasks whose trainer reads ``training.neftune_alpha`` and passes
#: it as ``neftune_noise_alpha`` to ``TrainingArguments``. Every other task
#: ignores the field, so it is refused there at config load.
@@ -8785,6 +8799,72 @@ class SoupConfig(BaseModel):
f"checkpoint's own RoPE. Use {changes}, or remove {keys}."
)
+ @model_validator(mode="after")
+ def _validate_use_mod_is_applied(self) -> "SoupConfig":
+ """#1752 — ``use_mod`` loaded on every task, but a router is installed
+ only by the LoRA arm of ``SFTTrainerWrapper._setup_transformers`` (which
+ ``tts`` reaches through ``super()``) and by
+ ``PretrainTrainerWrapper._setup_transformers`` after its LISA/LoRA
+ split. Everywhere else the run trained without the router that was
+ requested. Placed with the freeze / RoPE route checks, before the
+ #1357 backend refusal, which stays last. Combinations an earlier
+ validator already rejects keep that error."""
+ tcfg = self.training
+ if not tcfg.use_mod:
+ return self
+ if self.task not in MOD_APPLYING_TASKS:
+ raise ValueError(
+ f"training.use_mod is not applied by task={self.task!r}: only "
+ "task='sft', 'tts' and 'pretrain' install a Mixture-of-Depths "
+ "router, so this run would train without one. Use one of those "
+ "tasks, or set use_mod: false."
+ )
+ off_path = []
+ # PretrainTrainerWrapper.setup branches on the backend only and applies
+ # MoD after the LISA/LoRA split, so LISA is included and SFT's modality,
+ # streaming and parameter-selection gates are not. sft and tts share
+ # SFTTrainerWrapper.setup, which reaches the call only on the resident
+ # LoRA arm. Settings are named in the order resolve_trainer and that
+ # setup check them, then the LoRA-arm chain inside _setup_transformers.
+ if self.task == "pretrain":
+ if self.backend == "unsloth":
+ off_path.append(("backend='unsloth'", "backend: transformers"))
+ where = "on backend: transformers, including a LISA run"
+ else:
+ if self.backend == "mlx":
+ off_path.append(("backend='mlx'", "backend: transformers"))
+ if self.modality in ("vision", "audio"):
+ off_path.append((f"modality={self.modality!r}", "modality: text"))
+ if tcfg.stream_layers:
+ off_path.append(("training.stream_layers=true", "stream_layers: false"))
+ if self.backend == "unsloth":
+ off_path.append(("backend='unsloth'", "backend: transformers"))
+ if tcfg.unfrozen_parameters:
+ off_path.append(("training.unfrozen_parameters", "unfrozen_parameters: null"))
+ if tcfg.lisa_enabled:
+ off_path.append(("training.lisa_enabled=true", "lisa_enabled: false"))
+ if tcfg.lora.r == 0:
+ off_path.append(("training.lora.r=0", "lora.r >= 1"))
+ where = (
+ "on the resident text LoRA path with backend: transformers, "
+ "no layer streaming, lora.r >= 1, and neither LISA nor Spectrum"
+ if self.task == "sft"
+ else (
+ "on the transformers LoRA path tts reaches through the SFT "
+ "trainer (lora.r >= 1, not unsloth)"
+ )
+ )
+ if not off_path:
+ return self
+ settings = " and ".join(setting for setting, _ in off_path)
+ changes = " and ".join(change for _, change in off_path)
+ raise ValueError(
+ f"training.use_mod is not applied by task={self.task!r} with {settings}: "
+ f"a Mixture-of-Depths router is installed only {where}, so this run "
+ "would train without one. "
+ f"Use {changes}, or set use_mod: false."
+ )
+
@model_validator(mode="after")
def _validate_unsloth_sft_modality(self) -> "SoupConfig":
"""#1186: multimodal SFT setup does not use the requested Unsloth backend."""
diff --git a/tests/test_issue755_backend_support_registry.py b/tests/test_issue755_backend_support_registry.py
index d01bf777..2d0da945 100644
--- a/tests/test_issue755_backend_support_registry.py
+++ b/tests/test_issue755_backend_support_registry.py
@@ -179,11 +179,13 @@ def test_registry_covers_every_field_the_mlx_trainer_warns_about():
unknown = sorted(warned - known)
assert unknown == [], f"warning list names fields that do not exist: {unknown}"
registered = {e.field for e in unsupported_for("sft", "mlx")}
- # These warnings are internal guards for schema-refused monitoring values.
- # Their load-time refusal is pinned by test_issue1069; doctor cannot list them.
+ # These warnings are internal guards for schema-refused values. Their
+ # load-time refusal is pinned by test_issue1069 (monitoring flags) and
+ # test_mlx_use_mod_is_refused_at_load_and_has_no_doctor_row below (use_mod,
+ # #1752); doctor cannot list them.
schema_refused = {
"training.loss_watchdog", "training.loss_spike_recovery",
- "training.grad_accum_auto_tune",
+ "training.grad_accum_auto_tune", "training.use_mod",
}
missing = sorted(warned - registered - schema_refused)
assert missing == [], (
@@ -264,26 +266,45 @@ def test_961_reachable_fields_reported_together(config_at):
#961 declared four reachable fields. ``training.quantization_aware`` is no
longer one of them on MLX: ``true`` is refused at load on every backend
- (#1222), and ``fp8`` and ``quest`` are refused on mlx. So three are
- reported together, and adding the fourth stops the load instead.
+ (#1222), and ``fp8`` and ``quest`` are refused on mlx. ``training.use_mod``
+ is refused at load too (#1752). The two that still load are reported
+ together, and adding either refused field stops the load instead.
"""
from soup_cli.config.backend_support import check_config
from soup_cli.config.loader import load_config
- fields = " use_mod: true\n moe_lora: true\n use_fsdp2_compile: true"
+ fields = " moe_lora: true\n use_fsdp2_compile: true"
cfg = load_config(config_at("sft", "mlx", fields))
rows = check_config(cfg)
assert {e.field for e in rows} == {
- "training.use_mod",
"training.moe_lora",
"training.use_fsdp2_compile",
}
- assert len(rows) == 3
+ assert len(rows) == 2
with pytest.raises(SystemExit):
load_config(config_at("sft", "mlx", fields + "\n quantization_aware: true"))
+def test_mlx_use_mod_is_refused_at_load_and_has_no_doctor_row(config_at):
+ """#1752 — ``use_mod: true`` on MLX SFT stops at config load, so doctor can
+ never see it and the registry lists no row for it (a ``REJECTED`` row would
+ be unreachable, #1330). ``mlx_sft.py`` keeps its own warning for the field."""
+ from soup_cli.config.backend_support import unsupported_for
+ from soup_cli.config.loader import load_config, load_config_from_string
+
+ assert "training.use_mod" not in {e.field for e in unsupported_for("sft", "mlx")}
+
+ path = config_at("sft", "mlx", " use_mod: true")
+ with pytest.raises(ValueError) as info:
+ load_config_from_string(pathlib.Path(path).read_text(encoding="utf-8"))
+ message = " ".join(str(info.value).split())
+ assert "training.use_mod is not applied by task='sft' with backend='mlx'" in message, message
+ assert message.endswith("Use backend: transformers, or set use_mod: false.")
+ with pytest.raises(SystemExit):
+ load_config(path)
+
+
def test_only_fields_the_user_actually_set_are_reported(config_at):
"""Not all 275 — and not the other MLX gaps the user never touched."""
from soup_cli.config.backend_support import check_config
diff --git a/tests/test_use_mod_route_scope.py b/tests/test_use_mod_route_scope.py
new file mode 100644
index 00000000..01b12961
--- /dev/null
+++ b/tests/test_use_mod_route_scope.py
@@ -0,0 +1,430 @@
+"""#1752 — ``training.use_mod`` is refused at load where nothing installs a router.
+
+The flag loaded on all 23 tasks. Two call sites install a Mixture-of-Depths
+router: the LoRA arm of ``SFTTrainerWrapper._setup_transformers`` (``tts``
+reaches it through ``super()``) and ``PretrainTrainerWrapper._setup_transformers``
+after its LISA/LoRA split. Everywhere else the run trained without one and
+said nothing. Those configs now stop at load.
+
+Nothing is trained here: the gate is a config validator.
+"""
+
+from __future__ import annotations
+
+import typing
+
+import pytest
+import yaml
+
+from soup_cli.config.loader import load_config, load_config_from_string
+from soup_cli.config.schema import MOD_APPLYING_TASKS, SoupConfig
+
+_TASKS = tuple(typing.get_args(SoupConfig.model_fields["task"].annotation))
+# Written out, not read from MOD_APPLYING_TASKS: a task dropped from or added
+# to the constant must not move its own tests with it.
+_APPLYING = ("sft", "tts", "pretrain")
+_REFUSED = tuple(task for task in _TASKS if task not in _APPLYING)
+
+# The minimum each task needs to load at all (as in the #1697 tests).
+_TOP = {"tts": {"modality": "audio_out"}}
+_DATA = {
+ "dpo": {"format": "dpo"}, "kto": {"format": "kto"}, "pretrain": {"format": "plaintext"},
+ "unlearn": {"forget_set": "./f.jsonl"},
+}
+_TRAINING = {
+ "preference": {"preference_loss": "dpo"},
+ "tts": {"tts_family": "orpheus"},
+ "classifier": {"num_labels": 2}, "reranker": {"num_labels": 2},
+ "cross_encoder": {"num_labels": 2},
+ "unlearn": {"unlearn_method": "npo"},
+ "moe_lora_routing": {"mole_task_adapters": ["./a", "./b"]},
+ "distill": {"teacher_model": "org/t"},
+ "online_dpo": {"online_dpo_judge": "pairrm"},
+}
+
+_SFT_WHERE = (
+ "on the resident text LoRA path with backend: transformers, "
+ "no layer streaming, lora.r >= 1, and neither LISA nor Spectrum"
+)
+_TTS_WHERE = (
+ "on the transformers LoRA path tts reaches through the SFT "
+ "trainer (lora.r >= 1, not unsloth)"
+)
+_PRETRAIN_WHERE = "on backend: transformers, including a LISA run"
+
+# Paths that load today and never reach the router call:
+# (task, top-level keys, training keys, the setting named, the change, where).
+_OFF_PATH = {
+ "sft-mlx": (
+ "sft", {"backend": "mlx"}, {},
+ "backend='mlx'", "backend: transformers", _SFT_WHERE,
+ ),
+ "sft-vision": (
+ "sft", {"modality": "vision"}, {},
+ "modality='vision'", "modality: text", _SFT_WHERE,
+ ),
+ "sft-audio": (
+ "sft", {"modality": "audio"}, {},
+ "modality='audio'", "modality: text", _SFT_WHERE,
+ ),
+ "sft-stream": (
+ "sft", {}, {"stream_layers": True, "batch_size": 1},
+ "training.stream_layers=true", "stream_layers: false", _SFT_WHERE,
+ ),
+ "sft-unsloth": (
+ "sft", {"backend": "unsloth"}, {},
+ "backend='unsloth'", "backend: transformers", _SFT_WHERE,
+ ),
+ "sft-full-ft": (
+ "sft", {}, {"quantization": "none", "lora": {"r": 0}},
+ "training.lora.r=0", "lora.r >= 1", _SFT_WHERE,
+ ),
+ "sft-lisa": (
+ "sft", {}, {"quantization": "none", "lisa_enabled": True},
+ "training.lisa_enabled=true", "lisa_enabled: false", _SFT_WHERE,
+ ),
+ "sft-spectrum": (
+ "sft", {}, {
+ "quantization": "none",
+ "unfrozen_parameters": ["model.layers.0.mlp.down_proj"],
+ },
+ "training.unfrozen_parameters", "unfrozen_parameters: null", _SFT_WHERE,
+ ),
+ "tts-unsloth": (
+ "tts", {"backend": "unsloth"}, {},
+ "backend='unsloth'", "backend: transformers", _TTS_WHERE,
+ ),
+ "tts-full-ft": (
+ "tts", {}, {"lora": {"r": 0}},
+ "training.lora.r=0", "lora.r >= 1", _TTS_WHERE,
+ ),
+ "pretrain-unsloth": (
+ "pretrain", {"backend": "unsloth"}, {},
+ "backend='unsloth'", "backend: transformers", _PRETRAIN_WHERE,
+ ),
+}
+
+
+def _yaml(task="sft", top=None, **training):
+ raw = {
+ "base": "org/m", "task": task, **_TOP.get(task, {}), **(top or {}),
+ "data": {"train": "./x.jsonl", **_DATA.get(task, {})},
+ "training": {**_TRAINING.get(task, {}), **training},
+ }
+ return yaml.safe_dump(raw)
+
+
+def _refusal(text):
+ with pytest.raises(ValueError) as info:
+ load_config_from_string(text)
+ return " ".join(str(info.value).split())
+
+
+def _assert_off_path(message, task, settings, where, change):
+ assert (
+ f"training.use_mod is not applied by task={task!r} with {settings}: "
+ f"a Mixture-of-Depths router is installed only {where}, so"
+ ) in message, message
+ assert "would train without one" in message
+ assert message.endswith(f"Use {change}, or set use_mod: false.")
+
+
+def test_the_task_list_is_the_one_this_file_was_written_for():
+ assert len(_TASKS) == 23
+ assert set(_APPLYING) <= set(_TASKS)
+ assert MOD_APPLYING_TASKS == frozenset({"sft", "tts", "pretrain"})
+
+
+class TestRefusedOutsideTheThreeTasks:
+ @pytest.mark.parametrize("task", _TASKS)
+ def test_without_the_flag_the_task_still_loads(self, task):
+ assert load_config_from_string(_yaml(task)).training.use_mod is False
+
+ @pytest.mark.parametrize("task", _REFUSED)
+ def test_the_message_names_the_field_the_task_and_the_fix(self, task):
+ message = _refusal(_yaml(task, use_mod=True))
+
+ assert (
+ f"training.use_mod is not applied by task={task!r}: only "
+ "task='sft', 'tts' and 'pretrain' install a Mixture-of-Depths router"
+ ) in message, message
+ assert "would train without one" in message
+ assert message.endswith("Use one of those tasks, or set use_mod: false.")
+
+ @pytest.mark.parametrize("backend", ["transformers", "unsloth"])
+ def test_the_task_refusal_does_not_depend_on_the_backend(self, backend):
+ """``dpo`` on unsloth is refused for the task, not for the path."""
+ message = _refusal(_yaml("dpo", {"backend": backend}, use_mod=True))
+
+ assert "is not applied by task='dpo': only task='sft'" in message, message
+
+ def test_clearing_the_flag_loads(self):
+ raw = yaml.safe_load(_yaml("dpo", use_mod=True))
+ raw["training"]["use_mod"] = False
+
+ assert load_config_from_string(yaml.safe_dump(raw)).task == "dpo"
+
+
+class TestRefusedOffTheApplyingPath:
+ @pytest.mark.parametrize("case", list(_OFF_PATH))
+ def test_the_message_names_the_field_the_path_and_the_fix(self, case):
+ task, top, training, setting, change, where = _OFF_PATH[case]
+
+ message = _refusal(_yaml(task, top, **training, use_mod=True))
+
+ _assert_off_path(message, task, setting, where, change)
+
+ @pytest.mark.parametrize("case", list(_OFF_PATH))
+ @pytest.mark.parametrize("flag", [None, False])
+ def test_omitted_or_false_still_loads(self, case, flag):
+ """The refusal is about the request, not about the path."""
+ task, top, training, _, _, _ = _OFF_PATH[case]
+ if flag is not None:
+ training = {**training, "use_mod": flag}
+
+ cfg = load_config_from_string(_yaml(task, top, **training))
+
+ assert cfg.training.use_mod is False
+
+ @pytest.mark.parametrize(
+ ("top", "training", "settings", "change"),
+ [
+ (
+ {"backend": "unsloth", "modality": "vision"},
+ {},
+ "modality='vision' and backend='unsloth'",
+ "modality: text and backend: transformers",
+ ),
+ (
+ {"backend": "unsloth", "modality": "audio"},
+ {},
+ "modality='audio' and backend='unsloth'",
+ "modality: text and backend: transformers",
+ ),
+ (
+ {"backend": "mlx", "modality": "vision"},
+ {},
+ "backend='mlx' and modality='vision'",
+ "backend: transformers and modality: text",
+ ),
+ ],
+ )
+ def test_every_sft_setting_off_the_path_is_named(self, top, training, settings, change):
+ """Changing one of two settings would still leave the run off the LoRA
+ arm, so both are named, in the order the trainer checks them."""
+ message = _refusal(_yaml("sft", top, **training, use_mod=True))
+
+ _assert_off_path(message, "sft", settings, _SFT_WHERE, change)
+
+ def test_tts_unsloth_and_full_finetune_are_named_together(self):
+ """Both are legal on tts and both skip the inherited LoRA arm."""
+ message = _refusal(_yaml("tts", {"backend": "unsloth"}, lora={"r": 0}, use_mod=True))
+
+ _assert_off_path(
+ message, "tts",
+ "backend='unsloth' and training.lora.r=0",
+ _TTS_WHERE,
+ "backend: transformers and lora.r >= 1",
+ )
+
+ def test_following_the_sft_message_loads(self):
+ raw = yaml.safe_load(
+ _yaml("sft", {"modality": "vision", "backend": "unsloth"}, use_mod=True)
+ )
+ raw["modality"] = "text"
+ raw["backend"] = "transformers"
+
+ cfg = load_config_from_string(yaml.safe_dump(raw))
+
+ assert cfg.training.use_mod is True
+ assert cfg.modality == "text"
+ assert cfg.backend == "transformers"
+
+
+class TestTheApplyingPathsStillLoad:
+ @pytest.mark.parametrize("task", ["sft", "tts", "pretrain"])
+ def test_transformers_lora(self, task):
+ cfg = load_config_from_string(
+ _yaml(task, {"backend": "transformers"}, use_mod=True)
+ )
+
+ assert cfg.training.use_mod is True
+
+ def test_pretrain_lisa(self):
+ cfg = load_config_from_string(
+ _yaml("pretrain", quantization="none", lisa_enabled=True, use_mod=True)
+ )
+
+ assert cfg.training.use_mod is True
+ assert cfg.training.lisa_enabled is True
+
+ @pytest.mark.parametrize("modality", ["vision", "audio"])
+ def test_pretrain_modality_is_not_an_sft_gate(self, modality):
+ """``PretrainTrainerWrapper.setup`` branches on the backend only."""
+ cfg = load_config_from_string(
+ _yaml("pretrain", {"modality": modality}, use_mod=True)
+ )
+
+ assert cfg.training.use_mod is True
+
+ def test_pretrain_stream_layers_false_is_not_streaming(self):
+ cfg = load_config_from_string(
+ _yaml("pretrain", stream_layers=False, use_mod=True)
+ )
+
+ assert cfg.training.use_mod is True
+
+ def test_pretrain_lisa_with_lora_r_zero_is_not_the_sft_full_finetune_gate(self):
+ """Pretrain LISA attaches no adapter, so ``lora.r: 0`` still loads there
+ (#1875) and the router call after the LISA split still runs. Without LISA
+ a zero rank is refused earlier; see ``TestAlreadyRefusedForAnotherReason``."""
+ cfg = load_config_from_string(
+ _yaml(
+ "pretrain", quantization="none", lisa_enabled=True,
+ lora={"r": 0}, use_mod=True,
+ )
+ )
+
+ assert cfg.training.lora.r == 0
+ assert cfg.training.lisa_enabled is True
+ assert cfg.training.use_mod is True
+
+ def test_sft_stream_layers_false_is_not_streaming(self):
+ cfg = load_config_from_string(_yaml("sft", stream_layers=False, use_mod=True))
+
+ assert cfg.training.use_mod is True
+
+ def test_capacity_factor_still_loads_on_an_applying_path(self):
+ cfg = load_config_from_string(
+ _yaml("sft", use_mod=True, mod_capacity_factor=0.25)
+ )
+
+ assert cfg.training.mod_capacity_factor == pytest.approx(0.25)
+
+
+class TestAlreadyRefusedForAnotherReason:
+ """These never reached the new check, before or after. They are listed so
+ a baseline failure is not reported as a MoD refusal."""
+
+ @pytest.mark.parametrize(
+ ("text", "needle"),
+ [
+ (
+ _yaml("pretrain", {"backend": "mlx"}, use_mod=True),
+ "MLX backend only ships SFT",
+ ),
+ (
+ _yaml("tts", {"backend": "mlx"}, use_mod=True),
+ "not supported on backend=mlx",
+ ),
+ (
+ _yaml("pretrain", quantization="none", lora={"r": 0}, use_mod=True),
+ "its trainer always attaches a LoRA adapter",
+ ),
+ (
+ _yaml("pretrain", stream_layers=True, batch_size=1, use_mod=True),
+ "training.stream_layers supports task",
+ ),
+ (
+ _yaml("tts", stream_layers=True, batch_size=1, use_mod=True),
+ "training.stream_layers supports task",
+ ),
+ (
+ _yaml("sft", stream_layers=True, use_mod=True),
+ "batch_size='auto'",
+ ),
+ (
+ _yaml("sft", lisa_enabled=True, use_mod=True),
+ "quantization='none'",
+ ),
+ (
+ _yaml(
+ "sft", {"backend": "unsloth"},
+ quantization="none", lora={"r": 0}, use_mod=True,
+ ),
+ "full fine-tuning",
+ ),
+ (
+ _yaml(
+ "tts", quantization="none", lisa_enabled=True, use_mod=True,
+ ),
+ "training.lisa_enabled",
+ ),
+ (
+ _yaml("dpo", use_mod=True, mod_capacity_factor=2.0),
+ "mod_capacity_factor",
+ ),
+ (
+ _yaml("sft", use_mod=True, mod_capacity_factor=2.0),
+ "mod_capacity_factor",
+ ),
+ ],
+ )
+ def test_the_earlier_error_is_not_replaced(self, text, needle):
+ message = _refusal(text)
+
+ assert needle in message, message
+ assert "Mixture-of-Depths" not in message
+
+
+class TestDumpAndFileLoad:
+ def test_a_default_dump_round_trips(self):
+ dumped = yaml.safe_dump(
+ load_config_from_string(_yaml("sft")).model_dump(mode="json")
+ )
+
+ assert "use_mod: false" in dumped
+ assert load_config_from_string(dumped).training.use_mod is False
+
+ def test_load_config_exits_on_a_refused_file(self, tmp_path, monkeypatch):
+ from soup_cli.config import loader
+
+ printed: list[str] = []
+
+ def record(*args, **kwargs):
+ printed.append(str(args[0]) if args else "")
+
+ monkeypatch.setattr(loader.console, "print", record)
+ path = tmp_path / "soup.yaml"
+ path.write_text(_yaml("dpo", use_mod=True), encoding="utf-8")
+
+ with pytest.raises(SystemExit) as excinfo:
+ loader.load_config(path)
+
+ assert excinfo.value.code == 1
+ joined = " ".join(" ".join(printed).split())
+ assert "training.use_mod is not applied by task='dpo'" in joined
+
+ def test_load_config_accepts_an_applying_file(self, tmp_path):
+ path = tmp_path / "soup.yaml"
+ path.write_text(_yaml("tts", use_mod=True), encoding="utf-8")
+
+ cfg = load_config(path)
+
+ assert cfg.task == "tts"
+ assert cfg.training.use_mod is True
+
+
+class TestValidatorOrder:
+ def test_it_sits_with_the_route_checks_and_before_the_backend_refusal(self):
+ """#1357's backend refusal stays last. Earlier task gates stay in
+ front, so they keep their own errors."""
+ validators = SoupConfig.__pydantic_decorators__.model_validators
+ after = [name for name, dec in validators.items() if dec.info.mode == "after"]
+
+ assert (
+ after.index("_validate_freeze_is_applied")
+ < after.index("_validate_rope_scaling_is_applied")
+ < after.index("_validate_use_mod_is_applied")
+ < after.index("_validate_unsloth_has_a_setup")
+ ), after[-5:]
+ assert after[-1] == "_validate_unsloth_has_a_setup"
+ for earlier in (
+ "_validate_tts_compat",
+ "_validate_unfrozen_parameters",
+ "_validate_lisa_compat",
+ "_validate_full_finetune",
+ "_validate_stream_layers_compat",
+ "_validate_mlx_task_support",
+ ):
+ assert after.index(earlier) < after.index("_validate_use_mod_is_applied")