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(train): resolve the trainer wrapper through one dispatch, shared with sweep (#1213) (#1397)

dymuxdb7c03e2aeb3
diff --git a/changelog.d/0.75.1/1397.fixed.md b/changelog.d/0.75.1/1397.fixed.md
new file mode 100644
index 00000000..018668d2
--- /dev/null
+++ b/changelog.d/0.75.1/1397.fixed.md
@@ -0,0 +1 @@
+- **`soup sweep` builds the trainer `soup train` builds, for every task and for `backend: mlx` (#1213 by @putramkti in #1397).** The command carried its own `if/elif` chain over `task`, last extended in v0.40.0. Ten values (`distill`, `tts`, `classifier`, `reranker`, `cross_encoder`, `prm`, `unlearn`, `moe_lora_routing`, `online_dpo`, `asr`) reached the SFT wrapper, and `backend: mlx` was never read at all, so an arm trained next-token cross-entropy while the run registry recorded the configured task and the sweep ranked those numbers as the configured objective. Both commands now resolve through `soup_cli/trainer/dispatch.py::build_trainer`, which refuses a task it has no wrapper for instead of falling back to SFT.
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index 28eb42ff..54160558 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -504,6 +504,10 @@ soup sweep --config soup.yaml --param lr=1e-5,2e-5 --param epochs=2,3 --dry-run
soup sweep --config soup.yaml --param lr=1e-5,2e-5,5e-5 --early-stop 1.5
```
+Every arm builds the trainer `soup train` builds for the config's `task` and
+`backend`, so an arm on a `task: distill` config distills, and an arm on
+`backend: mlx` uses the MLX wrapper.
+
## Model Comparison
diff --git a/src/soup_cli/commands/sweep.py b/src/soup_cli/commands/sweep.py
index 6202ae98..968f5b68 100644
--- a/src/soup_cli/commands/sweep.py
+++ b/src/soup_cli/commands/sweep.py
@@ -12,6 +12,7 @@ from rich.panel import Panel
from rich.table import Table
from soup_cli.config.loader import load_config
+from soup_cli.utils.terminal import for_terminal
console = Console()
@@ -212,7 +213,12 @@ def sweep(
f"({best_loss:.4f} x {early_stop} = {best_loss * early_stop:.4f})[/]"
)
except Exception as exc:
- console.print(f"[red]Run {run_name} failed: {exc}[/]")
+ # #1213 — a `backend: mlx` arm now reaches the MLX wrapper, whose
+ # install hint reads `pip install "soup-cli[mlx]"`. Interpolated
+ # straight into the markup string, Rich reads `[mlx]` as a style tag
+ # and drops it, so the hint that tells the user what to install is
+ # the part that disappears. `for_terminal` escapes it.
+ console.print(f"[red]Run {run_name} failed:[/] {for_terminal(exc)}")
results.append({
"name": run_name,
"params": combo,
@@ -438,7 +444,7 @@ def _run_single(base_cfg, params: dict, run_name: str, config_path: Path) -> dic
from soup_cli.data.loader import load_dataset
from soup_cli.experiment.tracker import ExperimentTracker
from soup_cli.monitoring.display import TrainingDisplay
- from soup_cli.trainer.sft import SFTTrainerWrapper
+ from soup_cli.trainer.dispatch import build_trainer
from soup_cli.utils.eval_schedule import loader_data_config, validation_notice
from soup_cli.utils.gpu import detect_device, get_gpu_info
@@ -468,57 +474,11 @@ def _run_single(base_cfg, params: dict, run_name: str, config_path: Path) -> dic
experiment_name=run_name,
)
- # Build trainer
- if cfg.task == "dpo":
- from soup_cli.trainer.dpo import DPOTrainerWrapper
-
- trainer_wrapper = DPOTrainerWrapper(cfg, device=device)
- elif cfg.task == "kto":
- from soup_cli.trainer.kto import KTOTrainerWrapper
-
- trainer_wrapper = KTOTrainerWrapper(cfg, device=device)
- elif cfg.task == "grpo":
- from soup_cli.trainer.grpo import GRPOTrainerWrapper
-
- trainer_wrapper = GRPOTrainerWrapper(cfg, device=device)
- elif cfg.task == "ppo":
- from soup_cli.trainer.ppo import PPOTrainerWrapper
-
- trainer_wrapper = PPOTrainerWrapper(cfg, device=device)
- elif cfg.task == "orpo":
- from soup_cli.trainer.orpo import ORPOTrainerWrapper
-
- trainer_wrapper = ORPOTrainerWrapper(cfg, device=device)
- elif cfg.task == "simpo":
- from soup_cli.trainer.simpo import SimPOTrainerWrapper
-
- trainer_wrapper = SimPOTrainerWrapper(cfg, device=device)
- elif cfg.task == "ipo":
- from soup_cli.trainer.ipo import IPOTrainerWrapper
-
- trainer_wrapper = IPOTrainerWrapper(cfg, device=device)
- elif cfg.task == "bco":
- from soup_cli.trainer.bco import BCOTrainerWrapper
-
- trainer_wrapper = BCOTrainerWrapper(cfg, device=device)
- elif cfg.task == "preference":
- from soup_cli.trainer.preference import PreferenceTrainerWrapper
-
- trainer_wrapper = PreferenceTrainerWrapper(cfg, device=device)
- elif cfg.task == "reward_model":
- from soup_cli.trainer.reward_model import RewardModelTrainerWrapper
-
- trainer_wrapper = RewardModelTrainerWrapper(cfg, device=device)
- elif cfg.task == "pretrain":
- from soup_cli.trainer.pretrain import PretrainTrainerWrapper
-
- trainer_wrapper = PretrainTrainerWrapper(cfg, device=device)
- elif cfg.task == "embedding":
- from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
-
- trainer_wrapper = EmbeddingTrainerWrapper(cfg, device=device)
- else:
- trainer_wrapper = SFTTrainerWrapper(cfg, device=device)
+ # Build trainer — the same dispatch `soup train` uses (#1213). This used to
+ # be a second, shorter chain that never grew past v0.40.0, so ten task
+ # values and every `backend: mlx` config were trained as plain SFT here
+ # while the tracker recorded the configured task.
+ trainer_wrapper = build_trainer(cfg, device=device)
trainer_wrapper.setup(dataset)
# Train
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 339fec9f..5279bdb6 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -1632,106 +1632,12 @@ def train(
# v0.40.4 #63 — every transformer-backend trainer now threads
# --trust-remote-code through the wrapper (closes the v0.36.0 Part B gap).
trainer_kwargs = dict(trainer_kwargs, trust_remote_code=trust_remote_code)
- from soup_cli.trainer.mlx_routing import resolve_trainer
-
- mlx_cls, trainer_kwargs = resolve_trainer(cfg, trainer_kwargs)
- if mlx_cls is not None:
- trainer_wrapper = mlx_cls(cfg, **trainer_kwargs)
- elif cfg.task == "dpo":
- from soup_cli.trainer.dpo import DPOTrainerWrapper
-
- trainer_wrapper = DPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "online_dpo":
- from soup_cli.trainer.online_dpo import OnlineDPOTrainerWrapper
-
- trainer_wrapper = OnlineDPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "grpo":
- from soup_cli.trainer.grpo import GRPOTrainerWrapper
-
- trainer_wrapper = GRPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "ppo":
- from soup_cli.trainer.ppo import PPOTrainerWrapper
-
- trainer_wrapper = PPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "kto":
- from soup_cli.trainer.kto import KTOTrainerWrapper
-
- trainer_wrapper = KTOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "orpo":
- from soup_cli.trainer.orpo import ORPOTrainerWrapper
-
- trainer_wrapper = ORPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "simpo":
- from soup_cli.trainer.simpo import SimPOTrainerWrapper
-
- trainer_wrapper = SimPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "ipo":
- from soup_cli.trainer.ipo import IPOTrainerWrapper
-
- trainer_wrapper = IPOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "bco":
- from soup_cli.trainer.bco import BCOTrainerWrapper
-
- trainer_wrapper = BCOTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "preference":
- from soup_cli.trainer.preference import PreferenceTrainerWrapper
-
- trainer_wrapper = PreferenceTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "reward_model":
- from soup_cli.trainer.reward_model import RewardModelTrainerWrapper
-
- trainer_wrapper = RewardModelTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "pretrain":
- from soup_cli.trainer.pretrain import PretrainTrainerWrapper
-
- trainer_wrapper = PretrainTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "embedding":
- from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
-
- trainer_wrapper = EmbeddingTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "distill":
- # v0.53.2 #133 — knowledge distillation (student + frozen teacher).
- from soup_cli.trainer.distill import DistillTrainerWrapper
-
- trainer_wrapper = DistillTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "prm":
- # v0.53.11 #126 — Process Reward Model trainer.
- from soup_cli.trainer.prm import PRMTrainerWrapper
-
- trainer_wrapper = PRMTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task in ("classifier", "reranker", "cross_encoder"):
- # v0.53.2 #132 — sequence-classification head.
- from soup_cli.trainer.classifier import ClassifierTrainerWrapper
-
- trainer_wrapper = ClassifierTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "unlearn":
- # v0.71.9 #193 — NPO / SimNPO / RMU unlearning.
- from soup_cli.trainer.unlearn import UnlearnTrainerWrapper
-
- trainer_wrapper = UnlearnTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "moe_lora_routing":
- # v0.71.12 #222 — MoLE per-token routing over N frozen task LoRAs.
- from soup_cli.trainer.mole_routing import MoleRoutingTrainerWrapper
-
- trainer_wrapper = MoleRoutingTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "tts":
- # v0.71.20 #131 — TTS fine-tuning (SFT-style next-token CE over
- # text + audio-codec-token sequences; per-family templating).
- from soup_cli.trainer.tts import TTSTrainerWrapper
-
- trainer_wrapper = TTSTrainerWrapper(cfg, **trainer_kwargs)
- elif cfg.task == "asr":
- # v0.71.32 — ASR (Whisper) fine-tuning via Seq2SeqTrainer.
- from soup_cli.trainer.asr import AsrTrainerWrapper
-
- trainer_wrapper = AsrTrainerWrapper(cfg, **trainer_kwargs)
- else:
- # Keep the transformers/TRL SFT surface outside the backend-first MLX
- # route. The wrapper is import-light today, but importing it eagerly
- # makes an MLX-only install depend on that remaining true forever.
- from soup_cli.trainer.sft import SFTTrainerWrapper
+ # #1213 — one dispatch, shared with `soup sweep`: the two commands used
+ # to keep separate chains and sweep's copy fell ten tasks and the MLX
+ # route behind. See soup_cli/trainer/dispatch.py.
+ from soup_cli.trainer.dispatch import build_trainer
- trainer_wrapper = SFTTrainerWrapper(cfg, **trainer_kwargs)
+ trainer_wrapper = build_trainer(cfg, **trainer_kwargs)
trainer_wrapper.setup(dataset)
# #350 — PEFT promotes newly-created adapters to fp32. FSDP cannot flatten
diff --git a/src/soup_cli/trainer/dispatch.py b/src/soup_cli/trainer/dispatch.py
new file mode 100644
index 00000000..f8252ed5
--- /dev/null
+++ b/src/soup_cli/trainer/dispatch.py
@@ -0,0 +1,144 @@
+"""One task to trainer-wrapper dispatch, shared by ``soup train`` and ``soup sweep``.
+
+The two commands used to carry their own ``if/elif`` chains over ``cfg.task``.
+``soup sweep``'s copy was last extended in v0.40.0 and never grew the MLX route,
+so for ten task values and for every ``backend: mlx`` config it built the SFT
+wrapper while the run registry recorded the configured task (#1213). One
+function, called from both, is what stops that from drifting again: the next
+task the schema grows has to reach both commands or neither.
+
+Imports stay inside the function. Every trainer wrapper and the MLX registry are
+lazy-imported elsewhere in this package, and an MLX-only install must not pull
+the transformers/TRL surface (``soup_cli.trainer.sft``) in at import time.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def build_trainer(cfg: Any, **trainer_kwargs: Any):
+ """Build the trainer wrapper for ``cfg.task`` on ``cfg.backend``.
+
+ ``trainer_kwargs`` are forwarded to the wrapper unchanged: ``soup train``
+ passes ``device``, ``report_to``, ``deepspeed_config``, ``fsdp_config`` and
+ ``trust_remote_code``; ``soup sweep`` passes ``device`` only.
+
+ This module names ``deepspeed_config`` because it forwards the keyword, and
+ it builds no trainer of its own, so it is exempt from the #359 guard scan
+ (see ``_GUARD_EXEMPT`` in ``tests/test_issue359_deepspeed_guard_coverage.py``).
+
+ A task with no wrapper raises ``ValueError`` naming the task. There is no
+ SFT fallback on purpose: a task value the schema accepts but this function
+ does not know has to fail in both commands, loudly, rather than train the
+ wrong objective in one of them.
+ """
+ from soup_cli.trainer.mlx_routing import resolve_trainer
+
+ mlx_cls, trainer_kwargs = resolve_trainer(cfg, trainer_kwargs)
+ if mlx_cls is not None:
+ return mlx_cls(cfg, **trainer_kwargs)
+
+ task = getattr(cfg, "task", None)
+ if task == "sft":
+ # The transformers/TRL SFT surface stays behind this import so an
+ # MLX-only install does not load it.
+ from soup_cli.trainer.sft import SFTTrainerWrapper
+
+ return SFTTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "dpo":
+ from soup_cli.trainer.dpo import DPOTrainerWrapper
+
+ return DPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "online_dpo":
+ # v0.71.31 — on-policy generation judged by a pairwise judge or a
+ # reward_model in the loop.
+ from soup_cli.trainer.online_dpo import OnlineDPOTrainerWrapper
+
+ return OnlineDPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "grpo":
+ from soup_cli.trainer.grpo import GRPOTrainerWrapper
+
+ return GRPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "ppo":
+ from soup_cli.trainer.ppo import PPOTrainerWrapper
+
+ return PPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "kto":
+ from soup_cli.trainer.kto import KTOTrainerWrapper
+
+ return KTOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "orpo":
+ from soup_cli.trainer.orpo import ORPOTrainerWrapper
+
+ return ORPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "simpo":
+ from soup_cli.trainer.simpo import SimPOTrainerWrapper
+
+ return SimPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "ipo":
+ from soup_cli.trainer.ipo import IPOTrainerWrapper
+
+ return IPOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "bco":
+ from soup_cli.trainer.bco import BCOTrainerWrapper
+
+ return BCOTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "preference":
+ from soup_cli.trainer.preference import PreferenceTrainerWrapper
+
+ return PreferenceTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "reward_model":
+ from soup_cli.trainer.reward_model import RewardModelTrainerWrapper
+
+ return RewardModelTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "pretrain":
+ from soup_cli.trainer.pretrain import PretrainTrainerWrapper
+
+ return PretrainTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "embedding":
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ return EmbeddingTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "distill":
+ # v0.53.2 #133 — knowledge distillation (student + frozen teacher).
+ from soup_cli.trainer.distill import DistillTrainerWrapper
+
+ return DistillTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "prm":
+ # v0.53.11 #126 — Process Reward Model trainer.
+ from soup_cli.trainer.prm import PRMTrainerWrapper
+
+ return PRMTrainerWrapper(cfg, **trainer_kwargs)
+ if task in ("classifier", "reranker", "cross_encoder"):
+ # v0.53.2 #132 — sequence-classification head.
+ from soup_cli.trainer.classifier import ClassifierTrainerWrapper
+
+ return ClassifierTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "unlearn":
+ # v0.71.9 #193 — NPO / SimNPO / RMU unlearning.
+ from soup_cli.trainer.unlearn import UnlearnTrainerWrapper
+
+ return UnlearnTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "moe_lora_routing":
+ # v0.71.12 #222 — MoLE per-token routing over N frozen task LoRAs.
+ from soup_cli.trainer.mole_routing import MoleRoutingTrainerWrapper
+
+ return MoleRoutingTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "tts":
+ # v0.71.20 #131 — TTS fine-tuning (SFT-style next-token CE over text +
+ # audio-codec-token sequences; per-family templating).
+ from soup_cli.trainer.tts import TTSTrainerWrapper
+
+ return TTSTrainerWrapper(cfg, **trainer_kwargs)
+ if task == "asr":
+ # v0.71.32 — ASR (Whisper) fine-tuning via Seq2SeqTrainer.
+ from soup_cli.trainer.asr import AsrTrainerWrapper
+
+ return AsrTrainerWrapper(cfg, **trainer_kwargs)
+
+ raise ValueError(
+ f"no trainer wrapper for task={task!r} on backend="
+ f"{getattr(cfg, 'backend', 'transformers')!r}. Add the task to "
+ "soup_cli/trainer/dispatch.py::build_trainer."
+ )
diff --git a/tests/test_issue1001_backend_support_cites_no_source_lines.py b/tests/test_issue1001_backend_support_cites_no_source_lines.py
index 18e30deb..f319ed37 100644
--- a/tests/test_issue1001_backend_support_cites_no_source_lines.py
+++ b/tests/test_issue1001_backend_support_cites_no_source_lines.py
@@ -59,6 +59,12 @@ def test_the_fsdp2_compile_reason_names_the_refusal_that_soup_train_runs():
train_source = (_SRC / "commands" / "train.py").read_text(encoding="utf-8")
assert "validate_fsdp2_compile_config(" in train_source
+ # #1213 — trainer resolution moved into the shared dispatch, so the ordering
+ # claim is now "the refusal runs before the wrapper is built". Both halves
+ # are checked: the call in train.py, and the resolve_trainer call inside the
+ # function that train.py reaches through.
assert train_source.index("validate_fsdp2_compile_config(") < train_source.index(
- "resolve_trainer("
+ "build_trainer("
)
+ dispatch_source = (_SRC / "trainer" / "dispatch.py").read_text(encoding="utf-8")
+ assert "resolve_trainer(" in dispatch_source
diff --git a/tests/test_issue1213_dispatch_parity.py b/tests/test_issue1213_dispatch_parity.py
new file mode 100644
index 00000000..6294cfe4
--- /dev/null
+++ b/tests/test_issue1213_dispatch_parity.py
@@ -0,0 +1,347 @@
+"""#1213 — `soup train` and `soup sweep` must build the same trainer wrapper.
+
+Both commands now route through ``soup_cli.trainer.dispatch.build_trainer``.
+Before that, sweep carried a second ``if/elif`` chain over ``cfg.task`` that was
+last extended in v0.40.0, with no MLX route at all: for ten task values and for
+every ``backend: mlx`` config, an arm trained plain next-token SFT while the run
+registry recorded the configured task, and the sweep ranked those numbers.
+
+The task list below is read off ``SoupConfig``'s ``task`` Literal instead of
+being hand-written, so a task added to the schema without a dispatch entry fails
+the first test rather than training the wrong objective under one command.
+"""
+
+from __future__ import annotations
+
+import importlib
+import typing
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+_SRC = Path(__file__).resolve().parents[1] / "src" / "soup_cli"
+
+#: Every wrapper ``build_trainer`` can construct, keyed by the module that
+#: defines it. The classes here depend on peft/trl/mlx, so each site is swapped
+#: for a recorder and no backend has to be installed for this file to run.
+_WRAPPER_SITES = {
+ "soup_cli.trainer.sft": "SFTTrainerWrapper",
+ "soup_cli.trainer.dpo": "DPOTrainerWrapper",
+ "soup_cli.trainer.online_dpo": "OnlineDPOTrainerWrapper",
+ "soup_cli.trainer.grpo": "GRPOTrainerWrapper",
+ "soup_cli.trainer.ppo": "PPOTrainerWrapper",
+ "soup_cli.trainer.kto": "KTOTrainerWrapper",
+ "soup_cli.trainer.orpo": "ORPOTrainerWrapper",
+ "soup_cli.trainer.simpo": "SimPOTrainerWrapper",
+ "soup_cli.trainer.ipo": "IPOTrainerWrapper",
+ "soup_cli.trainer.bco": "BCOTrainerWrapper",
+ "soup_cli.trainer.preference": "PreferenceTrainerWrapper",
+ "soup_cli.trainer.reward_model": "RewardModelTrainerWrapper",
+ "soup_cli.trainer.pretrain": "PretrainTrainerWrapper",
+ "soup_cli.trainer.embedding": "EmbeddingTrainerWrapper",
+ "soup_cli.trainer.distill": "DistillTrainerWrapper",
+ "soup_cli.trainer.prm": "PRMTrainerWrapper",
+ "soup_cli.trainer.classifier": "ClassifierTrainerWrapper",
+ "soup_cli.trainer.unlearn": "UnlearnTrainerWrapper",
+ "soup_cli.trainer.mole_routing": "MoleRoutingTrainerWrapper",
+ "soup_cli.trainer.tts": "TTSTrainerWrapper",
+ "soup_cli.trainer.asr": "AsrTrainerWrapper",
+}
+
+#: transformer-backend dispatch: task -> wrapper class name.
+_EXPECTED = {
+ "sft": "SFTTrainerWrapper",
+ "dpo": "DPOTrainerWrapper",
+ "online_dpo": "OnlineDPOTrainerWrapper",
+ "grpo": "GRPOTrainerWrapper",
+ "ppo": "PPOTrainerWrapper",
+ "kto": "KTOTrainerWrapper",
+ "orpo": "ORPOTrainerWrapper",
+ "simpo": "SimPOTrainerWrapper",
+ "ipo": "IPOTrainerWrapper",
+ "bco": "BCOTrainerWrapper",
+ "preference": "PreferenceTrainerWrapper",
+ "reward_model": "RewardModelTrainerWrapper",
+ "pretrain": "PretrainTrainerWrapper",
+ "embedding": "EmbeddingTrainerWrapper",
+ "distill": "DistillTrainerWrapper",
+ "prm": "PRMTrainerWrapper",
+ "classifier": "ClassifierTrainerWrapper",
+ "reranker": "ClassifierTrainerWrapper",
+ "cross_encoder": "ClassifierTrainerWrapper",
+ "unlearn": "UnlearnTrainerWrapper",
+ "moe_lora_routing": "MoleRoutingTrainerWrapper",
+ "tts": "TTSTrainerWrapper",
+ "asr": "AsrTrainerWrapper",
+}
+
+#: MLX rows resolve through ``mlx_routing``. Same three tasks the registry
+#: accepts; the name is what ``resolve_trainer`` would have imported.
+_MLX_EXPECTED = {
+ "sft": "MLXSFTTrainerWrapper",
+ "dpo": "MLXDPOTrainerWrapper",
+ "grpo": "MLXGRPOTrainerWrapper",
+}
+
+#: The minimum each task's own validator asks for on top of base + data.
+_TASK_EXTRAS: dict[str, dict] = {
+ "preference": {"training": {"preference_loss": "simpo"}},
+ "tts": {"modality": "audio_out", "training": {"tts_family": "orpheus"}},
+ "classifier": {"training": {"num_labels": 2}},
+ "reranker": {"training": {"num_labels": 2}},
+ "cross_encoder": {"training": {"num_labels": 2}},
+ "distill": {"training": {"teacher_model": "fixtures/teacher"}},
+ "unlearn": {
+ "training": {"unlearn_method": "npo"},
+ "data": {"forget_set": "./forget.jsonl"},
+ },
+ "moe_lora_routing": {"training": {"mole_task_adapters": ["adapter-a", "adapter-b"]}},
+ "online_dpo": {"training": {"online_dpo_judge": "some-judge-model"}},
+}
+
+
+def _schema_tasks() -> tuple[str, ...]:
+ from soup_cli.config.schema import SoupConfig
+
+ annotation = SoupConfig.model_fields["task"].annotation
+ return typing.get_args(annotation)
+
+
+def _recorder(name: str, built: list[str]):
+ """A stand-in wrapper that records the class name and satisfies the CLI."""
+
+ class _Recorder:
+ def __init__(self, cfg, **kwargs):
+ built.append(name)
+
+ def setup(self, dataset):
+ pass
+
+ def train(self, **kwargs):
+ return {
+ "initial_loss": 1.0,
+ "final_loss": 0.5,
+ "total_steps": 1,
+ "duration_secs": 1.0,
+ "output_dir": "out",
+ "duration": "1s",
+ }
+
+ _Recorder.__name__ = name
+ _Recorder.__qualname__ = name
+ return _Recorder
+
+
+def built(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ """Swap every wrapper class for a recorder; collects the names that get built.
+
+ Every wrapper module is imported *before* the first patch lands. Some of
+ them subclass a class that lives in another of them (`tts.py` subclasses
+ `sft.py`'s wrapper), and the base is bound at that module's first import. If
+ the patch were already in place, the real class would inherit from a
+ recorder and stay that way for the rest of the session, breaking any later
+ test that walks the MRO or monkeypatches the real base.
+ """
+ names: list[str] = []
+ modules = {
+ module_path: importlib.import_module(module_path)
+ for module_path in _WRAPPER_SITES
+ }
+ for module_path, cls_name in _WRAPPER_SITES.items():
+ monkeypatch.setattr(modules[module_path], cls_name, _recorder(cls_name, names))
+
+ from soup_cli.trainer import mlx_routing
+
+ monkeypatch.setattr(
+ mlx_routing,
+ "get_mlx_trainer",
+ lambda task: _recorder(_MLX_EXPECTED[task], names),
+ )
+ return names
+
+
+def _sweep_config(task: str):
+ from soup_cli.config.schema import SoupConfig
+
+ fields: dict = {"base": "some-model", "task": task, "data": {"train": "./d.jsonl"}}
+ for key, value in _TASK_EXTRAS.get(task, {}).items():
+ existing = fields.get(key)
+ fields[key] = {**existing, **value} if isinstance(existing, dict) else value
+ return SoupConfig(**fields)
+
+
+def _run_sweep_arm(cfg) -> None:
+ """Run one sweep arm with everything outside the dispatch stubbed out."""
+ from soup_cli.commands.sweep import _run_single
+
+ tracker = MagicMock()
+ tracker.start_run.return_value = "run-1"
+ with (
+ patch("soup_cli.data.loader.load_dataset", return_value={"train": [{"text": "x"}]}),
+ patch("soup_cli.utils.gpu.detect_device", return_value=("cpu", "CPU")),
+ patch("soup_cli.utils.gpu.get_gpu_info", return_value={}),
+ patch("soup_cli.experiment.tracker.ExperimentTracker", return_value=tracker),
+ patch("soup_cli.monitoring.display.TrainingDisplay"),
+ ):
+ _run_single(cfg, {}, "sweep_1", None)
+
+
+class TestDispatchParity:
+ def test_every_schema_task_has_a_dispatch_entry(self, built: list[str]) -> None:
+ """Walk the Literal: a task the schema grows without a wrapper fails here."""
+ from soup_cli.trainer.dispatch import build_trainer
+
+ assert set(_schema_tasks()) == set(_EXPECTED), (
+ "SoupConfig.task and the dispatch table disagree: update "
+ "soup_cli/trainer/dispatch.py::build_trainer and this file together"
+ )
+
+ for task, expected_name in _EXPECTED.items():
+ built.clear()
+ build_trainer(SimpleNamespace(task=task, backend="transformers"), device="cpu")
+ assert built == [expected_name], f"task={task!r} built {built}"
+
+ def test_mlx_backend_goes_through_the_registry(self, built: list[str]) -> None:
+ from soup_cli.trainer.dispatch import build_trainer
+
+ for task, expected_name in _MLX_EXPECTED.items():
+ built.clear()
+ build_trainer(SimpleNamespace(task=task, backend="mlx"), device="metal")
+ assert built == [expected_name], f"backend=mlx task={task!r} built {built}"
+
+ def test_sweep_builds_the_wrapper_the_schema_names(self, built: list[str]) -> None:
+ """The sweep-side half of the parity claim, over every task value."""
+ for task, expected_name in _EXPECTED.items():
+ built.clear()
+ _run_sweep_arm(_sweep_config(task))
+ assert built == [expected_name], f"sweep task={task!r} built {built}"
+
+ def test_sweep_builds_the_mlx_wrapper_too(self, built: list[str]) -> None:
+ """`backend: mlx` used to reach the SFT wrapper in sweep, and only there.
+
+ The schema admits MLX for ``sft`` alone (it refuses the other registry
+ entries before dispatch), so this row is the one end-to-end MLX case the
+ config layer allows.
+ """
+ cfg = _sweep_config("sft").model_copy(update={"backend": "mlx"})
+ built.clear()
+ _run_sweep_arm(cfg)
+ assert built == ["MLXSFTTrainerWrapper"], built
+
+ def test_an_unknown_task_raises_instead_of_falling_back_to_sft(
+ self, built: list[str]
+ ) -> None:
+ from soup_cli.trainer.dispatch import build_trainer
+
+ with pytest.raises(ValueError) as excinfo:
+ build_trainer(SimpleNamespace(task="not_a_task", backend="transformers"), device="cpu")
+
+ assert "not_a_task" in str(excinfo.value)
+ assert built == [], "an unknown task must not build an SFT wrapper"
+
+ def test_sweeping_the_shrink_heal_config_builds_the_distill_wrapper(
+ self, built: list[str], tmp_path: Path
+ ) -> None:
+ """`soup shrink --heal-steps` writes a `task: distill` config; sweep used to SFT it."""
+ from soup_cli.commands.shrink import _build_heal_config_yaml
+ from soup_cli.config.loader import load_config
+
+ heal_yaml = _build_heal_config_yaml(
+ pruned_dir=str(tmp_path / "pruned"),
+ teacher="fixtures/teacher",
+ heal_data=str(tmp_path / "heal.jsonl"),
+ steps=200,
+ out_dir=str(tmp_path / "healed"),
+ heal_rows=1000,
+ )
+ config_path = tmp_path / "soup.yaml"
+ config_path.write_text(heal_yaml, encoding="utf-8")
+ cfg = load_config(config_path)
+ assert cfg.task == "distill"
+
+ built.clear()
+ _run_sweep_arm(cfg)
+ assert built == ["DistillTrainerWrapper"], built
+
+
+class TestNoSecondChain:
+ """The regression this file exists for was a chain, not a wrong branch."""
+
+ @pytest.mark.parametrize("filename", ["train.py", "sweep.py"])
+ def test_command_calls_the_shared_dispatch_only(self, filename: str) -> None:
+ source = (_SRC / "commands" / filename).read_text(encoding="utf-8")
+
+ assert "build_trainer(" in source, f"{filename} does not call build_trainer"
+ assert "elif cfg.task ==" not in source, (
+ f"{filename} grew a task chain again; route it through "
+ "soup_cli/trainer/dispatch.py instead"
+ )
+
+
+class TestTheKwargsReachTheWrapper:
+ """`build_trainer` forwards each command's kwargs unchanged (#1213).
+
+ The parity tests above compare which *class* gets built. Without this class,
+ `build_trainer` could stop forwarding `trust_remote_code`,
+ `deepspeed_config`, `fsdp_config` or `report_to` and nothing would fail:
+ `soup train` would silently ignore `--trust-remote-code`, `--deepspeed`,
+ FSDP and trackers, and a sweep arm could lose `device=` and fall back to the
+ wrapper's own `"cuda"` default. Both mutations survive the recorder fixtures
+ because the recorder accepts `**kwargs` and never looks at them.
+ """
+
+ #: What `soup train` passes (commands/train.py builds exactly these five).
+ TRAIN_KWARGS = {
+ "device": "cpu",
+ "report_to": "none",
+ "deepspeed_config": "ds_config.json",
+ "fsdp_config": {"fsdp": "full_shard"},
+ "trust_remote_code": True,
+ }
+
+ @pytest.fixture
+ def seen(self, monkeypatch: pytest.MonkeyPatch) -> dict:
+ received: dict = {}
+
+ def recorder(name: str):
+ class _Recorder:
+ def __init__(self, cfg, **kwargs):
+ received[name] = kwargs
+
+ def setup(self, dataset):
+ pass
+
+ def train(self, **kwargs):
+ return {"initial_loss": 1.0, "final_loss": 0.5, "total_steps": 1,
+ "duration_secs": 1.0, "output_dir": "out", "duration": "1s"}
+
+ return _Recorder
+
+ modules = {path: importlib.import_module(path) for path in _WRAPPER_SITES}
+ for path, cls_name in _WRAPPER_SITES.items():
+ monkeypatch.setattr(modules[path], cls_name, recorder(cls_name))
+ from soup_cli.trainer import mlx_routing
+
+ monkeypatch.setattr(
+ mlx_routing, "get_mlx_trainer", lambda task: recorder(_MLX_EXPECTED[task])
+ )
+ return received
+
+ def test_build_trainer_forwards_every_kwarg_unchanged(self, seen: dict) -> None:
+ from soup_cli.trainer.dispatch import build_trainer
+
+ rows = [(task, "transformers", name) for task, name in _EXPECTED.items()]
+ rows += [(task, "mlx", name) for task, name in _MLX_EXPECTED.items()]
+ for task, backend, name in rows:
+ seen.clear()
+ build_trainer(SimpleNamespace(task=task, backend=backend), **self.TRAIN_KWARGS)
+ assert seen == {name: self.TRAIN_KWARGS}, f"{backend}/{task}: {seen}"
+
+ def test_sweep_passes_the_detected_device(self, seen: dict) -> None:
+ for task, name in _EXPECTED.items():
+ seen.clear()
+ _run_sweep_arm(_sweep_config(task))
+ assert seen == {name: {"device": "cpu"}}, f"sweep {task}: {seen}"
diff --git a/tests/test_issue359_deepspeed_guard_coverage.py b/tests/test_issue359_deepspeed_guard_coverage.py
index 62e16a6a..ccb4dec2 100644
--- a/tests/test_issue359_deepspeed_guard_coverage.py
+++ b/tests/test_issue359_deepspeed_guard_coverage.py
@@ -76,12 +76,13 @@ class TestGuardCoverage:
"with LoRA it dies at the first lr_scheduler.step() (#359)."
)
- #: preference.py forwards ``deepspeed_config`` into five wrappers that each
- #: carry the guard, and builds no trainer of its own. It is the ONLY module
- #: allowed to hold a deepspeed_config without calling the guard, and it is
- #: named here so that the next such module has to be argued for rather than
+ #: Modules that forward a ``deepspeed_config`` without calling the guard,
+ #: because they build no trainer of their own. Today: ``preference.py``
+ #: forwards it into five wrappers that each carry the guard, and
+ #: ``dispatch.py`` (#1213) forwards it to whichever wrapper it resolves.
+ #: Named here so that the next such module has to be argued for rather than
#: slipping through a regex that stopped matching.
- _GUARD_EXEMPT = {"preference.py"}
+ _GUARD_EXEMPT = {"preference.py", "dispatch.py"}
def test_no_deepspeed_capable_module_quietly_loses_the_guard(self):
"""Closes the rebind evasion: ``_BUILDS_TRAINER`` requires the
diff --git a/tests/test_sweep.py b/tests/test_sweep.py
index 870b6708..0f226410 100644
--- a/tests/test_sweep.py
+++ b/tests/test_sweep.py
@@ -1,5 +1,6 @@
"""Tests for soup sweep — hyperparameter search."""
+from pathlib import Path
import pytest
@@ -320,3 +321,29 @@ class TestSweepCLI:
"--strategy", "bayesian",
])
assert result.exit_code != 0
+
+
+def test_a_failed_arm_prints_its_error_verbatim(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`backend: mlx` arms now reach the MLX wrapper, whose install hint has brackets (#1213)."""
+ import re
+
+ from typer.testing import CliRunner
+
+ import soup_cli.commands.sweep as sweep_mod
+ from soup_cli.cli import app
+
+ def fail(*args, **kwargs):
+ raise ImportError('Install with: pip install "soup-cli[mlx]"')
+
+ monkeypatch.setattr(sweep_mod, "_run_single", fail)
+ config = tmp_path / "soup.yaml"
+ config.write_text("base: some-model\ndata:\n train: ./d.jsonl\n", encoding="utf-8")
+
+ result = CliRunner().invoke(
+ app, ["sweep", "--config", str(config), "--param", "lr=1e-5", "--yes"]
+ )
+
+ plain = " ".join(re.sub(r"\x1b\[[0-9;]*m", "", result.output).split())
+ assert 'pip install "soup-cli[mlx]"' in plain, plain
diff --git a/tests/test_v0532.py b/tests/test_v0532.py
index 3dbe3d92..e264fcab 100644
--- a/tests/test_v0532.py
+++ b/tests/test_v0532.py
@@ -868,24 +868,31 @@ class TestTrainRouting:
the class. ``"DistillTrainerWrapper(cfg, **trainer_kwargs)"`` requires the
actual call expression to be present, which is much harder to satisfy by
accident.
+
+ #1213 moved this chain out of ``commands/train.py`` into
+ ``trainer/dispatch.py``, which ``soup train`` and ``soup sweep`` both call,
+ so the audit now reads the module that holds the routing and also checks the
+ command still reaches it.
"""
def test_distill_routed(self) -> None:
from soup_cli.commands import train as train_cmd
+ from soup_cli.trainer import dispatch as dispatch_mod
- src = __import__("inspect").getsource(train_cmd)
- assert 'cfg.task == "distill"' in src
+ src = __import__("inspect").getsource(dispatch_mod)
+ assert "build_trainer(" in __import__("inspect").getsource(train_cmd)
+ assert 'task == "distill"' in src
# Require the actual instantiation expression, not just the bare name.
assert "DistillTrainerWrapper(cfg, **trainer_kwargs)" in src
def test_classifier_family_routed(self) -> None:
from soup_cli.commands import train as train_cmd
+ from soup_cli.trainer import dispatch as dispatch_mod
- src = __import__("inspect").getsource(train_cmd)
+ src = __import__("inspect").getsource(dispatch_mod)
+ assert "build_trainer(" in __import__("inspect").getsource(train_cmd)
# Tuple membership in the if-branch is the load-bearing pattern.
- assert (
- 'cfg.task in ("classifier", "reranker", "cross_encoder")' in src
- )
+ assert 'task in ("classifier", "reranker", "cross_encoder")' in src
# Instantiation expression — not just the class name.
assert "ClassifierTrainerWrapper(cfg, **trainer_kwargs)" in src
diff --git a/tests/test_v07112.py b/tests/test_v07112.py
index 88847298..0a0a01d0 100644
--- a/tests/test_v07112.py
+++ b/tests/test_v07112.py
@@ -1012,8 +1012,12 @@ class TestPatchInvariants:
import inspect
from soup_cli.commands import train
+ from soup_cli.trainer import dispatch
- src = inspect.getsource(train)
+ # #1213 moved the chain into the dispatch both commands call, so the
+ # branch is read there and the command is checked to still reach it.
+ assert "build_trainer(" in inspect.getsource(train)
+ src = inspect.getsource(dispatch)
assert "moe_lora_routing" in src
assert "MoleRoutingTrainerWrapper" in src
diff --git a/tests/test_v07120.py b/tests/test_v07120.py
index 2d83e1b2..2d957b36 100644
--- a/tests/test_v07120.py
+++ b/tests/test_v07120.py
@@ -351,8 +351,11 @@ class TestTtsSchemaAndRouting:
assert cfg.training.tts_family == "orpheus"
def test_train_routes_tts(self):
- src = (_SRC / "commands" / "train.py").read_text(encoding="utf-8")
- assert 'cfg.task == "tts"' in src
+ # #1213 — the routing chain moved into the dispatch both commands call.
+ train_src = (_SRC / "commands" / "train.py").read_text(encoding="utf-8")
+ assert "build_trainer(" in train_src
+ src = (_SRC / "trainer" / "dispatch.py").read_text(encoding="utf-8")
+ assert 'task == "tts"' in src
assert "TTSTrainerWrapper" in src
def test_utils_tts_no_top_level_torch(self):
diff --git a/tests/test_v07131.py b/tests/test_v07131.py
index 54f10980..2c247dff 100644
--- a/tests/test_v07131.py
+++ b/tests/test_v07131.py
@@ -712,14 +712,17 @@ class TestBuildJudgeOrReward:
class TestOnlineDpoRouting:
def test_train_routes_online_dpo(self):
- # A distinct-string `elif cfg.task == ...` branch (cannot be shadowed by
- # another equality branch) that instantiates the wrapper.
+ # A distinct-string `task == ...` branch (cannot be shadowed by another
+ # equality branch) that instantiates the wrapper. #1213 moved the chain
+ # into the dispatch both commands call, so the branch is read there.
import inspect
from soup_cli.commands import train as train_cmd
+ from soup_cli.trainer import dispatch as dispatch_mod
- src = inspect.getsource(train_cmd)
- assert 'elif cfg.task == "online_dpo":' in src
+ assert "build_trainer(" in inspect.getsource(train_cmd)
+ src = inspect.getsource(dispatch_mod)
+ assert 'task == "online_dpo"' in src
assert "OnlineDPOTrainerWrapper(cfg, **trainer_kwargs)" in src
diff --git a/tests/test_v07132.py b/tests/test_v07132.py
index f4a0753b..1c59d80b 100644
--- a/tests/test_v07132.py
+++ b/tests/test_v07132.py
@@ -738,9 +738,12 @@ class TestAsrRouting:
import inspect
import soup_cli.commands.train as train_mod
+ from soup_cli.trainer import dispatch as dispatch_mod
- src = inspect.getsource(train_mod)
- assert 'cfg.task == "asr"' in src
+ # #1213 — routing lives in the dispatch both commands call now.
+ assert "build_trainer(" in inspect.getsource(train_mod)
+ src = inspect.getsource(dispatch_mod)
+ assert 'task == "asr"' in src
assert "AsrTrainerWrapper" in src