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
ci(recipes): the attach ratchet over every shipped config (#1116) (#1388)
Srinivasan R772614f6e41f
diff --git a/.github/workflows/recipe-attach.yml b/.github/workflows/recipe-attach.ymlnew file mode 100644index 00000000..73ffbefb--- /dev/null+++ b/.github/workflows/recipe-attach.yml@@ -0,0 +1,92 @@+# Recipe attach ratchet (#1116).+#+# `soup recipes verify` builds every shipped config's base on the meta device+# and runs the trainer's own target resolution and the real peft attach, so a+# recipe whose target_modules match nothing is caught before a user downloads+# the weights. It reads `config.json` from the Hub, nothing else.+# `scripts/check_recipe_attach.py` pins the configs that knowingly cannot attach+# yet, and fails only on a change: a new cannot-attach, or a pinned one that now+# attaches and should leave its list.+#+# Two trigger shapes, by ruling on #1116:+#+# push to main -- HF_TOKEN is in scope, so gated bases are verified.+# pull_request -- no token, on purpose. Fork PRs never see secrets anyway,+# and a same-repo PR must not report more coverage than a+# fork PR would. A gated base is SKIPPED (never a pass,+# never a failure); the count line says how many, so a+# green PR run is not mistaken for full coverage.+#+# Not a required check, and must never become one: a Hub outage would then+# block every merge. The recipe-repo-ids job (#677) stays token-free on a+# schedule for the same reason; this one is the attach-level complement.+name: recipe attach++on:+ push:+ branches: [main]+ paths:+ - 'src/soup_cli/recipes/**'+ - 'src/soup_cli/config/**'+ - 'src/soup_cli/templates/**'+ - 'src/soup_cli/utils/attach_preflight.py'+ - 'src/soup_cli/utils/peft_wiring.py'+ - 'src/soup_cli/utils/moe.py'+ - 'src/soup_cli/commands/recipes.py'+ - 'scripts/check_recipe_attach.py'+ - 'examples/**'+ - 'pyproject.toml'+ - '.github/workflows/recipe-attach.yml'+ pull_request:+ branches: [main]+ paths:+ - 'src/soup_cli/recipes/**'+ - 'src/soup_cli/config/**'+ - 'src/soup_cli/templates/**'+ - 'src/soup_cli/utils/attach_preflight.py'+ - 'src/soup_cli/utils/peft_wiring.py'+ - 'src/soup_cli/utils/moe.py'+ - 'src/soup_cli/commands/recipes.py'+ - 'scripts/check_recipe_attach.py'+ - 'examples/**'+ - 'pyproject.toml'+ - '.github/workflows/recipe-attach.yml'+ workflow_dispatch:++permissions:+ contents: read++# Same rule as recipe-validation.yml (#1374): a pull request supersedes its own+# earlier run; pushes to main share one group, so a running main run finishes+# and a newer push replaces only the pending one.+concurrency:+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || (github.ref == 'refs/heads/main' && 'main-push' || github.sha) }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ verify:+ name: attach every shipped config on the meta device+ runs-on: ubuntu-latest+ timeout-minutes: 30+ env:+ PYTHONUTF8: "1"+ PYTHONIOENCODING: "utf-8"+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.11"+ - name: Install the training stack+ # `[train]`, not `[dev]`: the attach needs torch, transformers and peft+ # and nothing from the test extras.+ run: pip install -e ".[train]"+ - name: Ratchet every shipped config's attach+ # Exit 2 is a new cannot-attach, or a pinned config that now attaches;+ # exit 1 is the command itself failing. Skipped (gated, no token) exits 0+ # and is counted on the line this prints.+ env:+ # This step only: the install above runs third-party build code and+ # never needs the token. Empty on anything but a push to main, and+ # huggingface_hub reads an empty HF_TOKEN as "no token".+ HF_TOKEN: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && secrets.HF_TOKEN || '' }}+ run: python scripts/check_recipe_attach.pydiff --git a/scripts/check_recipe_attach.py b/scripts/check_recipe_attach.pynew file mode 100644index 00000000..1180b029--- /dev/null+++ b/scripts/check_recipe_attach.py@@ -0,0 +1,152 @@+#!/usr/bin/env python3+"""The attach ratchet over every shipped config (#1116, second half).++``soup recipes verify`` builds each shipped recipe, template and example on the+meta device and runs the trainer's own target resolution and the real peft attach.+It exits 2 while any config cannot attach, and some shipped configs knowingly+cannot yet. So this script pins those, each with a reason, and fails only on a+change: a config that newly cannot attach, or a pinned one that now attaches and+should leave the list. Either way a change is a deliberate edit here.++It prints one count line so a run without a token is never read as full coverage+(ruled on #1116, 2026-09-21): gated bases are *skipped*, never passed or failed.+``.github/workflows/recipe-attach.yml`` runs it on pull requests without a token+and on push to main with ``HF_TOKEN``.+"""++from __future__ import annotations++import json+import subprocess+import sys+from collections import Counter+from dataclasses import dataclass, field++_NO_AUTO = (+ "target_modules: auto has no mapping for this model_type; the #1070 table may "+ "grow one family per PR, measured on the meta device (ruled on #1116)"+)+_NO_PEFT_DEFAULT = (+ "peft has no default targets for this wrapper model_type, so it needs "+ "tower-scoped target_modules (#1116)"+)+_VL_WRAPPER = (+ "the base is a vision-language wrapper that the task's text model class "+ "cannot build"+)++#: Configs that cannot attach today, measured on the meta device without a token.+#: A name leaves this list when it attaches; a new one needs a reason to join.+EXCEPTIONS: dict[str, str] = {+ "lfm2-sft": _NO_AUTO,+ "ministral-sft": _NO_AUTO,+ "paddle-ocr-sft": _NO_AUTO,+ "phi3.5-mini-sft": _NO_AUTO,+ "phi4-14b-sft": _NO_AUTO,+ "phi4-reasoning-grpo": _NO_AUTO,+ "qvq-72b-sft": _NO_AUTO,+ "qwen2-vl-72b-sft": _NO_AUTO,+ "qwen2-vl-7b-sft": _NO_AUTO,+ "ra-dit-retriever": _NO_AUTO,+ "seamlessm4t-v2-sft": _NO_AUTO,+ "smollm3-3b-sft": _NO_AUTO,+ "whisper-large-v3-ft": _NO_AUTO,+ "llava-next-sft": _NO_PEFT_DEFAULT,+ "qwen2-audio-7b-sft": _NO_PEFT_DEFAULT,+ "templates/audio.yaml": _NO_PEFT_DEFAULT,+ "voxtral-sft": _NO_PEFT_DEFAULT,+ "minimax-m3-sft": _VL_WRAPPER + " (#1145)",+ "minimax-m3-dpo": _VL_WRAPPER + " (#1145)",+ "mistral-medium-3-5-sft": _VL_WRAPPER + " (mistral3)",+}++_VERIFIED = frozenset({"attaches", "no_adapter"})+++@dataclass+class Ratchet:+ verified: list[str] = field(default_factory=list)+ skipped: list[tuple[str, str]] = field(default_factory=list)+ pinned: list[str] = field(default_factory=list)+ new_failures: list[tuple[str, str]] = field(default_factory=list)+ now_attach: list[str] = field(default_factory=list)+ not_reported: list[str] = field(default_factory=list)++ @property+ def ok(self) -> bool:+ return not self.new_failures and not self.now_attach and not self.not_reported+++def compare(rows: list[dict], exceptions: dict[str, str]) -> Ratchet:+ """Sort ``soup recipes verify --json`` rows against the pinned exceptions."""+ result = Ratchet()+ for row in rows:+ name, verdict = row["name"], row["verdict"]+ if verdict == "unverified":+ # Gated, remote code, or unreadable here: not a pass, not a failure.+ result.skipped.append((name, row.get("detail", "")))+ elif verdict == "cannot_attach":+ if name in exceptions:+ result.pinned.append(name)+ else:+ result.new_failures.append((name, row.get("detail", "")))+ elif verdict in _VERIFIED:+ result.verified.append(name)+ if name in exceptions:+ result.now_attach.append(name)+ else:+ raise ValueError(f"unknown verdict {verdict!r} for {name}")+ # verify leaves out a config that does not parse; a pinned one must not vanish.+ seen = {row["name"] for row in rows}+ result.not_reported = sorted(set(exceptions) - seen)+ return result+++def count_line(result: Ratchet) -> str:+ return (+ f"{len(result.verified)} verified, {len(result.skipped)} skipped (gated, "+ f"remote code or unreadable here), {len(result.pinned)} pinned cannot-attach, "+ f"{len(result.new_failures)} new cannot-attach, "+ f"{len(result.now_attach)} pinned that now attach"+ )+++def report(result: Ratchet) -> list[str]:+ lines = [count_line(result)]+ # The ruling asks for SKIPPED *with the reason*: a token only fixes the gated ones.+ by_reason = Counter(detail[:120] for _name, detail in result.skipped)+ for reason, count in by_reason.most_common():+ lines.append(f" skipped {count}: {reason}")+ for name, detail in result.new_failures:+ lines.append(+ f"NEW cannot attach: {name}: {detail[:200]} -- fix it, or pin it in "+ "EXCEPTIONS in scripts/check_recipe_attach.py with a reason"+ )+ for name in result.now_attach:+ lines.append(f"now attaches, remove from EXCEPTIONS: {name}")+ for name in result.not_reported:+ lines.append(f"pinned but not reported by verify: {name}")+ return lines+++def main() -> int:+ run = subprocess.run(+ [sys.executable, "-m", "soup_cli", "recipes", "verify", "--json"],+ capture_output=True, text=True, stdin=subprocess.DEVNULL,+ )+ # 0: everything checkable attaches; 2: something cannot. Anything else is the+ # command itself failing (a missing library is 1), not a verdict.+ # Always forwarded: verify's advisories (a partial-coverage note, a config that+ # does not parse) belong in the CI log whatever the verdict.+ if run.stderr:+ print(run.stderr, file=sys.stderr, end="" if run.stderr.endswith("\n") else "\n")+ if run.returncode not in (0, 2):+ print(f"soup recipes verify exited {run.returncode}", file=sys.stderr)+ return 1+ result = compare(json.loads(run.stdout), EXCEPTIONS)+ print("\n".join(report(result)))+ return 0 if result.ok else 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_issue1116_attach_ratchet.py b/tests/test_issue1116_attach_ratchet.pynew file mode 100644index 00000000..fd323da9--- /dev/null+++ b/tests/test_issue1116_attach_ratchet.py@@ -0,0 +1,166 @@+"""#1116, second half — the attach ratchet over every shipped config.++``scripts/check_recipe_attach.py`` compares ``soup recipes verify --json`` rows+against pinned exceptions. These tests are offline: the Hub run is the workflow's.+"""++from __future__ import annotations++import json+import subprocess+from types import SimpleNamespace++import pytest++from scripts.check_recipe_attach import EXCEPTIONS, compare, count_line, main, report+from tests.conftest import strip_ansi+++def _row(name, verdict, detail=""):+ return {"name": name, "verdict": verdict, "detail": detail}+++class TestCompare:+ def test_a_pinned_failure_keeps_the_run_green(self):+ result = compare([_row("a", "cannot_attach")], {"a": "why"})++ assert result.ok and result.pinned == ["a"]++ def test_a_new_failure_turns_it_red_and_is_named(self):+ result = compare(+ [_row("a", "cannot_attach"), _row("b", "cannot_attach", "no mapping")],+ {"a": "why"},+ )++ # Red because of "b" alone: "a" is reported, so nothing is missing.+ assert result.not_reported == [] and result.pinned == ["a"]+ assert not result.ok+ assert result.new_failures == [("b", "no mapping")]+ assert any(line.startswith("NEW cannot attach: b: no mapping") for line in report(result))++ def test_a_pinned_config_that_now_attaches_must_leave_the_list(self):+ result = compare([_row("a", "attaches")], {"a": "why"})++ assert not result.ok and result.now_attach == ["a"]+ assert "now attaches, remove from EXCEPTIONS: a" in report(result)++ @pytest.mark.parametrize("pinned", [True, False])+ def test_unverified_is_skipped_never_a_pass_or_a_failure(self, pinned):+ """A gated base without a token (the pull_request run) must not count+ either way, pinned or not (ruled on #1116)."""+ exceptions = {"g": "why"} if pinned else {}+ result = compare([_row("g", "unverified", "gated")], exceptions)++ assert result.ok+ assert result.skipped == [("g", "gated")]+ assert result.verified == [] and result.pinned == [] and result.now_attach == []++ def test_a_pinned_config_missing_from_the_run_is_flagged(self):+ """verify skips a config that does not parse, so a pinned one that stopped+ parsing (or was removed) would otherwise vanish while the run stays green."""+ result = compare([_row("a", "attaches")], {"gone": "why"})++ assert not result.ok and result.not_reported == ["gone"]+ assert "pinned but not reported by verify: gone" in report(result)++ def test_no_adapter_counts_as_verified(self):+ result = compare([_row("c", "no_adapter")], {})++ assert result.ok and result.verified == ["c"]++ def test_an_unknown_verdict_is_an_error_not_a_pass(self):+ with pytest.raises(ValueError, match="unknown verdict"):+ compare([_row("x", "maybe")], {})++ def test_the_count_line_says_what_was_not_covered(self):+ result = compare(+ [_row("a", "attaches"), _row("g", "unverified"), _row("p", "cannot_attach")],+ {"p": "why"},+ )++ assert count_line(result) == (+ "1 verified, 1 skipped (gated, remote code or unreadable here), "+ "1 pinned cannot-attach, 0 new cannot-attach, 0 pinned that now attach"+ )+++def test_skipped_rows_are_reported_by_reason():+ gated = "gated repo; set HF_TOKEN to check it"+ remote = "needs trust_remote_code, which this check never enables"+ result = compare(+ [_row("g1", "unverified", gated), _row("g2", "unverified", gated),+ _row("r", "unverified", remote), _row("a", "attaches")],+ {},+ )++ lines = report(result)++ assert f" skipped 2: {gated}" in lines+ assert f" skipped 1: {remote}" in lines+++def test_a_new_failure_says_how_to_pin_it():+ result = compare([_row("b", "cannot_attach", "no mapping")], {})++ assert any("pin it in EXCEPTIONS in scripts/check_recipe_attach.py" in line+ for line in report(result))+++class TestMain:+ @pytest.fixture+ def verify(self, monkeypatch):+ def install(rows, returncode=2, stderr=""):+ out = SimpleNamespace(returncode=returncode, stdout=json.dumps(rows), stderr=stderr)++ def run(argv, *_a, **_k):+ # The whole catalogue, templates included: `--no-templates` would+ # drop templates/audio.yaml from the rows (#1388 review).+ assert list(argv[-3:]) == ["recipes", "verify", "--json"], argv+ return out++ monkeypatch.setattr(subprocess, "run", run)++ return install++ def test_pinned_failures_only_exit_0(self, verify, capsys):+ verify([_row(name, "cannot_attach") for name in EXCEPTIONS])++ assert main() == 0+ assert f"{len(EXCEPTIONS)} pinned cannot-attach" in strip_ansi(capsys.readouterr().out)++ def test_a_new_failure_exits_2(self, verify):+ pinned = [_row(name, "cannot_attach") for name in EXCEPTIONS]+ verify(pinned + [_row("brand-new-sft", "cannot_attach", "boom")])++ assert main() == 2++ def test_a_pinned_config_that_attaches_exits_2(self, verify):+ first, *rest = EXCEPTIONS+ verify([_row(first, "attaches")] + [_row(name, "cannot_attach") for name in rest])++ assert main() == 2++ def test_verify_warnings_reach_the_log_whatever_the_verdict(self, verify, capsys):+ verify([_row(name, "cannot_attach") for name in EXCEPTIONS], stderr="Partial LoRA coverage")++ assert main() == 0+ assert "Partial LoRA coverage" in strip_ansi(capsys.readouterr().err)++ def test_the_command_failing_is_not_a_verdict(self, verify, capsys):+ """Exit 1 from verify is a missing library, not a ratchet result."""+ verify([], returncode=1, stderr="soup recipes verify needs torch")++ assert main() == 1+ assert "exited 1" in strip_ansi(capsys.readouterr().err)+++class TestTheExceptions:+ def test_every_pinned_name_is_a_shipped_config(self):+ from soup_cli.commands.recipes import _configs_to_verify++ shipped = {name for name, _cfg in _configs_to_verify(None, True)}++ assert set(EXCEPTIONS) <= shipped, sorted(set(EXCEPTIONS) - shipped)++ def test_every_pinned_name_has_a_reason(self):+ assert all(len(reason) > 40 for reason in EXCEPTIONS.values())