Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(recipes): soup recipes verify — attach every shipped config on the meta device (#1116) (#1117)
Srinivasan Rddf8de935897
diff --git a/changelog.d/0.75.1/1117.added.md b/changelog.d/0.75.1/1117.added.mdnew file mode 100644index 00000000..98fb1704--- /dev/null+++ b/changelog.d/0.75.1/1117.added.md@@ -0,0 +1,16 @@+- **`soup recipes verify` checks that a config can attach a LoRA adapter, without downloading weights (#1116 by @Srinivasan8888 in #1117).**+ It builds each base's architecture on the meta device from `config.json` alone, with the+ model class that config's trainer loads (only SFT chooses it by `modality`), then builds+ the adapter config the way the trainer does — `training.moe_lora` included — and runs+ the real peft attach with the config's own LoRA settings. `soup recipes verify` checks+ every shipped recipe, template and example (`--no-templates` limits it to the recipes);+ `--config soup.yaml` checks one before a long download; `--json` emits machine-readable+ rows. Exit codes follow the gate/verdict contract: 0 when everything checkable attaches,+ 2 when a config cannot attach, 3 for a bad flag or a missing or unparseable `--config`,+ and 1 for a crash or a missing or broken `torch` / `transformers` / `peft` (it names+ `pip install "soup-cli[train]"`). Text from a config is printed safely: markup prints+ literally and control bytes are stripped. `task: asr` without `asr_lora` reports no+ adapter, as that trainer full-fine-tunes, and the target resolver's advisories go to+ stderr, so `--json` stdout stays a document. A gated repo, one needing+ `trust_remote_code`, or a config this `transformers` cannot read is reported as+ unverified rather than broken, and remote code is never executed.diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 341faf0c..a818f1db 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -459,6 +459,11 @@ soup recipes search "reasoning"soup recipes search --size 7bsoup recipes search "medical"soup recipes search "vision"++# Check every shipped config can attach its LoRA adapter (no weights downloaded)+soup recipes verify+soup recipes verify --config soup.yaml+soup recipes verify --json # one row per config on stdout, for CI```**What's covered:**diff --git a/docs/commands.md b/docs/commands.mdindex 3ad8d27c..ef95cd2a 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -181,6 +181,10 @@ soup recipes list List all 174 ready-made recipessoup recipes show llama3.1-8b-sft Print recipe YAMLsoup recipes use llama3.1-8b-sft Copy recipe to soup.yamlsoup recipes search "reasoning" Search by keyword/task/size+soup recipes verify Attach every shipped config on the meta device; exit 2 if one cannot (#1116)+soup recipes verify --config soup.yaml Same check for one config, before downloading weights+soup recipes verify --no-templates Recipes only; skip src/soup_cli/templates and examples/+soup recipes verify --json One JSON row per config on stdout; advisories go to stderrsoup registry push --run-id <id> --name n --tag v1 Register runsoup registry list [--name n] [--tag v1] List registry entriessoup registry show <ref> Entry details + artifacts + ancestors@@ -490,7 +494,7 @@ Soup gate and verdict commands follow a unified, CI-friendly exit-code contract:| `3` | `EXIT_USAGE_ERROR` | USAGE / INPUT / CONFIG ERROR | Bad or invalid CLI flag; missing or unparseable input file; empty series || `1` | `EXIT_RUNTIME_ERROR` | RUNTIME ERROR | Unexpected crash, environment incompatibility, or live inference error |-The taxonomy applies consistently across `soup ship`, `soup eval gate`, `soup eval against`, `soup eval checklist`, `soup eval behavior`, `soup eval quant-check`, `soup lock check`, `soup expect`, `soup data validate`, and `soup data lint`.+The taxonomy applies consistently across `soup ship`, `soup eval gate`, `soup eval against`, `soup eval checklist`, `soup eval behavior`, `soup eval quant-check`, `soup lock check`, `soup expect`, `soup data validate`, `soup data lint`, and `soup recipes verify`.`soup eval checklist` requires `--evidence`. `soup eval behavior` also requires`--evidence` unless `--base-model` selects the live path. Omitting the requireddiff --git a/src/soup_cli/commands/recipes.py b/src/soup_cli/commands/recipes.pyindex e26a5179..65f33ea0 100644--- a/src/soup_cli/commands/recipes.py+++ b/src/soup_cli/commands/recipes.py@@ -9,7 +9,13 @@ from rich.panel import Panelfrom rich.syntax import Syntaxfrom rich.table import Table+from soup_cli.utils.exit_codes import GateCommand+from soup_cli.utils.terminal import for_terminal+console = Console()+#: Diagnostics for ``verify``. They go to stderr so that ``--json`` leaves stdout+#: as nothing but the JSON document -- a skipped config is a note, not a result.+err_console = Console(stderr=True)app = typer.Typer(no_args_is_help=True)@@ -135,6 +141,199 @@ def search(console.print(table)[email protected](cls=GateCommand)+def verify(+ config: Optional[str] = typer.Option(+ None, "--config", "-c",+ help="Verify one config instead of the whole catalogue.",+ ),+ json_out: bool = typer.Option(+ False, "--json", help="Machine-readable rows on stdout."+ ),+ templates: bool = typer.Option(+ True, "--templates/--no-templates",+ help="Also verify src/soup_cli/templates and examples/ (catalogue mode).",+ ),+):+ """Check that a config can attach a LoRA adapter, without downloading weights.++ Builds each base's architecture on the meta device from config.json alone,+ then runs Soup's own target resolution and the real peft attach. Exit codes+ follow the gate/verdict contract: 0 when everything that could be checked+ attaches, 2 when a config cannot attach, 3 for a missing or unparseable+ --config, 1 for a crash. A gated repo, or one needing trust_remote_code, is+ reported as unverified and does not change the exit code (#1116).+ """+ import contextlib+ import importlib+ import json as _json+ import sys++ from soup_cli.utils.exit_codes import EXIT_RUNTIME_ERROR++ # #1117 review: without these the per-stage catch-alls turned a missing+ # library into a verdict (unverified, exit 0; or cannot_attach, exit 2).+ # A missing or broken dependency is an environment problem: exit 1, naming+ # the fix. Import, not find_spec: an installed torch whose DLL will not load+ # is found but raises (an OSError on Windows, hence Exception).+ for name in ("torch", "transformers", "peft"):+ try:+ importlib.import_module(name)+ except Exception as exc: # noqa: BLE001+ err_console.print(+ f"[red]soup recipes verify needs {name}, which failed to import:[/] "+ f"{for_terminal(type(exc).__name__)}: {for_terminal(str(exc))}. "+ # \\[ -- Rich reads a bare [train] as a markup tag and drops it.+ 'Install it with: pip install "soup-cli\\[train]"'+ )+ raise typer.Exit(EXIT_RUNTIME_ERROR) from None++ from soup_cli.utils.attach_preflight import (+ PreflightReport,+ Verdict,+ build_on_meta,+ check_attach,+ load_hf_config,+ )+ from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR++ # The config loader prints its own warnings (a deprecated value, #759; a+ # staged field, #808) on stdout, ahead of --json's document. Send them to+ # stderr with every other diagnostic.+ with contextlib.redirect_stdout(sys.stderr):+ configs = _configs_to_verify(config, templates)+ if not configs:+ err_console.print("[red]Nothing to verify.[/]")+ raise typer.Exit(EXIT_USAGE_ERROR)++ report = PreflightReport()+ for name, cfg in configs:+ report.checks.append(+ check_attach(+ name, cfg, load_hf_config=load_hf_config, build_model=build_on_meta,+ # stderr: the resolver's partial-coverage advisory must not land+ # in --json's stdout (#1117 review, after #1164).+ console=err_console,+ )+ )++ if json_out:+ # Plain stdout, not console.print_json: Rich syntax-colours JSON, and+ # under FORCE_COLOR (set by many CI runners) the escape codes make the+ # document unparseable. Same reason as ``soup adapters audit --json``.+ typer.echo(+ _json.dumps(+ [+ {+ "name": c.name, "base": c.base, "task": c.task,+ "verdict": c.verdict.value, "model_type": c.model_type,+ "adapted": c.adapted, "expert_modules": c.expert_modules,+ "vision_modules": c.vision_modules, "detail": c.detail,+ }+ for c in report.checks+ ],+ indent=2,+ )+ )+ else:+ _print_preflight(report, Verdict)+ raise typer.Exit(report.exit_code)+++def _configs_to_verify(config: Optional[str], templates: bool):+ """``(name, SoupConfig)`` for everything in scope; a config that will not+ parse is surfaced here rather than counted as an attach failure."""+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR++ pairs: list[tuple[str, str]] = []+ if config:+ path = Path(config)+ if not path.is_file():+ err_console.print(f"[red]Config not found:[/] {for_terminal(config)}")+ raise typer.Exit(EXIT_USAGE_ERROR)+ try:+ return [(path.name, load_config_from_string(path.read_text(encoding="utf-8")))]+ except Exception as exc: # noqa: BLE001 --- any parse failure is an input error+ first_line = str(exc).splitlines()[0] if str(exc) else ""+ err_console.print(+ f"[red]Config does not parse:[/] {for_terminal(config)}: "+ f"{for_terminal(type(exc).__name__)}: {for_terminal(first_line)}"+ )+ raise typer.Exit(EXIT_USAGE_ERROR) from None+ else:+ from soup_cli.recipes.catalog import RECIPES++ pairs.extend((name, recipe.yaml_str) for name, recipe in RECIPES.items())+ if templates:+ root = Path(__file__).resolve().parents[1]+ for base in (root / "templates", root.parents[1] / "examples"):+ if base.is_dir():+ pairs.extend(+ (p.relative_to(base.parent).as_posix(), p.read_text(encoding="utf-8"))+ for p in sorted(base.rglob("*.yaml"))+ )++ loaded = []+ for name, text in pairs:+ try:+ loaded.append((name, load_config_from_string(text)))+ except Exception as exc: # noqa: BLE001 --- a parse failure is #330's job+ err_console.print(+ f"[dim]skipped {for_terminal(name)}: does not parse ({type(exc).__name__})[/]"+ )+ return loaded+++def _print_preflight(report, verdict_cls) -> None:+ """One row per config that did not simply attach, then the counts.++ Printing every green row buries the ones that matter, so ATTACHES is summarised+ and everything else is listed.+ """+ failures = report.failures+ unverified = report.by_verdict(verdict_cls.UNVERIFIED)++ if failures:+ table = Table(title="Cannot attach")+ table.add_column("Config", style="bold cyan")+ table.add_column("model_type", style="magenta")+ table.add_column("Stage", style="yellow")+ table.add_column("Why")+ for check in failures:+ # Every cell can carry config text (peft quotes target_modules+ # verbatim): markup would crash the report or restyle it, and a raw+ # ESC would reach the terminal (#1117 review).+ table.add_row(+ for_terminal(check.name), for_terminal(check.model_type),+ for_terminal(check.stage), for_terminal(check.detail[:90]),+ )+ console.print(table)++ if unverified:+ console.print(+ f"[yellow]{len(unverified)} config(s) could not be checked here[/] "+ "[dim](gated, remote code, or unreadable by this transformers) — "+ "not counted as failures.[/]"+ )++ attaches = report.by_verdict(verdict_cls.ATTACHES)+ experts = sum(1 for c in attaches if c.expert_modules)+ vision = [c.name for c in attaches if c.vision_modules]+ console.print(+ f"[green]{len(attaches)} attach[/], "+ f"[red]{len(failures)} cannot[/], "+ f"{len(report.by_verdict(verdict_cls.NO_ADAPTER))} have no adapter, "+ f"{len(unverified)} unverified."+ )+ if experts:+ console.print(f"[dim]{experts} of them adapted expert modules.[/]")+ if vision:+ console.print(+ f"[yellow]adapted a vision tower:[/] {for_terminal(', '.join(vision))}"+ )++def _suggest_recipes(query: str, n: int = 3) -> list[str]:"""v0.40.1 Part E / M3 — return up to ``n`` close-matching recipe ids."""from difflib import get_close_matchesdiff --git a/src/soup_cli/utils/attach_preflight.py b/src/soup_cli/utils/attach_preflight.pynew file mode 100644index 00000000..865b2d6d--- /dev/null+++ b/src/soup_cli/utils/attach_preflight.py@@ -0,0 +1,496 @@+"""Can a shipped config attach a LoRA adapter at all? (#1116)++A config can parse through the schema, name a repo that resolves on the Hub, and+still be untrainable: ``target_modules: auto`` resolves to nothing for an+architecture neither Soup nor peft maps, and ``get_peft_model`` raises. Nothing+checked that until now --- ``validate-recipes`` (#330) parses YAML,+``check_recipe_repo_ids`` (#677) resolves repo ids, ``soup doctor --config``+(#903) reads a declared table, and ``soup adapters audit`` (#763) runs after+training. #1070 (every shipped MoE recipe), #798's dropout refusal and #1074's+``templates/moe.yaml`` blocker were each found by a person reading code.++The check builds the architecture on the **meta device** from ``config.json``+alone --- no weights, no download of a checkpoint, no GPU --- and then runs+Soup's own target resolution and the real ``get_peft_model``. The verdict is+therefore the trainer's verdict rather than a re-implementation of it.++Two disciplines carried over from #677, because without them a guard becomes+noise and gets muted:++**A failure to load the architecture is not a failure to attach.** A gated repo,+a repo needing ``trust_remote_code``, and a config this ``transformers`` cannot+read are all :data:`Verdict.UNVERIFIED` --- "could not check" --- never+:data:`Verdict.CANNOT_ATTACH`. Whether such a repo is missing is #677's+question, and answering it here in a second voice is how two guards disagree.++**Remote code is never executed.** ``trust_remote_code`` stays off, and a repo+that needs it reports as unverifiable. A preflight that runs arbitrary code from+the Hub to decide whether a recipe is healthy is a worse problem than the one it+solves.+"""++from __future__ import annotations++import enum+from dataclasses import dataclass, field+from typing import Any, Callable, Optional++#: Layers are cut to this many before the model is built. Every module peft+#: matches on is per-layer and identically named in layer 0 and layer 40, so the+#: attach is unchanged --- and a 671B config becomes a skeleton that builds in+#: milliseconds.+PREFLIGHT_LAYERS = 2+++class Verdict(enum.Enum):+ """Four outcomes, not two. Collapsing UNVERIFIED into CANNOT_ATTACH reports+ every gated repo as a broken recipe, which is how a guard gets muted."""++ ATTACHES = "attaches"+ NO_ADAPTER = "no_adapter"+ CANNOT_ATTACH = "cannot_attach"+ UNVERIFIED = "unverified"+++@dataclass(frozen=True)+class AttachCheck:+ """One config's result. ``detail`` always says *why* for a non-ATTACHES+ verdict, because a bare verdict sends the reader back to the code."""++ name: str+ base: str+ task: str+ verdict: Verdict+ detail: str = ""+ model_type: Optional[str] = None+ adapted: int = 0+ expert_modules: int = 0+ vision_modules: int = 0+ targets: Any = None+ stage: str = ""+++#: Substrings that mean "this config could not be loaded", mapped to the reason.+#: Matched against the exception text only (``transformers`` raises plain+#: ``ValueError``/``OSError`` for all of them), first match wins, so the ORDER is+#: the #677 lesson: "gated repo" goes first, ahead of "is not a local folder",+#: so a gated repo is never filed as an unresolvable id if one message ever+#: carries both.+_UNVERIFIABLE_MARKERS: tuple[tuple[str, str], ...] = (+ ("gated repo", "gated repo; set HF_TOKEN to check it"),+ ("trust_remote_code", "needs trust_remote_code, which this check never enables"),+ ("custom code", "needs trust_remote_code, which this check never enables"),+ ("Unrecognized model", "this transformers cannot read the config"),+ ("does not appear to have a file named config.json", "no config.json in the repo"),+ ("is not a local folder", "repo id does not resolve anonymously (see #677)"),+)+++def classify_load_failure(exc: BaseException) -> str:+ """Why a base's config could not be loaded, in words, or "" if unrecognised.++ Kept separate from the check so the mapping is testable without a model, and+ so an unrecognised failure is visible as an empty string rather than being+ silently filed under the last branch.+ """+ for marker, reason in _UNVERIFIABLE_MARKERS:+ if marker in str(exc):+ return reason+ return ""+++def shrink_for_preflight(hf_config: Any, layers: int = PREFLIGHT_LAYERS) -> Any:+ """Cut every sub-config's layer count, in place, and return the config.++ Sub-configs matter: a vision-language wrapper keeps the text tower's depth in+ ``text_config``, and leaving that at 61 builds 61 layers of a model whose+ module names repeat after the first.+ """+ targets = [hf_config]+ for attribute in ("text_config", "vision_config", "audio_config"):+ sub = getattr(hf_config, attribute, None)+ if sub is not None:+ targets.append(sub)+ for target in targets:+ current = getattr(target, "num_hidden_layers", None)+ if isinstance(current, int) and current > layers:+ target.num_hidden_layers = max(+ layers,+ _first_sparse_depth(target, current),+ _first_of_each_kind_depth(target, current),+ )+ return hf_config+++def _first_of_each_kind_depth(config: Any, current: int) -> int:+ """Layers needed to include one layer of every kind in ``layer_types``.++ A hybrid decoder (Granite 4.0-H, Qwen3.5) puts attention at only some depths:+ two layers kept only Mamba or linear-attention layers, so ``q_proj`` was+ reported missing on a config the trainer attaches (#1117 review).+ """+ kinds = getattr(config, "layer_types", None)+ if not isinstance(kinds, (list, tuple)) or not kinds:+ return 0+ first: dict = {}+ for index, kind in enumerate(kinds[:current]):+ first.setdefault(kind, index)+ return max(first.values()) + 1+++def _first_sparse_depth(config: Any, current: int) -> int:+ """Layers needed to include the first MoE layer, or 0 for a dense config.++ A shrink to two layers kept only dense layers on DeepSeek-V3 and GLM-5.1+ (``first_k_dense_replace: 3``), so their ``moe_lora`` recipes were reported as+ attaching with no expert ever built (found by a local CodeRabbit review).+ Each rule is the one the architecture's own modeling code applies.+ """+ first_dense = getattr(config, "first_k_dense_replace", None)+ moe_freq = getattr(config, "moe_layer_freq", None)+ sparse_step = getattr(config, "decoder_sparse_step", None)+ interleave = getattr(config, "interleave_moe_layer_step", None)+ mlp_only = getattr(config, "mlp_only_layers", None) or []+ fields = (first_dense, moe_freq, sparse_step, interleave)+ if not any(isinstance(v, int) and v > 0 for v in fields):+ return 0++ def is_sparse(i: int) -> bool:+ if i in mlp_only:+ return False+ if isinstance(first_dense, int) and i < first_dense:+ return False+ if isinstance(moe_freq, int) and moe_freq > 0 and i % moe_freq != 0:+ return False+ if isinstance(sparse_step, int) and sparse_step > 0 and (i + 1) % sparse_step != 0:+ return False+ if isinstance(interleave, int) and interleave > 0 and (i + 1) % interleave != 0:+ return False+ return True++ for i in range(current):+ if is_sparse(i):+ return i + 1+ return 0+++def count_adapted(model: Any) -> tuple[int, int, int]:+ """``(adapted, expert modules, vision modules)`` for an attached model.++ The two breakdowns are what make the report say something a bare count+ cannot: whether a MoE config reached its experts, and whether a+ vision-language config quietly adapted its image encoder during a text+ fine-tune.+ """+ # ``.lora_A`` is the ModuleDict peft inserts once per adapted base module.+ # Counting ``lora_A.default`` as well double-counts every one of them, and+ # counting ONLY ``lora_A.default`` silently misses a non-default adapter+ # name -- peft names the inner Linear after the adapter.+ names = [name for name, _ in model.named_modules() if name.endswith(".lora_A")]+ experts = sum(1 for name in names if "expert" in name)+ vision = sum(1 for name in names if "vision" in name or "visual" in name)+ return len(names), experts, vision+++_NO_ADAPTER_TASKS = {+ "prm": "the prm trainer full-fine-tunes and builds no adapter",+ "moe_lora_routing": "moe_lora_routing loads existing adapters and builds none",+}+_CLASSIFIER_TASKS = frozenset({"classifier", "reranker", "cross_encoder"})+++def plan_adapter(cfg: Any) -> tuple[bool, str]:+ """``(has an adapter to attach, why not)``, without touching the network.++ ``lora.r: 0`` is full fine-tuning (#700) and MLX attaches through a different+ path entirely, so neither is a failure --- and reporting them as one would+ put 3 permanent red rows in a report meant to be all green.+ """+ if getattr(cfg, "backend", None) == "mlx":+ return False, "mlx backend attaches through a different path"+ tcfg = getattr(cfg, "training", None)+ lora = getattr(tcfg, "lora", None)+ if lora is None or not getattr(lora, "r", 0):+ return False, "lora.r: 0 --- full fine-tuning, no adapter"+ task = getattr(cfg, "task", "")+ # Trainers that never build an adapter, whatever lora.r says: answering for one+ # would report on an adapter the run does not have.+ if task in _NO_ADAPTER_TASKS:+ return False, _NO_ADAPTER_TASKS[task]+ if task in _CLASSIFIER_TASKS and not getattr(tcfg, "classifier_lora", False):+ return False, "classifier_lora is off --- that trainer full-fine-tunes"+ if task == "asr" and not getattr(tcfg, "asr_lora", False):+ # trainer/asr.py attaches only with asr_lora on (and r > 0, checked above).+ return False, "asr_lora is off --- that trainer full-fine-tunes"+ return True, ""+++def check_attach(+ name: str,+ cfg: Any,+ *,+ load_hf_config: Callable[[str], Any],+ build_model: Callable[[Any, str], Any],+ attach: Optional[Callable[[Any, Any], Any]] = None,+ console: Any = None,+) -> AttachCheck:+ """Run one config through resolution and attach; never raise.++ ``load_hf_config`` and ``build_model`` are injected so the decision logic is+ testable without the Hub. The target resolution is deliberately NOT+ injectable --- it is :func:`trainer_lora_config`, the trainer's own sequence+ --- and ``attach`` defaults to the real ``get_peft_model``: stubbing either+ would make this check assert its own beliefs about peft and the trainer+ rather than their behaviour, which is the #826 mistake.+ """+ base = getattr(cfg, "base", "")+ task = getattr(cfg, "task", "")+ row = dict(name=name, base=base, task=task)++ wanted, why_not = plan_adapter(cfg)+ if not wanted:+ return AttachCheck(**row, verdict=Verdict.NO_ADAPTER, detail=why_not)++ try:+ hf_config = load_hf_config(base)+ except Exception as exc: # noqa: BLE001 --- every loader failure is a verdict+ reason = classify_load_failure(exc) or f"{type(exc).__name__}: {exc}"+ return AttachCheck(+ **row, verdict=Verdict.UNVERIFIED, detail=reason, stage="config"+ )++ model_type = getattr(hf_config, "model_type", None)+ row["model_type"] = model_type+ try:+ model = build_model(shrink_for_preflight(hf_config), loader_for(cfg))+ except Exception as exc: # noqa: BLE001+ reason = classify_load_failure(exc)+ return AttachCheck(+ **row,+ verdict=Verdict.UNVERIFIED if reason else Verdict.CANNOT_ATTACH,+ detail=reason or f"{type(exc).__name__}: {exc}",+ stage="build",+ )++ try:+ peft_config, targets = trainer_lora_config(model, cfg, console)+ except Exception as exc: # noqa: BLE001 --- Soup's own refusals land here+ return AttachCheck(+ **row,+ verdict=Verdict.CANNOT_ATTACH,+ detail=f"{type(exc).__name__}: {exc}",+ stage="resolve",+ )++ if attach is None:+ attach = _attach_with_peft+ try:+ attached = attach(model, peft_config)+ except Exception as exc: # noqa: BLE001+ return AttachCheck(+ **row,+ verdict=Verdict.CANNOT_ATTACH,+ detail=f"{type(exc).__name__}: {exc}",+ targets=targets,+ stage="attach",+ )++ adapted, experts, vision = count_adapted(attached)+ return AttachCheck(+ **row,+ verdict=Verdict.ATTACHES if adapted else Verdict.CANNOT_ATTACH,+ detail="" if adapted else "peft attached, but no module carries an adapter",+ adapted=adapted,+ expert_modules=experts,+ vision_modules=vision,+ targets=targets,+ stage="attach",+ )+++def trainer_lora_config(model: Any, cfg: Any, console: Any = None) -> tuple[Any, Any]:+ """The adapter config a LoRA trainer builds, in the order it builds it.++ ``resolve_lora_target_modules`` -> ``resolve_lora_target_parameters`` ->+ the ``moe_lora`` override -> ``build_lora_config``: the same four calls, in the+ same order, as ``trainer/sft.py`` and the other MoE-wired trainers. The first+ version of this check stopped after the first call and built its own+ ``LoraConfig``, so a recipe with ``moe_lora: true`` -- which the trainer+ rescues by replacing ``target_modules`` -- was reported unable to attach while+ the real trainer attached it. Measured on ``qwen3-30b-a3b-sft``: this check+ said FAILS, the trainer's path attached 12 modules.++ The config's OWN r / alpha / dropout go in unchanged: normalising them to a+ tidy ``dropout: 0.0`` would have hidden #798, whose dropout was the schema+ default the recipes inherited.++ ``task_type`` is left unset: a task head wants a loaded model+ (``prepare_inputs_for_generation`` and friends), and the adapter injection is+ what is under test, not the head.++ ``moe_lora`` is applied for every task that reaches this sequence: #1148 and+ #1179 wired every trainer that builds an adapter, and config load refuses it+ where none is built. ``asr`` takes its own path above. The one split by+ modality is SFT's: its vision and audio branches (``_setup_vision_transformers``,+ ``_setup_audio_transformers``) call only ``resolve_lora_target_modules`` and+ ``build_lora_config``, so for those the MoE and ``target_parameters`` steps are+ skipped here too -- the same split :func:`loader_for` makes for the class.+ ``classifier`` (with ``classifier_lora``), ``distill`` and ``unlearn`` run the+ resolver, the MoE step and ``build_lora_config`` but never+ ``resolve_lora_target_parameters``, which this sequence runs for them too. No+ shipped config sets ``lora.target_parameters``, so no verdict depends on the+ difference today.+ """+ from soup_cli.utils.moe import resolve_moe_lora_targets+ from soup_cli.utils.peft_wiring import (+ build_lora_config,+ resolve_lora_target_modules,+ resolve_lora_target_parameters,+ )++ tcfg = cfg.training+ lora = tcfg.lora+ if getattr(cfg, "task", "") == "asr":+ # trainer/asr.py never calls the resolver: auto means Whisper's q/v.+ targets = lora.target_modules+ if targets == "auto":+ targets = ["q_proj", "v_proj"]+ return build_lora_config(lora, target_modules=targets, task_type=None), targets+ targets = resolve_lora_target_modules(model, lora.target_modules, console)+ if getattr(cfg, "task", "") == "sft" and getattr(cfg, "modality", "text") in (+ "vision", "audio",+ ):+ # SFT's vision and audio branches make only these two calls: no MoE+ # rescue and no target_parameters. Report what that path attaches.+ peft_config = build_lora_config(lora, target_modules=targets, task_type=None)+ return peft_config, targets+ target_parameters = resolve_lora_target_parameters(+ model, getattr(lora, "target_parameters", None)+ )+ # No console: its "targeting N module patterns" line names no config, so in+ # catalogue mode it is noise on stderr (#1117 review). The verdict is the same.+ targets = resolve_moe_lora_targets(model, tcfg, targets, None)+ peft_config = build_lora_config(+ lora,+ target_modules=targets,+ task_type=None,+ target_parameters=target_parameters,+ )+ return peft_config, targets+++def _attach_with_peft(model: Any, peft_config: Any) -> Any:+ """The real ``get_peft_model``, on the config the trainer would build."""+ from peft import get_peft_model++ return get_peft_model(model, peft_config)+++@dataclass+class PreflightReport:+ """Every row, plus the one question CI asks: did anything fail to attach?"""++ checks: list[AttachCheck] = field(default_factory=list)++ def by_verdict(self, verdict: Verdict) -> list[AttachCheck]:+ return [check for check in self.checks if check.verdict is verdict]++ @property+ def failures(self) -> list[AttachCheck]:+ return self.by_verdict(Verdict.CANNOT_ATTACH)++ @property+ def exit_code(self) -> int:+ """``EXIT_GATE_FAILED`` (2) only for CANNOT_ATTACH, the gate/verdict+ contract. An unverifiable config is not a failure --- it is a config this+ machine could not answer for."""+ from soup_cli.utils.exit_codes import EXIT_GATE_FAILED, EXIT_OK++ return EXIT_GATE_FAILED if self.failures else EXIT_OK+++#: The auto-class each trainer loads, read off the trainers rather than guessed.+#: SFT chooses by MODALITY, not task -- ``trainer/sft.py`` loads a causal LM for+#: text, ``AutoModelForImageTextToText`` for vision and ``AutoModel`` for audio --+#: so keying this on the task alone built every vision recipe as a causal LM.+_MODALITY_AUTO_CLASS = {+ "vision": ("AutoModelForImageTextToText",),+ "audio": ("AutoModel",),+}+_TASK_AUTO_CLASS = {+ "embedding": ("AutoModel",),+ "reward_model": ("AutoModelForSequenceClassification",),+ # trainer/classifier.py serves all three.+ "classifier": ("AutoModelForSequenceClassification",),+ "reranker": ("AutoModelForSequenceClassification",),+ "cross_encoder": ("AutoModelForSequenceClassification",),+ # trainer/asr.py loads the Whisper seq2seq class by name, not an auto-class.+ "asr": ("WhisperForConditionalGeneration",),+}+#: Only SFT reads ``modality`` (#1117 review): every other trainer loads its one+#: class whatever the config says, so a vision DPO config is a causal LM there.+_MODALITY_TASKS = frozenset({"sft"})+#: ONE class per path, with no fallback, because no trainer has one. My first+#: version fell back from ``AutoModelForCausalLM`` to ``AutoModel``, so a config+#: the causal-LM class refuses -- MiniMax-M3 with no ``modality``, which cannot load+#: in SFT at all (#1145) -- was built one level down and reported as attaching.+#: That is the failure the #1116 ruling named: a preflight instantiating at a+#: different level from the trainer reports green on a config that cannot attach.+_DEFAULT_AUTO_CLASS = ("AutoModelForCausalLM",)+++def loader_for(cfg: Any) -> tuple[str, ...]:+ """The auto-classes to try, in the order the config's trainer would.++ A task with its own class wins. After that only SFT lets ``modality`` choose+ (``trainer/sft.py`` is the one trainer that reads it); every other task loads+ a causal LM, so answering by modality there reported a vision DPO config as+ attaching while DPO's own ``AutoModelForCausalLM`` refused it (#1117 review).+ """+ task = getattr(cfg, "task", "")+ if task in _TASK_AUTO_CLASS:+ return _TASK_AUTO_CLASS[task]+ if task not in _MODALITY_TASKS:+ return _DEFAULT_AUTO_CLASS+ return _MODALITY_AUTO_CLASS.get(getattr(cfg, "modality", "text"), _DEFAULT_AUTO_CLASS)+++def load_hf_config(base: str) -> Any:+ """``config.json`` alone, anonymously, with remote code refused."""+ from transformers import AutoConfig++ return AutoConfig.from_pretrained(base, trust_remote_code=False)+++def build_on_meta(hf_config: Any, classes: tuple[str, ...]) -> Any:+ """Instantiate the architecture with no storage behind any parameter.++ ``classes`` comes from :func:`loader_for`, tried in order; the last error is+ raised if none works, so the report says which class refused rather than+ "could not build".+ """+ import torch+ import transformers++ last: Optional[BaseException] = None+ for class_name in classes:+ factory = getattr(transformers, class_name, None)+ if factory is None:+ continue+ try:+ with torch.device("meta"):+ # trust_remote_code=False explicitly. Omitted, transformers does+ # not refuse a custom-code architecture -- it PROMPTS on stdin+ # ("Do you wish to run the custom code? [y/N]"), which hangs a+ # terminal, corrupts --json on stdout, and runs remote code for+ # anyone who answers y. load_hf_config passing False is not+ # enough: a config can load while its modeling code is remote+ # (Kimi-K2.5 does exactly this).+ if hasattr(factory, "from_config"):+ return factory.from_config(hf_config, trust_remote_code=False)+ # A concrete class (asr's WhisperForConditionalGeneration) has no+ # from_config and no remote code: the trainer constructs it by name.+ return factory(hf_config)+ except Exception as exc: # noqa: BLE001 --- try the next class+ last = exc+ raise last if last is not None else RuntimeError("no model class available")diff --git a/tests/test_issue1116_attach_preflight.py b/tests/test_issue1116_attach_preflight.pynew file mode 100644index 00000000..ef819865--- /dev/null+++ b/tests/test_issue1116_attach_preflight.py@@ -0,0 +1,1362 @@+"""#1116: can every shipped config actually attach a LoRA adapter?++A config can parse (#330), name a repo that resolves (#677), and still be+untrainable, because `target_modules: auto` resolves to nothing for an+architecture neither Soup nor peft maps. #1070 (every shipped MoE recipe),+#798's dropout refusal and #1074's `templates/moe.yaml` blocker were each found+by a person reading code, not by a check.++Two rules are load-bearing and are pinned hardest here, because breaking either+turns the guard into noise that gets muted:++1. **A failure to LOAD is not a failure to ATTACH.** Gated, remote-code and+ unreadable configs are UNVERIFIED, never CANNOT_ATTACH, and never change the+ exit code. On a box with no `HF_TOKEN` that is most of the gated bases in+ the catalogue, so the rule is what keeps CI from going permanently red.+2. **Remote code is never executed**, so a repo needing it is unverifiable+ rather than run.++The end-to-end tests build real `transformers` configs locally and inject them,+so the real resolution and the real `get_peft_model` run with no network.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from soup_cli.utils.attach_preflight import (+ PREFLIGHT_LAYERS,+ AttachCheck,+ PreflightReport,+ Verdict,+ check_attach,+ classify_load_failure,+ count_adapted,+ plan_adapter,+ shrink_for_preflight,+)++transformers = pytest.importorskip("transformers")+pytest.importorskip("peft")+torch = pytest.importorskip("torch")+++def _cfg(+ base="org/m", task="sft", r=8, dropout=0.0, backend=None, targets="auto",+ modality="text",+):+ """A stand-in for the loaded SoupConfig, carrying only what the check reads."""+ return SimpleNamespace(+ base=base,+ task=task,+ modality=modality,+ backend=backend,+ training=SimpleNamespace(+ lora=SimpleNamespace(r=r, alpha=16, dropout=dropout, target_modules=targets)+ ),+ )+++def _real_cfg(r=8, dropout=0.0, targets="auto", moe_lora=False, target_parameters=None):+ """A config loaded through the real schema, for every test that reaches the+ attach. The check now builds the adapter with the trainer's own+ ``build_lora_config``, which reads the whole LoRA block (``use_dora``,+ ``rank_pattern``, the #1037 variants ...), so a hand-built stand-in would be+ testing a config no user can write."""+ import json++ from soup_cli.config.loader import load_config_from_string++ return load_config_from_string(+ "base: org/m\ntask: sft\n"+ "data:\n train: ./x.jsonl\n format: alpaca\n"+ f"training:\n moe_lora: {'true' if moe_lora else 'false'}\n"+ f" lora:\n r: {r}\n alpha: 16\n dropout: {dropout}\n"+ f" target_modules: {json.dumps(targets)}\n"+ + (+ f" target_parameters: {json.dumps(target_parameters)}\n"+ if target_parameters is not None else ""+ )+ )+++class TestLoadFailuresAreNotAttachFailures:+ """Rule 1. Each of these is a config this machine could not answer for."""++ @pytest.mark.parametrize(+ "message, expected_fragment",+ [+ ("You are trying to access a gated repo.", "gated"),+ ("contains custom code which must be executed", "trust_remote_code"),+ (+ "requires you to execute the configuration file... trust_remote_code",+ "trust_remote_code",+ ),+ ("Unrecognized model in org/x. Should have a `model_type`", "cannot read"),+ ("org/x does not appear to have a file named config.json", "no config.json"),+ ("org/x is not a local folder and is not a valid model identifier", "#677"),+ ],+ )+ def test_each_known_loader_failure_is_named(self, message, expected_fragment):+ assert expected_fragment in classify_load_failure(ValueError(message))++ def test_an_unrecognised_failure_returns_empty_not_a_guess(self):+ """Empty is how the caller knows to print the exception instead. Filing an+ unknown failure under the last branch is how a guard starts lying."""+ assert classify_load_failure(ValueError("something entirely new")) == ""++ @pytest.mark.parametrize(+ "message",+ [+ "You are trying to access a gated repo.",+ "contains custom code which must be executed",+ "org/x is not a local folder and is not a valid model identifier",+ ],+ )+ def test_they_verdict_unverified_and_do_not_fail_the_run(self, message):+ def _raise(_base):+ raise OSError(message)++ check = check_attach(+ "r", _cfg(), load_hf_config=_raise, build_model=lambda *_: None+ )++ assert check.verdict is Verdict.UNVERIFIED, check+ assert PreflightReport([check]).exit_code == 0, (+ "an unverifiable config failed the run; on a box with no HF_TOKEN "+ "that is 51 recipes, and the guard gets muted"+ )++ def test_an_unknown_loader_failure_still_does_not_claim_it_cannot_attach(self):+ """The conservative direction: we did not reach the attach, so we do not+ get to say it fails. The message carries the exception verbatim."""+ def _raise(_base):+ raise RuntimeError("hub had a bad minute")++ check = check_attach(+ "r", _cfg(), load_hf_config=_raise, build_model=lambda *_: None+ )++ assert check.verdict is Verdict.UNVERIFIED+ assert "hub had a bad minute" in check.detail++ def test_a_recognised_build_failure_is_also_unverified(self):+ """The same rule one stage later, and the stage my first version of these+ tests missed entirely: ``from_config`` raises "Unrecognized model" for a+ config this transformers cannot build (MiniMax-M3 does exactly this).+ Filing that as CANNOT_ATTACH blames the recipe for the library's age."""+ def _boom(_config, _task):+ raise ValueError("Unrecognized model in org/x. Should have a `model_type`")++ check = check_attach(+ "r", _cfg(), load_hf_config=lambda _b: SimpleNamespace(model_type="x"),+ build_model=_boom,+ )++ assert check.verdict is Verdict.UNVERIFIED, check+ assert check.stage == "build"+ assert PreflightReport([check]).exit_code == 0++ def test_an_unrecognised_build_failure_is_an_attach_failure(self):+ """The other side, so the rule is not "never fail". The config loaded and+ the architecture is known; if it will not instantiate, that is real."""+ def _boom(_config, _task):+ raise TypeError("__init__() missing 1 required argument")++ check = check_attach(+ "r", _cfg(), load_hf_config=lambda _b: SimpleNamespace(model_type="x"),+ build_model=_boom,+ )++ assert check.verdict is Verdict.CANNOT_ATTACH+ assert check.stage == "build"+++class TestNothingToAttach:+ """Neither of these is a failure, and reporting them as one puts permanent+ red rows in a report meant to go green."""++ def test_full_fine_tuning_has_no_adapter(self):+ check = check_attach(+ "r", _cfg(r=0), load_hf_config=_unreachable, build_model=_unreachable+ )++ assert check.verdict is Verdict.NO_ADAPTER+ assert "lora.r" in check.detail++ def test_the_mlx_backend_is_out_of_scope(self):+ check = check_attach(+ "r", _cfg(backend="mlx"),+ load_hf_config=_unreachable, build_model=_unreachable,+ )++ assert check.verdict is Verdict.NO_ADAPTER+ assert "mlx" in check.detail++ def test_neither_touches_the_network(self):+ """Pinned by `_unreachable` above, which raises if called -- the check+ must decide these before it asks the Hub anything."""+ assert plan_adapter(_cfg(r=0))[0] is False+ assert plan_adapter(_cfg(backend="mlx"))[0] is False+ assert plan_adapter(_cfg())[0] is True+++def _unreachable(*_args, **_kwargs):+ raise AssertionError("the check reached the network for a config with no adapter")+++class TestTheLoaderMatchesTheTrainer:+ """The class a config is built with has to be the one its trainer loads, or+ the verdict is about a different model. SFT picks by MODALITY+ (``trainer/sft.py``: causal LM for text, ``AutoModelForImageTextToText`` for+ vision, ``AutoModel`` for audio); my first version keyed on the task and+ built every vision recipe as a causal LM. It was caught by re-verifying the+ multimodal rows of #1116 against the real loaders, not by these tests --+ which is why these now exist."""++ def test_vision_sft_uses_the_image_text_class(self):+ from soup_cli.utils.attach_preflight import loader_for++ assert loader_for(_cfg(modality="vision")) == ("AutoModelForImageTextToText",)++ def test_audio_sft_uses_the_bare_model(self):+ from soup_cli.utils.attach_preflight import loader_for++ assert loader_for(_cfg(modality="audio")) == ("AutoModel",)++ def test_text_sft_uses_a_causal_lm(self):+ from soup_cli.utils.attach_preflight import loader_for++ # Exact, not [0]: a fallback at [1] is the bug this pins (see+ # test_a_text_config_the_causal_lm_class_refuses_is_not_attached).+ assert loader_for(_cfg()) == ("AutoModelForCausalLM",)++ def test_a_task_with_its_own_head_wins_over_modality(self):+ """An embedding run is ``AutoModel`` whatever the modality says --+ ``trainer/embedding.py`` never loads a causal LM."""+ from soup_cli.utils.attach_preflight import loader_for++ assert loader_for(_cfg(task="embedding")) == ("AutoModel",)+ assert loader_for(_cfg(task="reward_model")) == (+ "AutoModelForSequenceClassification",+ )+++class TestRemoteCodeIsNeverOffered:+ """The module promises remote code is never executed. The first version kept+ that promise for the config and broke it for the model: ``from_config`` was+ called without ``trust_remote_code``, and for a custom-code architecture+ transformers does not refuse -- it PROMPTS on stdin, "Do you wish to run the+ custom code? [y/N]". That hangs a terminal, corrupts ``--json``, and runs+ remote code for anyone who types y. Kimi-K2.5 is the live case: its config+ loads with ``trust_remote_code=False`` while its modeling code is remote.+ Found by running the real command end to end, not by any test here."""++ def test_every_build_passes_trust_remote_code_false(self, monkeypatch):+ from soup_cli.utils import attach_preflight++ seen = []++ def _spy(_config, **kwargs):+ seen.append(kwargs)+ return SimpleNamespace()++ # Patch the method on the real class: ``build_on_meta`` resolves the+ # class through transformers' lazy module, which a module-level setattr+ # does not reliably intercept.+ monkeypatch.setattr(transformers.AutoModelForCausalLM, "from_config", _spy)+ attach_preflight.build_on_meta(SimpleNamespace(), ("AutoModelForCausalLM",))++ assert seen == [{"trust_remote_code": False}], (+ "from_config was called without trust_remote_code=False; transformers "+ "will prompt on stdin for a custom-code architecture"+ )++ def test_the_config_load_refuses_remote_code_too(self, monkeypatch):+ seen = []+ monkeypatch.setattr(+ transformers.AutoConfig, "from_pretrained",+ lambda base, **kwargs: seen.append(kwargs) or SimpleNamespace(),+ )+ from soup_cli.utils.attach_preflight import load_hf_config++ load_hf_config("org/m")++ assert seen == [{"trust_remote_code": False}]+++class TestJsonIsParseable:+ """``--json`` exists for a program to read, so stdout must be the document+ and nothing else."""++ def _invoke(self, tmp_path, monkeypatch, *, force_colour):+ import json as _json++ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.setattr(+ "soup_cli.utils.attach_preflight.check_attach",+ lambda name, cfg, **_k: AttachCheck(+ name, cfg.base, cfg.task, Verdict.ATTACHES, adapted=4+ ),+ )+ if force_colour:+ # The module-level Console is built at import time, so FORCE_COLOR set+ # here would never reach it and the assertion below would pass+ # without testing anything -- which is exactly what my first version+ # did (the print_json mutant survived). Pin a colour-forced console+ # into the module instead; it resolves sys.stdout at write time, so+ # CliRunner still captures it.+ from rich.console import Console++ import soup_cli.commands.recipes as recipes_cmd++ monkeypatch.setattr(recipes_cmd, "console", Console(force_terminal=True))+ good = tmp_path / "soup.yaml"+ good.write_text(+ "base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"+ "training:\n lora:\n r: 8\n",+ encoding="utf-8",+ )+ result = CliRunner().invoke(app, ["recipes", "verify", "--config", str(good), "--json"])+ return result, _json++ def test_stdout_parses_as_json(self, tmp_path, monkeypatch):+ result, json_mod = self._invoke(tmp_path, monkeypatch, force_colour=False)++ rows = json_mod.loads(result.stdout)+ assert rows[0]["verdict"] == "attaches"++ def test_it_still_parses_when_colour_is_forced(self, tmp_path, monkeypatch):+ """Rich's ``print_json`` syntax-colours its output, and under+ ``FORCE_COLOR`` -- which many CI runners set -- the escape codes make the+ document unparseable. Measured: ``json.loads`` raised JSONDecodeError on+ ``print_json`` output with a forced terminal."""+ result, json_mod = self._invoke(tmp_path, monkeypatch, force_colour=True)++ assert "\x1b[" not in result.stdout, "ANSI colour codes in --json output"+ json_mod.loads(result.stdout)+++class TestShrinking:+ def test_sub_configs_are_cut_too(self):+ """A vision-language wrapper keeps the text tower's depth in+ `text_config`; leaving it builds 61 layers whose names repeat after 2."""+ config = SimpleNamespace(+ num_hidden_layers=61,+ text_config=SimpleNamespace(num_hidden_layers=61),+ vision_config=SimpleNamespace(num_hidden_layers=27),+ )++ shrink_for_preflight(config)++ assert config.num_hidden_layers == PREFLIGHT_LAYERS+ assert config.text_config.num_hidden_layers == PREFLIGHT_LAYERS+ assert config.vision_config.num_hidden_layers == PREFLIGHT_LAYERS++ def test_a_model_already_smaller_is_left_alone(self):+ """Raising a 1-layer test model to 2 would change what is being checked."""+ config = SimpleNamespace(num_hidden_layers=1)++ shrink_for_preflight(config)++ assert config.num_hidden_layers == 1++ def test_a_config_without_layers_is_not_invented(self):+ config = SimpleNamespace(model_type="x")++ shrink_for_preflight(config)++ assert not hasattr(config, "num_hidden_layers")+++class TestTheRealAttach:+ """End to end with the real resolution and the real `get_peft_model`, on+ real architectures built locally. No network, no weights."""++ @staticmethod+ def _local(config):+ return lambda _base: config++ @staticmethod+ def _meta(config, classes):+ from soup_cli.utils.attach_preflight import build_on_meta++ return build_on_meta(config, classes)++ def test_a_dense_llama_attaches(self):+ from transformers import LlamaConfig++ config = LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1,+ )+ check = check_attach(+ "llama", _real_cfg(), load_hf_config=self._local(config), build_model=self._meta+ )++ assert check.verdict is Verdict.ATTACHES, check.detail+ assert check.adapted == 4, "q_proj and v_proj on two layers"+ assert check.expert_modules == 0++ def test_a_phi3_shaped_model_cannot_attach(self):+ """The finding this check exists for, reduced to a test. phi-4 is+ `model_type: phi3`; its attention is a fused `qkv_proj` + `o_proj`, so+ there is no `q_proj`/`v_proj` for a default to hit, peft 0.20 has no+ `phi3` key, and Soup's `auto` returns None. Three shipped recipes name+ that base."""+ from transformers import Phi3Config++ config = Phi3Config(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,+ )+ check = check_attach(+ "phi", _real_cfg(), load_hf_config=self._local(config), build_model=self._meta+ )++ assert check.verdict is Verdict.CANNOT_ATTACH, check+ assert check.model_type == "phi3"+ assert check.adapted == 0++ def test_the_configs_own_lora_settings_reach_peft(self):+ """Substituting a tidy ``r=8, dropout=0.0`` would have hidden #798+ completely: the dropout that made every MoE recipe unattachable was the+ schema default those recipes inherited, and a check that normalises it+ away cannot see the defect it exists to find.++ Asserted on the kwargs rather than on a failure, because reaching peft's+ ``ParamWrapper`` (where a non-zero dropout actually raises) needs+ ``target_parameters``, which is #798/#1074 machinery and not this+ module's business.+ """+ from transformers import LlamaConfig++ config = LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1,+ )+ seen = {}++ def _record(model, peft_config):+ seen["config"] = peft_config+ return SimpleNamespace(named_modules=lambda: [("a.lora_A", None)])++ check_attach(+ "llama", _real_cfg(r=64, dropout=0.05),+ load_hf_config=self._local(config), build_model=self._meta,+ attach=_record,+ )++ # The config handed to peft IS the trainer's -- build_lora_config's output.+ assert seen["config"].lora_dropout == 0.05, "the check normalised the dropout away"+ assert seen["config"].r == 64, "the check substituted its own rank"++ def test_an_attach_that_adapts_nothing_is_a_failure(self):+ """The defensive branch: peft normally raises when nothing matches, but if+ it ever returns a model with no adapter, "it attached" is the wrong+ answer -- that is a run that trains no LoRA parameters and looks fine,+ which is the v0.73.3 shape this repo has been bitten by before."""+ from transformers import LlamaConfig++ config = LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1,+ )+ check = check_attach(+ "llama", _real_cfg(),+ load_hf_config=self._local(config), build_model=self._meta,+ attach=lambda _m, _k: SimpleNamespace(named_modules=lambda: []),+ )++ assert check.verdict is Verdict.CANNOT_ATTACH, check+ assert "no module carries an adapter" in check.detail++ def test_an_explicit_target_that_matches_nothing_fails(self):+ """`auto` is not the only way to reach nothing -- a hand-written list+ naming modules this architecture does not have reaches it too."""+ from transformers import LlamaConfig++ config = LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1,+ )+ check = check_attach(+ "llama", _real_cfg(targets=["not_a_module_here"]),+ load_hf_config=self._local(config), build_model=self._meta,+ )++ assert check.verdict is Verdict.CANNOT_ATTACH+++class TestTheBreakdowns:+ """`adapted=8` says nothing about whether the right 8. These two columns are+ the ones that caught a vision tower being adapted during a text fine-tune."""++ def test_expert_and_vision_modules_are_counted_apart(self):+ model = SimpleNamespace(+ named_modules=lambda: [+ ("model.layers.0.self_attn.q_proj.lora_A", None),+ ("model.layers.0.mlp.experts.gate_up_proj.lora_A", None),+ ("vision_tower.layers.0.self_attn.q_proj.lora_A", None),+ ("model.layers.0.self_attn.q_proj.lora_B", None),+ ]+ )++ assert count_adapted(model) == (3, 1, 1)++ def test_the_inner_adapter_module_is_not_counted_twice(self):+ """peft emits BOTH ``q_proj.lora_A`` (the ModuleDict) and+ ``q_proj.lora_A.<adapter>`` (the Linear inside it) from+ ``named_modules``. My first version matched either and reported 8 for a+ model with 4 adapted modules -- caught by the real llama test below, not+ by a fake."""+ model = SimpleNamespace(+ named_modules=lambda: [+ ("a.lora_A", None), ("a.lora_A.default", None),+ ("a.lora_B", None), ("a.lora_B.default", None),+ ]+ )++ assert count_adapted(model)[0] == 1++ def test_a_non_default_adapter_name_is_still_counted(self):+ """The other half of why ``.lora_A`` is the right anchor: peft names the+ inner Linear after the adapter, so matching ``lora_A.default`` alone+ reports 0 for any run that named its adapter something else."""+ model = SimpleNamespace(+ named_modules=lambda: [("a.lora_A", None), ("a.lora_A.my_adapter", None)]+ )++ assert count_adapted(model)[0] == 1+++class TestTheExitCode:+ def test_only_cannot_attach_fails_the_run(self):+ rows = [+ AttachCheck("a", "b", "sft", Verdict.ATTACHES, adapted=4),+ AttachCheck("b", "b", "sft", Verdict.UNVERIFIED, detail="gated"),+ AttachCheck("c", "b", "sft", Verdict.NO_ADAPTER, detail="lora.r: 0"),+ ]++ assert PreflightReport(rows).exit_code == 0++ def test_one_failure_fails_the_run(self):+ rows = [+ AttachCheck("a", "b", "sft", Verdict.ATTACHES, adapted=4),+ AttachCheck("c", "b", "sft", Verdict.CANNOT_ATTACH, detail="nothing"),+ ]+ report = PreflightReport(rows)++ # #1117 review: the gate/verdict contract, not "1 on any failure".+ assert report.exit_code == 2+ assert [c.name for c in report.failures] == ["c"]+++class TestTheCommand:+ """The CLI is a thin wrapper, so this pins only what the wrapper decides:+ which configs are in scope, and the exit code."""++ def _run(self, tmp_path, monkeypatch, verdict):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ def _fake(name, cfg, **_kwargs):+ return AttachCheck(name, cfg.base, cfg.task, verdict, detail="stubbed")++ monkeypatch.setattr("soup_cli.utils.attach_preflight.check_attach", _fake)+ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"+ "training:\n lora:\n r: 8\n",+ encoding="utf-8",+ )+ return CliRunner().invoke(app, ["recipes", "verify", "--config", str(path)])++ def test_a_config_that_cannot_attach_exits_2(self, tmp_path, monkeypatch):+ """Was 1. A finding is EXIT_GATE_FAILED under the gate/verdict contract,+ so CI can tell it from a crash (1) or a bad --config (3)."""+ result = self._run(tmp_path, monkeypatch, Verdict.CANNOT_ATTACH)++ assert result.exit_code == 2, result.output++ def test_an_unverified_config_exits_0(self, tmp_path, monkeypatch):+ """The rule again, through the command: CI must not go red because the+ runner has no token."""+ result = self._run(tmp_path, monkeypatch, Verdict.UNVERIFIED)++ assert result.exit_code == 0, result.output++ def test_a_missing_config_is_refused(self, tmp_path):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ result = CliRunner().invoke(+ app, ["recipes", "verify", "--config", str(tmp_path / "nope.yaml")]+ )++ assert result.exit_code == 3, "an input error, not a finding or a crash"+ from tests.conftest import strip_ansi++ assert "not found" in strip_ansi(result.output).lower()++ def test_an_unparseable_config_exits_3(self, tmp_path):+ from typer.testing import CliRunner++ from soup_cli.cli import app+ from tests.conftest import strip_ansi++ path = tmp_path / "bad.yaml"+ path.write_text("base: org/m\ntask: sft\ndata:\n train: x.jsonl\n format: nope\n")+ result = CliRunner().invoke(app, ["recipes", "verify", "--config", str(path)])++ assert result.exit_code == 3, result.output+ assert "does not parse" in strip_ansi(result.output)++ def test_a_crash_exits_1(self, tmp_path, monkeypatch):+ """The fourth code: an unexpected error stays a runtime error."""+ def _boom(*_a, **_k):+ raise RuntimeError("boom")++ monkeypatch.setattr("soup_cli.utils.attach_preflight.check_attach", _boom)+ from typer.testing import CliRunner++ from soup_cli.cli import app++ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"+ "training:\n lora:\n r: 8\n",+ encoding="utf-8",+ )+ result = CliRunner().invoke(app, ["recipes", "verify", "--config", str(path)])++ assert result.exit_code == 1+ # The 1 must come from the injected crash, not some other failure path.+ assert isinstance(result.exception, RuntimeError), result.exception+++class TestTheVerdictIsTheTrainers:+ """The check must answer for what the TRAINER does, not for a lookalike.+ Two ways the first version answered for a lookalike, each now pinned."""++ @staticmethod+ def _qwen2_moe_config():+ from transformers import Qwen2MoeConfig++ return Qwen2MoeConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ moe_intermediate_size=16, shared_expert_intermediate_size=16,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1,+ num_experts=4, num_experts_per_tok=2,+ )++ def _check(self, cfg, hf_config, classes=None):+ from soup_cli.utils.attach_preflight import build_on_meta++ return check_attach(+ "r", cfg, load_hf_config=lambda _b: hf_config,+ build_model=lambda c, _cls: build_on_meta(c, classes or _cls),+ )++ def test_moe_lora_rescues_an_unmapped_moe_as_it_does_in_the_trainer(self):+ """``qwen2_moe`` is mapped by neither Soup nor peft, so ``auto`` resolves to+ nothing -- and the trainer then replaces ``target_modules`` from the+ ``moe_lora`` scan. The first version skipped that step and called such a+ recipe broken: measured on ``qwen3-30b-a3b-sft`` it said FAILS while the+ trainer's path attached 12 modules."""+ check = self._check(_real_cfg(moe_lora=True), self._qwen2_moe_config())++ assert check.verdict is Verdict.ATTACHES, check.detail+ assert check.adapted > 0++ def test_without_moe_lora_the_same_model_cannot_attach(self):+ """The control: it is the ``moe_lora`` step that attached it above, not a+ check that has stopped failing anything."""+ check = self._check(_real_cfg(moe_lora=False), self._qwen2_moe_config())++ assert check.verdict is Verdict.CANNOT_ATTACH, check++ @staticmethod+ def _qwen3_moe_config():+ from transformers import Qwen3MoeConfig++ return Qwen3MoeConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ moe_intermediate_size=16, num_hidden_layers=2, num_attention_heads=2,+ num_key_value_heads=1, num_experts=4, num_experts_per_tok=2,+ )++ def test_explicit_target_parameters_reach_the_attach(self):+ """``qwen3_moe``'s experts are fused 3-D parameters that no+ ``target_modules`` entry can name; ``lora.target_parameters`` is how a+ user reaches them, and the trainer hands them to ``build_lora_config``.+ A check that dropped them would report such a config as unable to attach+ -- or attach it without the experts it was written for."""+ cfg = _real_cfg(target_parameters=["experts.gate_up_proj", "experts.down_proj"])+ check = self._check(cfg, self._qwen3_moe_config())++ assert check.verdict is Verdict.ATTACHES, check.detail+ assert check.expert_modules > 0, check++ def test_the_attach_sees_the_keys_the_trainer_hands_peft(self):+ """The maintainer's review ask on #1116: run against the object the trainer+ hands ``get_peft_model``, INCLUDING the ``model.`` prefix peft matches on.++ peft fullmatches a string target against the whole module key, and under+ ``AutoModelForImageTextToText`` -- what vision SFT loads -- the key is+ ``model.language_model....``. So a pattern anchored at ``language_model``+ genuinely cannot attach, and a check that built the model at a different+ level (``AutoModel``, which drops the ``model.`` wrapper) would report it+ green. That exact regex shipped in #1102 and was caught at review."""+ from transformers import CLIPVisionConfig, LlamaConfig, LlavaConfig++ vl = LlavaConfig(+ text_config=LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,+ pad_token_id=0,+ ),+ vision_config=CLIPVisionConfig(+ hidden_size=16, intermediate_size=32, num_hidden_layers=2,+ num_attention_heads=2, image_size=32, patch_size=16,+ ),+ image_token_index=63,+ )+ classes = ("AutoModelForImageTextToText",)+ anchored = _real_cfg(targets=r"language_model\..*\.self_attn\.(q_proj|v_proj)")+ prefixed = _real_cfg(targets=r".*language_model\..*\.self_attn\.(q_proj|v_proj)")++ broken = self._check(anchored, vl, classes)+ working = self._check(prefixed, vl, classes)++ assert broken.verdict is Verdict.CANNOT_ATTACH, (+ "an anchored regex attached -- the check is not seeing the model. prefix"+ )+ assert working.verdict is Verdict.ATTACHES, working.detail+ assert working.vision_modules == 0, "and it stayed out of the vision tower"+++ def test_a_text_config_the_causal_lm_class_refuses_is_not_attached(self):+ """No trainer falls back from ``AutoModelForCausalLM`` to ``AutoModel``;+ SFT's text path loads exactly one class. My first version did fall back,+ so a config the causal-LM class refuses was built one level down and+ reported as ATTACHING -- MiniMax-M3 with no ``modality`` read green, while+ in SFT it cannot even load (#1145). A LLaVA reproduces the shape locally:+ ``AutoModelForCausalLM`` refuses it, ``AutoModel`` builds ``LlavaModel``."""+ from transformers import CLIPVisionConfig, LlamaConfig, LlavaConfig++ from soup_cli.utils.attach_preflight import build_on_meta, loader_for++ vl = LlavaConfig(+ text_config=LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,+ pad_token_id=0,+ ),+ vision_config=CLIPVisionConfig(+ hidden_size=16, intermediate_size=32, num_hidden_layers=2,+ num_attention_heads=2, image_size=32, patch_size=16,+ ),+ image_token_index=63,+ )+ text_cfg = _real_cfg() # no modality -> the text path++ check = check_attach(+ "vl-as-text", text_cfg, load_hf_config=lambda _b: vl,+ build_model=lambda c, _cls: build_on_meta(c, loader_for(text_cfg)),+ )++ assert check.verdict is Verdict.CANNOT_ATTACH, (+ f"reported {check.verdict.value} -- the check built it with a class "+ "the trainer never uses"+ )+ assert check.stage == "build"+++class TestReviewFollowUps:+ """The #1117 review's follow-ups, each pinned."""++ def test_a_gated_message_that_also_says_not_a_local_folder_is_gated(self):+ """First match wins, so the order is the #677 lesson: a 401 folded into+ "is not a local folder" text must still read as gated, not unresolvable."""+ exc = OSError(+ "org/m is not a local folder and is not a valid model identifier. "+ "Cannot access gated repo for url https://huggingface.co/org/m."+ )+ assert "gated" in classify_load_failure(exc)++ def test_catalogue_row_names_use_forward_slashes(self):+ """``--json`` keys must not depend on the OS: Windows printed+ ``templates\\audio.yaml``. Only the Windows cells can see a regression."""+ from soup_cli.commands.recipes import _configs_to_verify++ names = [name for name, _cfg in _configs_to_verify(None, True)]+ nested = [n for n in names if "/" in n]+ assert any(n.startswith("templates/") for n in nested), names[:5]+ assert any(n.startswith("examples/") for n in nested), names[:5]+ assert not [n for n in names if "\\" in n]++ @staticmethod+ def _cfg(modality):+ from soup_cli.config.loader import load_config_from_string++ fmt = {"text": "alpaca", "vision": "llava", "audio": "audio"}[modality]+ return load_config_from_string(+ f"base: org/m\ntask: sft\nmodality: {modality}\n"+ f"data:\n train: ./x.jsonl\n format: {fmt}\n"+ # No moe_lora: #1179 refuses it on SFT vision/audio at load, and the+ # modality gate under test does not read it.+ "training:\n"+ " lora:\n r: 8\n alpha: 16\n dropout: 0.0\n"+ ' target_modules: ["q_proj"]\n'+ )++ @pytest.mark.parametrize(+ ("modality", "full_sequence"),+ [("text", True), ("vision", False), ("audio", False)],+ )+ def test_sft_vision_and_audio_skip_the_moe_and_parameter_steps(+ self, monkeypatch, modality, full_sequence+ ):+ """SFT's vision and audio branches call only ``resolve_lora_target_modules``+ and ``build_lora_config``, so a vision or audio config must not be reported+ through the MoE and ``target_parameters`` steps the trainer never runs there."""+ import torch++ import soup_cli.utils.moe as moe+ import soup_cli.utils.peft_wiring as wiring+ from soup_cli.utils.attach_preflight import trainer_lora_config++ seen = []+ real_moe, real_params = moe.resolve_moe_lora_targets, wiring.resolve_lora_target_parameters++ def spy_moe(*a, **k):+ seen.append("moe")+ return real_moe(*a, **k)++ def spy_params(*a, **k):+ seen.append("params")+ return real_params(*a, **k)++ monkeypatch.setattr(moe, "resolve_moe_lora_targets", spy_moe)+ monkeypatch.setattr(wiring, "resolve_lora_target_parameters", spy_params)++ model = torch.nn.Sequential()+ model.add_module("q_proj", torch.nn.Linear(4, 4))+ _peft_config, targets = trainer_lora_config(model, self._cfg(modality))++ assert targets == ["q_proj"]+ assert (seen == ["params", "moe"]) is full_sequence, seen+ assert (seen == []) is (not full_sequence), seen+++class TestOnlySftReadsModality:+ """#1117 review, round 3: ``loader_for`` chose the class from ``modality`` for+ every task, but only ``trainer/sft.py`` reads it. A vision DPO config was+ reported ATTACHES (8 modules, 4 of them in the vision tower) while DPO's own+ ``AutoModelForCausalLM`` refuses the base outright."""++ @staticmethod+ def _cfg(task, modality="text", **training):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ fmt = {"text": "alpaca", "vision": "llava", "audio": "audio"}[modality]+ fmt = {"asr": "asr", "classifier": "auto", "reranker": "auto",+ "cross_encoder": "auto"}.get(task, fmt)+ raw = {+ "base": "org/m", "task": task, "modality": modality,+ "data": {"train": "./x.jsonl", "format": fmt},+ "training": {"lora": {"r": 8, "dropout": 0.0}, **training},+ }+ return load_config_from_string(yaml.safe_dump(raw))++ @pytest.mark.parametrize("task", ["dpo", "grpo"])+ def test_a_vision_config_on_a_text_trainer_is_a_causal_lm(self, task):+ from soup_cli.utils.attach_preflight import loader_for++ assert loader_for(self._cfg(task, "vision")) == ("AutoModelForCausalLM",)++ def test_sft_still_chooses_by_modality(self):+ """The control: the split is SFT's, and it stays."""+ from soup_cli.utils.attach_preflight import loader_for++ assert loader_for(self._cfg("sft", "vision")) == ("AutoModelForImageTextToText",)+ assert loader_for(self._cfg("sft", "audio")) == ("AutoModel",)++ def test_asr_loads_whisper_seq2seq(self):+ from soup_cli.utils.attach_preflight import loader_for++ asr = self._cfg("asr", "text", asr_language="en")+ assert loader_for(asr) == ("WhisperForConditionalGeneration",)++ @pytest.mark.parametrize("task", ["classifier", "reranker", "cross_encoder"])+ def test_the_classifier_family_loads_a_sequence_classifier(self, task):+ """All three: only ``classifier`` was asserted, so dropping the other two+ entries survived (#1117 review, round 3)."""+ from soup_cli.utils.attach_preflight import loader_for++ clf = self._cfg(task, num_labels=2, classifier_lora=True)+ assert loader_for(clf) == ("AutoModelForSequenceClassification",)+++class TestTheTrainersOwnTargetPaths:+ def test_a_vision_dpo_config_takes_the_full_sequence(self, monkeypatch):+ """Pins the ``task == "sft"`` half of the two-call gate: DPO has no+ vision branch, so a vision DPO config runs the full MoE sequence."""+ import torch++ import soup_cli.utils.moe as moe+ from soup_cli.utils.attach_preflight import trainer_lora_config++ seen = []+ real = moe.resolve_moe_lora_targets++ def spy(*a, **k):+ seen.append("moe")+ return real(*a, **k)++ monkeypatch.setattr(moe, "resolve_moe_lora_targets", spy)+ model = torch.nn.Sequential()+ model.add_module("q_proj", torch.nn.Linear(4, 4))+ cfg = TestOnlySftReadsModality._cfg("dpo", "vision")+ cfg.training.lora.target_modules = ["q_proj"]+ trainer_lora_config(model, cfg)++ assert seen == ["moe"]++ def test_asr_auto_means_q_and_v_without_the_resolver(self, monkeypatch):+ """``trainer/asr.py`` never calls the resolver; ``auto`` is Whisper's q/v."""+ import torch++ import soup_cli.utils.peft_wiring as wiring+ from soup_cli.utils.attach_preflight import trainer_lora_config++ def _no(*_a, **_k):+ raise AssertionError("asr must not call resolve_lora_target_modules")++ monkeypatch.setattr(wiring, "resolve_lora_target_modules", _no)+ cfg = TestOnlySftReadsModality._cfg("asr", "text", asr_language="en")+ _peft, targets = trainer_lora_config(torch.nn.Linear(2, 2), cfg)++ assert targets == ["q_proj", "v_proj"]+++class TestTasksThatBuildNoAdapter:+ @pytest.mark.parametrize("task", ["prm", "moe_lora_routing"])+ def test_they_are_no_adapter_whatever_lora_r_says(self, task):+ cfg = SimpleNamespace(+ task=task, backend="transformers", training=SimpleNamespace(lora=SimpleNamespace(r=8))+ )+ wanted, why = plan_adapter(cfg)++ assert not wanted and why++ def test_the_classifier_family_needs_classifier_lora(self):+ off = SimpleNamespace(task="reranker", backend="transformers", training=SimpleNamespace(+ lora=SimpleNamespace(r=8), classifier_lora=False))+ on = SimpleNamespace(task="reranker", backend="transformers", training=SimpleNamespace(+ lora=SimpleNamespace(r=8), classifier_lora=True))++ assert plan_adapter(off) == (+ False, "classifier_lora is off --- that trainer full-fine-tunes"+ )+ assert plan_adapter(on) == (True, "")+++class TestConcreteClassesBuild:+ def test_whisper_seq2seq_builds_on_meta(self):+ """``asr`` loads ``WhisperForConditionalGeneration`` by name, which has no+ ``from_config``. Calling it anyway turned all three shipped Whisper recipes+ from ATTACHES into CANNOT_ATTACH on a full catalogue run."""+ from transformers import WhisperConfig++ from soup_cli.utils.attach_preflight import build_on_meta++ cfg = WhisperConfig(+ vocab_size=64, d_model=16, encoder_layers=1, decoder_layers=1,+ encoder_attention_heads=2, decoder_attention_heads=2,+ encoder_ffn_dim=32, decoder_ffn_dim=32, max_source_positions=16,+ max_target_positions=16, num_mel_bins=8,+ pad_token_id=0, bos_token_id=1, eos_token_id=2, decoder_start_token_id=1,+ )+ model = build_on_meta(cfg, ("WhisperForConditionalGeneration",))++ assert type(model).__name__ == "WhisperForConditionalGeneration"+ assert next(model.parameters()).device.type == "meta"+++class TestAsrNeedsItsAdapter:+ def test_asr_without_asr_lora_is_no_adapter(self):+ """trainer/asr.py attaches only with asr_lora on (#1117 review, round 3):+ without it that run full-fine-tunes, so the check has nothing to attach."""+ off = SimpleNamespace(task="asr", backend="transformers", training=SimpleNamespace(+ lora=SimpleNamespace(r=8), asr_lora=False))+ on = SimpleNamespace(task="asr", backend="transformers", training=SimpleNamespace(+ lora=SimpleNamespace(r=8), asr_lora=True))++ assert plan_adapter(off) == (False, "asr_lora is off --- that trainer full-fine-tunes")+ assert plan_adapter(on) == (True, "")+++def _tiny_llama():+ from transformers import LlamaConfig++ return LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32, num_hidden_layers=2,+ num_attention_heads=2, num_key_value_heads=2, pad_token_id=0,+ )+++def plain_consoles(monkeypatch):+ """Both of the command's consoles with no colour system: Rich then emits no+ escape of its own, so any ESC byte in the output came from the config."""+ from rich.console import Console++ import soup_cli.commands.recipes as recipes_cmd++ monkeypatch.setattr(recipes_cmd, "console", Console(color_system=None, width=400))+ monkeypatch.setattr(+ recipes_cmd, "err_console", Console(stderr=True, color_system=None, width=400)+ )++[email protected]("plain_consoles")+class TestTheReportIsSafeForATerminal:+ """#1117 review, round 3: peft quotes a string target_modules verbatim, and the+ "Cannot attach" table printed it as Rich markup with control bytes intact."""++ def _verify(self, tmp_path, monkeypatch, targets):+ import json as _json++ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.setattr(+ "soup_cli.utils.attach_preflight.load_hf_config", lambda _base: _tiny_llama()+ )+ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"+ f"training:\n lora:\n r: 8\n target_modules: {_json.dumps(targets)}\n",+ encoding="utf-8",+ )+ return CliRunner().invoke(app, ["recipes", "verify", "--config", str(path)])++ def test_markup_in_the_config_is_printed_literally(self, tmp_path, monkeypatch):+ """'[/]' used to raise MarkupError after the verdict, turning a finding+ into a crash (exit 1)."""+ result = self._verify(tmp_path, monkeypatch, ".*[/]nothing")++ assert result.exit_code == 2, (result.output, result.exception)+ assert "[/]nothing" in result.output++ def test_a_character_class_survives(self, tmp_path, monkeypatch):+ """'[qkv]' was swallowed as a markup tag."""+ result = self._verify(tmp_path, monkeypatch, r".*\.[qkv]_nothing")++ assert result.exit_code == 2+ assert "[qkv]_nothing" in result.output++ def test_control_bytes_do_not_reach_the_terminal(self, tmp_path, monkeypatch):+ """'\\x1bc' is a full terminal reset."""+ result = self._verify(tmp_path, monkeypatch, "x\x1bcEVIL_nothing")++ assert result.exit_code == 2+ assert "\x1b" not in result.output+ assert "EVIL_nothing" in result.output++[email protected]("plain_consoles")+class TestConfigNamesAreSafeToo:+ def test_a_missing_config_path_prints_literally(self):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ # Bare, not joined onto tmp_path: Windows pathlib splits at the "/" and+ # the literal "[/]x" never reaches the output (#1117 review).+ result = CliRunner().invoke(+ app, ["recipes", "verify", "--config", "[/]x\x1b[2J.yaml"]+ )++ assert result.exit_code == 3+ assert "[/]x" in result.output and "\x1b" not in result.output++ def test_a_vision_tower_name_prints_literally(self, tmp_path, monkeypatch):+ """The "adapted a vision tower" line lists config names, which come from+ the file name in --config mode."""+ from transformers import CLIPVisionConfig, LlamaConfig, LlavaConfig+ from typer.testing import CliRunner++ from soup_cli.cli import app++ vl = LlavaConfig(+ text_config=LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32,+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,+ pad_token_id=0,+ ),+ vision_config=CLIPVisionConfig(+ hidden_size=16, intermediate_size=32, num_hidden_layers=2,+ num_attention_heads=2, image_size=32, patch_size=16,+ ),+ image_token_index=63,+ )+ monkeypatch.setattr("soup_cli.utils.attach_preflight.load_hf_config", lambda _b: vl)+ path = tmp_path / "[bold]v.yaml"+ path.write_text(+ "base: org/vl\ntask: sft\nmodality: vision\n"+ "data:\n train: ./x.jsonl\n format: llava\n"+ 'training:\n lora:\n r: 8\n target_modules: ".*(q_proj|v_proj)"\n',+ encoding="utf-8",+ )+ result = CliRunner().invoke(app, ["recipes", "verify", "--config", str(path)])++ assert result.exit_code == 0, (result.output, result.exception)+ assert "adapted a vision tower: [bold]v.yaml" in " ".join(result.output.split())++ def test_a_parse_error_prints_literally(self, tmp_path, monkeypatch):+ """The parse-error line carries the file name and pydantic's text, which+ quotes the key: both are user-controlled."""+ from typer.testing import CliRunner++ from soup_cli.cli import app++ # "[bold]", not "[/]": a "/" in the name is a separator on Windows.+ path = tmp_path / "[bold]p.yaml"+ path.write_text(+ 'base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"[/]x": 1\n',+ encoding="utf-8",+ )+ # Bare name: on Windows the full path puts a "\\" before "[bold]", Rich reads+ # "\\[" as an escaped bracket, and a raw print would pass (#1117 review).+ monkeypatch.chdir(tmp_path)+ result = CliRunner().invoke(app, ["recipes", "verify", "--config", path.name])++ assert result.exit_code == 3, (result.output, result.exception)+ out = " ".join(result.output.split())+ assert "Config does not parse" in out and "[/]x" in out and "[bold]p.yaml" in out+++class TestAMissingLibraryIsAnEnvironmentError:+ @pytest.mark.parametrize("lib", ["torch", "transformers", "peft"])+ @pytest.mark.parametrize(+ "error",+ [+ ModuleNotFoundError("No module named 'x'"),+ # Installed but broken: find_spec finds it, the import raises. A torch+ # DLL that will not load on Windows is an OSError (#1117 review).+ OSError("DLL load failed"),+ ],+ ids=["absent", "broken"],+ )+ def test_it_exits_1_naming_the_extra(self, tmp_path, monkeypatch, lib, error):+ """Without these the per-stage catch-alls turned a missing library into a+ verdict: unverified with exit 0, or cannot_attach with exit 2."""+ import importlib++ from typer.testing import CliRunner++ from soup_cli.cli import app+ from tests.conftest import strip_ansi++ real = importlib.import_module++ def fake(name, *a, **k):+ if name == lib:+ raise error+ return real(name, *a, **k)++ monkeypatch.setattr(importlib, "import_module", fake)+ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n",+ encoding="utf-8",+ )+ result = CliRunner().invoke(app, ["recipes", "verify", "--config", str(path)])++ assert result.exit_code == 1+ out = " ".join(strip_ansi(result.output).split())+ assert f"needs {lib}" in out and 'pip install "soup-cli[train]"' in out+ assert type(error).__name__ in out+++class TestTheAdvisoryGoesToStderr:+ def test_json_stdout_parses_with_a_partial_coverage_advisory(self, tmp_path, monkeypatch):+ """#1164's resolver prints a partial-coverage advisory for+ ``granitemoehybrid``. It must reach the user on stderr and leave --json's+ stdout a document."""+ import json as _json++ from typer.testing import CliRunner++ from soup_cli.cli import app+ from tests.test_issue1122_glm4_granite_moe_targets import _granite_config++ monkeypatch.setattr(+ "soup_cli.utils.attach_preflight.load_hf_config",+ lambda _base: _granite_config(num_hidden_layers=10, attention_every=5),+ )+ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: org/granite\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"+ "training:\n lora:\n r: 8\n target_modules: auto\n",+ encoding="utf-8",+ )+ # Click < 8.2 mixes stderr into stdout unless told not to; 8.2 removed the+ # parameter and always keeps them apart (cf. test_issue762's note).+ import importlib.metadata as _md++ click_version = tuple(int(x) for x in _md.version("click").split(".")[:2])+ runner = CliRunner(mix_stderr=False) if click_version < (8, 2) else CliRunner()+ result = runner.invoke(app, ["recipes", "verify", "--config", str(path), "--json"])++ rows = _json.loads(result.stdout)+ assert rows[0]["model_type"] == "granitemoehybrid"+ assert rows[0]["verdict"] == "attaches", rows[0]["detail"]+ assert "Partial LoRA coverage" in result.stderr+ assert "Partial LoRA coverage" not in result.stdout+++class TestNothingToVerify:+ def test_an_empty_scope_exits_3(self, monkeypatch):+ from typer.testing import CliRunner++ import soup_cli.recipes.catalog as catalog+ from soup_cli.cli import app++ monkeypatch.setattr(catalog, "RECIPES", {})+ result = CliRunner().invoke(app, ["recipes", "verify", "--no-templates"])++ assert result.exit_code == 3, result.output+++class TestTheSkeletonKeepsAnExpertLayer:+ """A local CodeRabbit review: shrinking every config to two layers kept only+ dense layers on DeepSeek-V3 and GLM-5.1 (``first_k_dense_replace: 3``), so their+ ``moe_lora`` recipes were reported ATTACHES with zero experts built -- the+ thing those recipes exist for was never checked."""++ @pytest.mark.parametrize(+ ("fields", "depth"),+ [+ ({"first_k_dense_replace": 3, "moe_layer_freq": 1}, 4),+ ({"first_k_dense_replace": 1, "moe_layer_freq": 1}, 2),+ # Frequency 2 skips layer 1: only this case tells the moe_layer_freq+ # rule from its absence (#1117 review).+ ({"first_k_dense_replace": 1, "moe_layer_freq": 2}, 3),+ ({"decoder_sparse_step": 2}, 2),+ # A step whose first sparse layer lies past the 2-layer minimum: the+ # step-2 case alone could not tell the rule from its absence.+ ({"decoder_sparse_step": 4}, 4),+ ({"decoder_sparse_step": 1, "mlp_only_layers": [0, 1, 2]}, 4),+ ({"interleave_moe_layer_step": 4}, 4),+ ({}, 2),+ ],+ )+ def test_the_depth_reaches_the_first_sparse_layer(self, fields, depth):+ config = SimpleNamespace(num_hidden_layers=61, **fields)++ assert shrink_for_preflight(config).num_hidden_layers == depth++ def test_a_shallow_model_is_not_deepened(self):+ config = SimpleNamespace(num_hidden_layers=2, first_k_dense_replace=3, moe_layer_freq=1)++ assert shrink_for_preflight(config).num_hidden_layers == 2++ def test_a_deepseek_v3_moe_lora_config_reaches_its_experts(self):+ from transformers import DeepseekV3Config++ from soup_cli.utils.attach_preflight import build_on_meta++ hf = DeepseekV3Config(+ vocab_size=64, hidden_size=32, intermediate_size=32, moe_intermediate_size=16,+ num_hidden_layers=61, num_attention_heads=2, num_key_value_heads=2,+ n_routed_experts=4, num_experts_per_tok=2, n_group=1, topk_group=1,+ first_k_dense_replace=3, moe_layer_freq=1, q_lora_rank=16, kv_lora_rank=16,+ qk_rope_head_dim=8, qk_nope_head_dim=8, v_head_dim=8, pad_token_id=0,+ )+ check = check_attach(+ "r", _real_cfg(moe_lora=True), load_hf_config=lambda _b: hf,+ build_model=lambda c, cls: build_on_meta(c, cls),+ )++ assert check.verdict is Verdict.ATTACHES, check.detail+ assert check.expert_modules > 0, "the skeleton built no expert layer"+++class TestTheSkeletonKeepsEveryLayerKind:+ """#1117 review: on a hybrid decoder the first two layers can hold no+ attention layer, so a config the trainer attaches read cannot_attach."""++ def test_a_hybrid_skeleton_keeps_an_attention_layer(self):+ from soup_cli.utils.attach_preflight import build_on_meta+ from tests.test_issue1122_glm4_granite_moe_targets import _granite_config++ hf = _granite_config(num_hidden_layers=10, attention_every=5) # attention at 2 and 7+ check = check_attach(+ "g", _real_cfg(), load_hf_config=lambda _b: hf, build_model=build_on_meta+ )++ assert check.verdict is Verdict.ATTACHES, check.detail+ assert check.adapted == 4 # q/k/v/o of the first attention layer++ @pytest.mark.parametrize(+ ("kinds", "depth"),+ [+ (["mamba"] * 5 + ["attention"] + ["mamba"] * 10, 6),+ (["linear_attention"] * 3 + ["full_attention"] * 13, 4),+ (["full_attention"] * 16, 2),+ ],+ )+ def test_the_depth_reaches_the_first_layer_of_each_kind(self, kinds, depth):+ config = SimpleNamespace(num_hidden_layers=len(kinds), layer_types=kinds)++ assert shrink_for_preflight(config).num_hidden_layers == depth+++class TestTheLoadersWarningsLeaveJsonStdoutAlone:+ def test_json_stdout_parses_when_the_loader_warns(self, tmp_path, monkeypatch):+ """The config loader prints a deprecated value (#759) or a staged field (#808)+ as a warning on stdout. Under --json that line came before the document."""+ import importlib.metadata as _md+ import json as _json++ from transformers import LlamaConfig+ from typer.testing import CliRunner++ from soup_cli.cli import app+ from tests.conftest import strip_ansi++ tiny = LlamaConfig(+ vocab_size=64, hidden_size=16, intermediate_size=32, num_hidden_layers=2,+ num_attention_heads=2, num_key_value_heads=2,+ )+ monkeypatch.setattr("soup_cli.utils.attach_preflight.load_hf_config", lambda _b: tiny)+ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: org/m\ntask: sft\ndata:\n train: ./x.jsonl\n format: alpaca\n"+ # soup autopilot wrote this line into every config it generated (#759).+ " remove_unused_columns: true\n"+ "training:\n lora:\n r: 8\n target_modules: [q_proj, v_proj]\n",+ encoding="utf-8",+ )+ click_version = tuple(int(x) for x in _md.version("click").split(".")[:2])+ runner = CliRunner(mix_stderr=False) if click_version < (8, 2) else CliRunner()+ result = runner.invoke(app, ["recipes", "verify", "--config", str(path), "--json"])++ assert result.exit_code == 0, (result.output, result.exception)+ rows = _json.loads(result.stdout)+ assert rows[0]["verdict"] == "attaches", rows[0]["detail"]+ assert "remove_unused_columns" in " ".join(strip_ansi(result.stderr).split())diff --git a/tests/test_issue813_gate_exit_codes.py b/tests/test_issue813_gate_exit_codes.pyindex cbd0fc69..c85d8a28 100644--- a/tests/test_issue813_gate_exit_codes.py+++ b/tests/test_issue813_gate_exit_codes.py@@ -561,6 +561,7 @@ def test_eval_gate_hook_exit_code_dispatch(["data", "validate", "--bogus"],["data", "lint", "--bogus"],["ship", "--bogus"],+ ["recipes", "verify", "--bogus"],],)def test_gate_command_invalid_flag_exits_3(cmd: list[str]) -> None: