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
fix(cli): name gate-command input errors and missing train modules (#1833)
Abhinay Kumard93091f78154
diff --git a/changelog.d/0.76.0/1833.fixed.md b/changelog.d/0.76.0/1833.fixed.mdnew file mode 100644index 00000000..d898b0af--- /dev/null+++ b/changelog.d/0.76.0/1833.fixed.md@@ -0,0 +1 @@+- Gate-style commands now name the problem in their error text instead of printing a bare value: `soup expect` reports `data file not found: <path>` / `suite file not found: <path>` for a missing input, `soup lock check`/`soup lock show` name a corrupt lock file and say its JSON is invalid, and `soup draft measure`/`soup draft distill` point at the missing `[train]` extra when `transformers` is absent. `soup expect`'s module docstring is also corrected (a suite failure exits 2, not 3). Exit codes are unchanged (#1830 in #1833).diff --git a/src/soup_cli/commands/draft.py b/src/soup_cli/commands/draft.pyindex d7b46cc5..70fc7cb2 100644--- a/src/soup_cli/commands/draft.py+++ b/src/soup_cli/commands/draft.py@@ -98,6 +98,45 @@ def _fail(message: str, code: int = 1) -> NoReturn:raise typer.Exit(code)+# Top-level import names declared by pyproject's ``[train]`` optional-dependency+# group. Kept in sync with that group by hand (the install names there match+# their import names). Only a module in this set means the ``[train]`` extra is+# the right fix; a model's ``trust_remote_code`` config can import anything+# (einops, flash_attn, ...), and blaming the extra for those would send the user+# the wrong way.+_TRAIN_EXTRA_MODULES = frozenset(+ {+ "torch",+ "transformers",+ "peft",+ "trl",+ "requests",+ "datasets",+ "bitsandbytes",+ "accelerate",+ }+)+++def _config_read_error(exc: Exception) -> str:+ """Message for a failed ``config`` read, hinting ``[train]`` only when apt.++ A ``ModuleNotFoundError`` for a module the ``[train]`` extra provides means+ the extra is not installed, so point the user at it. Any other failure —+ including a missing module pulled in by a model's remote code — surfaces+ verbatim, without the hint. ``_fail`` escapes, so the ``[train]`` bracket+ renders literally.+ """+ message = f"could not read model config: {exc}"+ missing = (getattr(exc, "name", None) or "").split(".")[0]+ if isinstance(exc, ModuleNotFoundError) and missing in _TRAIN_EXTRA_MODULES:+ message += (+ '. The training extra is not installed; install it with: '+ 'pip install "soup-cli[train]"'+ )+ return message++def _read_jsonl(path: str, label: str, max_rows: int) -> list[dict]:"""Read a JSONL file: cwd-contained, O_NOFOLLOW, size- and row-capped."""enforce_under_cwd_and_no_symlink(path, label)@@ -157,7 +196,7 @@ def _pair_vocab_sizes_or_fail(_vocab_size_of(draft_id, draft_trc),)except Exception as exc: # noqa: BLE001 — surface as a friendly CLI error- _fail(f"could not read model config: {exc}")+ _fail(_config_read_error(exc))def _write_draft_report(report: AcceptanceReport, output: str) -> None:@@ -617,7 +656,7 @@ def distill(target_vocab = _vocab_size_of(target, target_trc)draft_vocab = _vocab_size_of(draft_base, draft_trc)except Exception as exc: # noqa: BLE001 — surface as a friendly CLI error- _fail(f"could not read model config: {exc}")+ _fail(_config_read_error(exc))cross_tokenizer = target_vocab != draft_vocabif not cross_tokenizer:diff --git a/src/soup_cli/commands/expect.py b/src/soup_cli/commands/expect.pyindex b2d771a5..bbb93ee6 100644--- a/src/soup_cli/commands/expect.py+++ b/src/soup_cli/commands/expect.py@@ -1,8 +1,9 @@"""soup expect — Expectations suite for chat data (v0.69.0 Part B).-Runs a YAML suite of expectations against a JSONL dataset. Exit code 3 on-suite failure (matches v0.55 / v0.56 / v0.64 / v0.65 gate convention) so CI-pipelines can gate on dataset quality regressions without parsing output.+Runs a YAML suite of expectations against a JSONL dataset. A suite failure+exits 2 (EXIT_GATE_FAILED, the gate convention), so CI pipelines can gate on+dataset quality regressions without parsing output; a usage or input error+(missing/invalid paths) exits 3 (EXIT_USAGE_ERROR). See utils/exit_codes.py."""from __future__ import annotations@@ -36,11 +37,11 @@ def _load_jsonl_rows(data_path: str) -> List[Mapping[str, object]]:if not isinstance(data_path, str) or not data_path:raise ValueError("data path must be a non-empty string")if not os.path.lexists(data_path):- raise FileNotFoundError(data_path)+ raise FileNotFoundError(f"data file not found: {data_path!r}")enforce_under_cwd_and_no_symlink(data_path, "data path")real = os.path.realpath(data_path)if not os.path.isfile(real):- raise FileNotFoundError(data_path)+ raise FileNotFoundError(f"data file not found: {data_path!r}")if os.path.getsize(real) > _MAX_DATA_BYTES:raise ValueError(f"data file exceeds {_MAX_DATA_BYTES} bytes")rows: List[Mapping[str, object]] = []diff --git a/src/soup_cli/utils/expectations.py b/src/soup_cli/utils/expectations.pyindex b4d550cd..9884ed9f 100644--- a/src/soup_cli/utils/expectations.py+++ b/src/soup_cli/utils/expectations.py@@ -944,10 +944,10 @@ def load_suite_yaml(path: object) -> SuiteSpec:raise TypeError("path must be a string")enforce_under_cwd_and_no_symlink(path, "suite path")if not os.path.lexists(path):- raise FileNotFoundError(path)+ raise FileNotFoundError(f"suite file not found: {path!r}")real = os.path.realpath(path)if not os.path.isfile(real):- raise FileNotFoundError(real)+ raise FileNotFoundError(f"suite file not found: {path!r}")if os.path.getsize(real) > _MAX_FILE_BYTES:raise ValueError(f"suite file exceeds {_MAX_FILE_BYTES} bytes")with open(real, "r", encoding="utf-8") as handle:diff --git a/src/soup_cli/utils/soup_lock.py b/src/soup_cli/utils/soup_lock.pyindex 7c90d76b..8cc1538a 100644--- a/src/soup_cli/utils/soup_lock.py+++ b/src/soup_cli/utils/soup_lock.py@@ -179,7 +179,10 @@ def read_lock(path: str) -> SoupLock:f"lock file size {st.st_size} > {_MAX_FILE_BYTES}")with open(real, encoding="utf-8") as fh:- data = json.load(fh)+ try:+ data = json.load(fh)+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:+ raise ValueError(f"lock file {path!r} is not valid JSON: {exc}") from excif not isinstance(data, dict):raise ValueError("lock file root must be JSON object")# SoupLock __post_init__ does the rest of the validationdiff --git a/tests/test_issue1830_cli_message_gaps.py b/tests/test_issue1830_cli_message_gaps.pynew file mode 100644index 00000000..ee895c1d--- /dev/null+++ b/tests/test_issue1830_cli_message_gaps.py@@ -0,0 +1,298 @@+"""#1830 — four small gaps in what the gate-style commands print.++The exit codes were already right (0 pass, 2 gate failure, 3 usage/input+error, 1 runtime); only the text was thin. Each gap is independent:++1. ``soup expect`` with a missing data or suite file printed only the bare+ path. It now names the problem (``data file not found: ...`` /+ ``suite file not found: ...``), still exiting 3.+2. ``soup lock check`` / ``soup lock show`` on a corrupt lock file printed the+ raw ``json`` error without naming the file. ``read_lock`` now re-raises a+ ``ValueError`` that names the file and says the JSON is invalid (exit 3).+3. The module docstring of ``commands/expect.py`` claimed "Exit code 3 on+ suite failure"; a suite failure exits 2. The docstring is corrected.+4. ``soup draft measure`` / ``soup draft distill`` on a core-only install+ printed ``could not read model config: No module named 'transformers'``+ with no hint. They now point at the ``[train]`` extra (exit 1 kept).++Every test asserts the message a user would grep for; with the fix reverted,+each one fails (mutation check).+"""++from __future__ import annotations++import json++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.commands import draft as draft_mod+from soup_cli.utils.exit_codes import EXIT_RUNTIME_ERROR, EXIT_USAGE_ERROR+from tests.conftest import strip_ansi++_VALID_SUITE = "expectations:\n - name: expect_no_pii\n"+++def _plain(text: "str | None") -> str:+ """ANSI-stripped, whitespace-collapsed output (Rich wraps at 80 columns in+ CliRunner, so a long message can span lines)."""+ return " ".join(strip_ansi(text).split())+++# ---------------------------------------------------------------------------+# 1. soup expect — missing data / suite file names the problem+# ---------------------------------------------------------------------------+++def test_expect_missing_data_file_names_the_problem(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "suite.yaml").write_text(_VALID_SUITE, encoding="utf-8")++ result = CliRunner().invoke(app, ["expect", "missing.jsonl", "suite.yaml"])++ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))+ assert "data file not found: 'missing.jsonl'" in _plain(result.output)+++def test_expect_missing_suite_file_names_the_problem(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "data.jsonl").write_text(+ json.dumps({"text": "hi"}) + "\n", encoding="utf-8"+ )++ result = CliRunner().invoke(app, ["expect", "data.jsonl", "missing.yaml"])++ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))+ assert "suite file not found: 'missing.yaml'" in _plain(result.output)+++def test_expect_data_path_that_is_a_directory_names_the_problem(tmp_path, monkeypatch):+ """A data path that exists but is a directory hits the not-a-regular-file+ branch, which must name it like the missing-file branch does."""+ monkeypatch.chdir(tmp_path)+ (tmp_path / "suite.yaml").write_text(_VALID_SUITE, encoding="utf-8")+ (tmp_path / "data.jsonl").mkdir()++ result = CliRunner().invoke(app, ["expect", "data.jsonl", "suite.yaml"])++ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))+ assert "data file not found: 'data.jsonl'" in _plain(result.output)+++def test_expect_suite_path_that_is_a_directory_names_the_problem(tmp_path, monkeypatch):+ """A suite path that exists but is a directory hits the not-a-regular-file+ branch for the suite, which must name it too."""+ monkeypatch.chdir(tmp_path)+ (tmp_path / "data.jsonl").write_text(+ json.dumps({"text": "hi"}) + "\n", encoding="utf-8"+ )+ (tmp_path / "suite.yaml").mkdir()++ result = CliRunner().invoke(app, ["expect", "data.jsonl", "suite.yaml"])++ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))+ assert "suite file not found: 'suite.yaml'" in _plain(result.output)+++# ---------------------------------------------------------------------------+# 2. soup lock check / show — a corrupt lock file is named as invalid JSON+# ---------------------------------------------------------------------------+++ "args",+ [+ ["lock", "show", "soup.lock"],+ [+ "lock", "check", "soup.lock",+ "--base-sha", "0" * 64,+ "--dataset-sha", "0" * 64,+ "--env-hash", "0" * 64,+ "--base-model", "gpt2",+ ],+ ],+ ids=["show", "check"],+)+def test_lock_commands_name_a_corrupt_lock_file(tmp_path, monkeypatch, args):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "soup.lock").write_text("garbage:", encoding="utf-8")++ result = CliRunner().invoke(app, args)++ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "not valid JSON" in plain+ assert "soup.lock" in plain+++def test_lock_show_names_a_lock_file_that_is_not_utf8(tmp_path, monkeypatch):+ """A lock file that is valid bytes but not UTF-8 raises ``UnicodeDecodeError``+ inside ``json.load``; that half of the ``except`` must also name it (the+ corrupt-file test above only exercises the ``JSONDecodeError`` half)."""+ monkeypatch.chdir(tmp_path)+ (tmp_path / "soup.lock").write_bytes(b"\xff\xfe\x00{")++ result = CliRunner().invoke(app, ["lock", "show", "soup.lock"])++ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "not valid JSON" in plain+ assert "soup.lock" in plain+++# ---------------------------------------------------------------------------+# 3. commands/expect.py module docstring matches the real exit codes+# ---------------------------------------------------------------------------+++def test_expect_module_docstring_does_not_claim_exit_3_on_suite_failure():+ from soup_cli.commands import expect as expect_mod++ doc = expect_mod.__doc__ or ""+ assert "Exit code 3 on suite failure" not in doc+ # A suite failure exits 2 (EXIT_GATE_FAILED); 3 is the usage/input error.+ assert "exits 2" in doc+++# ---------------------------------------------------------------------------+# 4. soup draft measure / distill — a missing [train] extra points the user at it+# ---------------------------------------------------------------------------+++def _raise_missing_transformers(*args, **kwargs):+ # A real ``import transformers`` failure sets ``name`` on the exception; the+ # hint keys off that, so the stub must set it too.+ raise ModuleNotFoundError("No module named 'transformers'", name="transformers")+++def test_draft_measure_hints_the_train_extra_when_transformers_is_absent(+ tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "prompts.jsonl").write_text(+ json.dumps({"prompt": "hello"}) + "\n", encoding="utf-8"+ )+ monkeypatch.setattr(draft_mod, "_vocab_size_of", _raise_missing_transformers)++ result = CliRunner().invoke(+ app,+ ["draft", "measure", "--target", "gpt2", "--draft", "gpt2",+ "--prompts", "prompts.jsonl"],+ )++ assert result.exit_code == EXIT_RUNTIME_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "could not read model config" in plain+ assert "soup-cli[train]" in plain+++def test_draft_measure_does_not_blame_the_extra_for_an_unrelated_module(+ tmp_path, monkeypatch+):+ """A model's ``trust_remote_code`` config can import anything; a missing+ module outside the ``[train]`` extra (here ``einops``) must surface verbatim+ without the ``[train]`` hint, which would send the user the wrong way."""+ monkeypatch.chdir(tmp_path)+ (tmp_path / "prompts.jsonl").write_text(+ json.dumps({"prompt": "hello"}) + "\n", encoding="utf-8"+ )++ def boom(*args, **kwargs):+ raise ModuleNotFoundError("No module named 'einops'", name="einops")++ monkeypatch.setattr(draft_mod, "_vocab_size_of", boom)++ result = CliRunner().invoke(+ app,+ ["draft", "measure", "--target", "gpt2", "--draft", "gpt2",+ "--prompts", "prompts.jsonl"],+ )++ assert result.exit_code == EXIT_RUNTIME_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "No module named 'einops'" in plain+ assert "soup-cli[train]" not in plain+def test_draft_measure_hints_the_train_extra_for_a_dotted_submodule(+ tmp_path, monkeypatch+):+ """A real missing-dependency error names the dotted submodule that failed to+ import (e.g. ``transformers.models.llama``), not the bare top-level package.+ The hint keys off the top-level name, so it must still fire for a submodule+ of a ``[train]`` package -- pinning the ``.split(".")[0]`` that extracts it."""+ monkeypatch.chdir(tmp_path)+ (tmp_path / "prompts.jsonl").write_text(+ json.dumps({"prompt": "hello"}) + "\n", encoding="utf-8"+ )++ def boom(*args, **kwargs):+ raise ModuleNotFoundError(+ "No module named 'transformers.models.llama'",+ name="transformers.models.llama",+ )++ monkeypatch.setattr(draft_mod, "_vocab_size_of", boom)++ result = CliRunner().invoke(+ app,+ ["draft", "measure", "--target", "gpt2", "--draft", "gpt2",+ "--prompts", "prompts.jsonl"],+ )++ assert result.exit_code == EXIT_RUNTIME_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "could not read model config" in plain+ assert "soup-cli[train]" in plain+++def test_draft_measure_does_not_hint_when_the_module_name_is_unset(+ tmp_path, monkeypatch+):+ """A ``ModuleNotFoundError`` with no ``name`` (``name=None``) cannot be+ attributed to the ``[train]`` extra, so the failure surfaces verbatim with+ no hint -- pinning the ``or ""`` guard against a ``None`` name."""+ monkeypatch.chdir(tmp_path)+ (tmp_path / "prompts.jsonl").write_text(+ json.dumps({"prompt": "hello"}) + "\n", encoding="utf-8"+ )++ def boom(*args, **kwargs):+ raise ModuleNotFoundError("boom")++ monkeypatch.setattr(draft_mod, "_vocab_size_of", boom)++ result = CliRunner().invoke(+ app,+ ["draft", "measure", "--target", "gpt2", "--draft", "gpt2",+ "--prompts", "prompts.jsonl"],+ )++ assert result.exit_code == EXIT_RUNTIME_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "boom" in plain+ assert "soup-cli[train]" not in plain+++++def test_draft_distill_hints_the_train_extra_when_transformers_is_absent(+ tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "data.jsonl").write_text(+ json.dumps({"messages": [{"role": "user", "content": "hi"},+ {"role": "assistant", "content": "ok"}]}) + "\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(draft_mod, "_vocab_size_of", _raise_missing_transformers)++ result = CliRunner().invoke(+ app,+ ["draft", "distill", "--target", "gpt2", "--draft-base", "gpt2",+ "--data", "data.jsonl", "--output", "draft_out"],+ )++ assert result.exit_code == EXIT_RUNTIME_ERROR, (result.output, repr(result.exception))+ plain = _plain(result.output)+ assert "could not read model config" in plain+ assert "soup-cli[train]" in plain