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(train): tip backend: unsloth only for a config that loads with it (#1736) (#1746)
Yang Baifeec5c6dce4f
diff --git a/changelog.d/0.75.1/1746.fixed.md b/changelog.d/0.75.1/1746.fixed.mdnew file mode 100644index 00000000..e6926e04--- /dev/null+++ b/changelog.d/0.75.1/1746.fixed.md@@ -0,0 +1 @@+- **`soup train` suggests `backend: unsloth` only for a config that would load with it (#1736 by @ybai08 in #1746).** With unsloth installed, every run on `backend: transformers` was told `Tip: unsloth is installed. Add backend: unsloth ...`, including configs the loader refuses as soon as that line is added: a task with no unsloth setup, `freeze_layers`, `rope_scaling_type`, `moe_lora` recipes. 38 of the 184 shipped templates and recipes on transformers got a tip they would be refused with. The tip now validates the config again with the backend changed and is printed only if that succeeds, so a new backend refusal is covered without a list in `train.py`. Nothing else about the run changes, and a machine without unsloth validates nothing twice.diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 33e3adb8..02ef12c8 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -197,9 +197,9 @@ training:alpha: 16```-Works with the tasks that have an unsloth setup: SFT (text; SFT vision and audio still run the transformers setup), DPO, GRPO, PPO, KTO, ORPO, SimPO, IPO, BCO, preference, Pretrain, Embedding and TTS. The others (`reward_model`, `prm`, `classifier`, `reranker`, `cross_encoder`, `distill`, `unlearn`, `moe_lora_routing`, `online_dpo` and `asr`) have no unsloth setup, so `backend: unsloth` is refused at config load for them (#1357). If unsloth is installed but not enabled, Soup will suggest it automatically.+Works with the tasks that have an unsloth setup: SFT (text; SFT vision and audio still run the transformers setup), DPO, GRPO, PPO, KTO, ORPO, SimPO, IPO, BCO, preference, Pretrain, Embedding and TTS. The others (`reward_model`, `prm`, `classifier`, `reranker`, `cross_encoder`, `distill`, `unlearn`, `moe_lora_routing`, `online_dpo` and `asr`) have no unsloth setup, so `backend: unsloth` is refused at config load for them (#1357). If unsloth is installed but not enabled, Soup suggests it, but only for a config that would still load with `backend: unsloth` (#1736): a config one of these refusals would stop gets no suggestion.-> **Tip:** Soup auto-detects unsloth. When installed, you'll see a hint during `soup train` if you haven't enabled it yet.+> **Tip:** Soup auto-detects unsloth. When it is installed, `soup train` prints a hint if you haven't enabled it yet and your config would load with it.## Cloud GPU Trainingdiff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex 59fdcf95..b1b69040 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -442,6 +442,39 @@ def _hardware_fit_preflight(cfg, gpu_info, *, allow_oom_attempt: bool) -> None:raise typer.Exit(1)+def _loads_on_unsloth(cfg) -> bool:+ """#1736 — would this config still load with ``backend: unsloth``?++ The tip that suggests the backend used to look at the backend alone, so it+ was also printed for configs the schema refuses on unsloth (a task with no+ unsloth setup, ``freeze_layers``, ``moe_lora``...). The schema is asked+ instead of a list kept here: the dumped config is validated again with the+ backend changed. Only that pass's ``ValidationError`` means no; anything+ else is a bug and must surface.+ """+ from pydantic import ValidationError++ from soup_cli.config.schema import SoupConfig++ try:+ SoupConfig.model_validate({**cfg.model_dump(), "backend": "unsloth"})+ except ValidationError:+ return False+ return True+++def _unsloth_tip_applies(cfg) -> bool:+ """Whether to suggest ``backend: unsloth``: only to a run on transformers,+ with unsloth installed, whose config would load with it (#1736). The+ installed check comes before the second validation, so a machine without+ unsloth validates nothing twice."""+ if cfg.backend != "transformers":+ return False+ from soup_cli.utils.unsloth import is_unsloth_available++ return is_unsloth_available() and _loads_on_unsloth(cfg)++def _apply_replay_overrides(cfg, *, replay, replay_ratio, replay_seed=None):"""Apply the ``--replay*`` flags, then RE-VALIDATE.@@ -1649,15 +1682,13 @@ def train(for err in ctx_errors:console.print(f"[yellow]Long-context warning:[/] {err}")- # Suggest unsloth if available but not being used- if cfg.backend == "transformers":- from soup_cli.utils.unsloth import is_unsloth_available-- if is_unsloth_available():- console.print(- "[dim]Tip: unsloth is installed. Add [bold]backend: unsloth[/dim]"- "[dim] to soup.yaml for 2-5x faster training.[/]"- )+ # Suggest unsloth if available but not being used, and only to a config the+ # loader would take with it (#1736).+ if _unsloth_tip_applies(cfg):+ console.print(+ "[dim]Tip: unsloth is installed. Add [bold]backend: unsloth[/dim]"+ "[dim] to soup.yaml for 2-5x faster training.[/]"+ )# #1613: cheap stripe roots validation ahead of confirmation, --dry-run,# dataset loading, and run creation.diff --git a/tests/test_issue1736_unsloth_tip_only_when_it_loads.py b/tests/test_issue1736_unsloth_tip_only_when_it_loads.pynew file mode 100644index 00000000..e46ab196--- /dev/null+++ b/tests/test_issue1736_unsloth_tip_only_when_it_loads.py@@ -0,0 +1,241 @@+"""#1736 — ``soup train`` tips ``backend: unsloth`` only for a config that loads with it.++With unsloth installed, every run on ``backend: transformers`` was told to add+``backend: unsloth``. The check looked at the backend alone, so the tip was also+printed for configs the loader refuses the moment that line is added: a task+with no unsloth setup, ``freeze_layers`` on sft, ``moe_lora`` recipes. 38 of+the 184 shipped templates and recipes on transformers were among them.++The tip now asks the schema: the dumped config is validated again with+``backend: unsloth``, and the tip is printed only if that succeeds. No list in+``train.py`` has to follow the validators.++unsloth is not installed here; ``is_unsloth_available`` is stubbed.+"""++from __future__ import annotations++import builtins+import json+import logging+import os+import warnings++import pytest+import yaml+from pydantic import ValidationError+from typer.testing import CliRunner++import soup_cli.utils.unsloth as unsloth_mod+from soup_cli.cli import app+from soup_cli.commands.train import _loads_on_unsloth, _unsloth_tip_applies+from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import TEMPLATES, SoupConfig+from soup_cli.recipes.catalog import RECIPES+from tests.conftest import strip_ansi++TIP = "Tip: unsloth is installed"++_SHIPPED = {+ **{f"template:{name}": text for name, text in TEMPLATES.items()},+ **{f"recipe:{name}": recipe.yaml_str for name, recipe in RECIPES.items()},+}+++def _raw(task="sft", **training):+ return {+ "base": "org/m", "task": task, "data": {"train": "./x.jsonl"}, "training": training,+ }+++# A config on transformers, and whether the loader takes it with backend: unsloth.+_CASES = {+ "plain sft": (_raw(), True),+ "sft with a lora rank": (_raw(lora={"r": 8}), True),+ "freeze_layers on sft (#1581)": (_raw(freeze_layers=2), False),+ "rope_scaling_type on sft (#1697)": (_raw(rope_scaling_type="dynamic"), False),+ "a task with no unsloth setup (#1357)": (_raw("classifier", num_labels=2), False),+ "distill": (_raw("distill", teacher_model="org/t"), False),+}+++def _loads(raw: dict) -> bool:+ """The oracle, independent of the helper: write the line and load the YAML."""+ try:+ load_config_from_string(yaml.safe_dump({**raw, "backend": "unsloth"}))+ except ValueError:+ return False+ return True+++class TestTheHelper:+ @pytest.mark.parametrize("case", list(_CASES))+ def test_it_answers_what_the_loader_answers(self, case):+ raw, loads = _CASES[case]+ cfg = load_config_from_string(yaml.safe_dump(raw))++ assert _loads(raw) is loads, "the case table is out of step with the schema"+ assert _loads_on_unsloth(cfg) is loads++ def test_the_config_it_was_given_is_left_alone(self):+ cfg = load_config_from_string(yaml.safe_dump(_raw(freeze_layers=2)))+ before = cfg.model_dump()++ _loads_on_unsloth(cfg)++ assert cfg.backend == "transformers"+ assert cfg.model_dump() == before++ def test_only_a_validation_error_means_no(self, monkeypatch):+ """A bug in the dump or in a validator must surface, not hide the tip."""+ cfg = load_config_from_string(yaml.safe_dump(_raw()))++ def broken(cls, *args, **kwargs):+ raise RuntimeError("not a validation error")++ monkeypatch.setattr(SoupConfig, "model_validate", classmethod(broken))++ with pytest.raises(RuntimeError, match="not a validation error"):+ _loads_on_unsloth(cfg)++ def test_a_validation_error_is_what_a_refusal_raises(self):+ """Guard on the test above: the refusals are ValidationErrors, so+ catching only that still covers every one of them."""+ cfg = load_config_from_string(yaml.safe_dump(_raw(freeze_layers=2)))++ with pytest.raises(ValidationError):+ SoupConfig.model_validate({**cfg.model_dump(), "backend": "unsloth"})++[email protected]("name", list(_SHIPPED))+class TestEveryShippedConfig:+ def test_the_tip_agrees_with_the_loader(self, name):+ """A template or recipe either gets the tip and loads with+ ``backend: unsloth``, or gets neither."""+ text = _SHIPPED[name]+ cfg = load_config_from_string(text)+ if cfg.backend != "transformers":+ pytest.skip("already on another backend: the tip is not offered")++ assert _loads_on_unsloth(cfg) is _loads(yaml.safe_load(text))++ def test_the_second_validation_is_silent_and_stays_off_the_disk(+ self, name, monkeypatch, capsys, caplog+ ):+ cfg = load_config_from_string(_SHIPPED[name])+ capsys.readouterr()+ caplog.clear()++ touched = []++ def spy(name, real):+ def call(*args, **kwargs):+ touched.append((name, args[:1]))+ return real(*args, **kwargs)++ return call++ for module, attr in (+ (builtins, "open"), (os, "stat"), (os, "lstat"), (os, "listdir"),+ (os, "scandir"), (os, "mkdir"), (os, "makedirs"), (os, "remove"),+ ):+ monkeypatch.setattr(module, attr, spy(attr, getattr(module, attr)))+ try:+ with caplog.at_level(logging.DEBUG), warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ _loads_on_unsloth(cfg)+ finally:+ monkeypatch.undo() # before pytest itself needs the disk again++ out = capsys.readouterr()+ assert touched == []+ assert (out.out, out.err) == ("", "")+ assert [str(w.message) for w in caught] == []+ assert [record.getMessage() for record in caplog.records] == []+++def test_some_shipped_configs_are_on_each_side():+ """Guard on the sweep: it must really see both answers."""+ answers = [+ _loads_on_unsloth(cfg)+ for cfg in (load_config_from_string(text) for text in _SHIPPED.values())+ if cfg.backend == "transformers"+ ]++ assert answers.count(True) > 100+ assert answers.count(False) > 20+++def _dry_run(tmp_path, monkeypatch, raw, *, installed=True) -> str:+ monkeypatch.setattr(unsloth_mod, "is_unsloth_available", lambda: installed)+ monkeypatch.chdir(tmp_path)+ rows = [+ {"instruction": f"q{n}", "output": f"a{n}", "text": f"t{n}", "label": n % 2}+ for n in range(20)+ ]+ (tmp_path / "x.jsonl").write_text(+ "".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8"+ )+ (tmp_path / "soup.yaml").write_text(yaml.safe_dump(raw), encoding="utf-8")++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ out = " ".join(strip_ansi(result.output).split())+ # A run that stopped early would also print no tip, and must not pass for+ # that reason: every case here has to get through the whole dry run, whose+ # last line comes after the place the tip is printed.+ assert result.exit_code == 0, out+ assert out.endswith("Config valid. Ready to train!"), out+ return out+++class TestSoupTrain:+ @pytest.mark.parametrize("case", list(_CASES))+ def test_the_tip_is_printed_only_for_a_config_that_would_load(+ self, tmp_path, monkeypatch, case+ ):+ raw, loads = _CASES[case]++ assert (TIP in _dry_run(tmp_path, monkeypatch, raw)) is loads++ def test_without_unsloth_installed_nothing_is_said(self, tmp_path, monkeypatch):+ assert TIP not in _dry_run(tmp_path, monkeypatch, _raw(), installed=False)++ def test_without_unsloth_installed_the_config_is_not_validated_again(+ self, tmp_path, monkeypatch+ ):+ import soup_cli.commands.train as train_mod++ def unexpected(cfg):+ raise AssertionError("validated again although unsloth is not installed")++ monkeypatch.setattr(train_mod, "_loads_on_unsloth", unexpected)++ assert TIP not in _dry_run(tmp_path, monkeypatch, _raw(), installed=False)+++class TestOnAnotherBackend:+ """The tip is for a run on transformers. A run already on unsloth, or on+ mlx, is asked nothing: not whether unsloth is installed, and not whether its+ config would load with it. Asked of the function, not through a dry run,+ which gets a different distance on each of these backends per platform."""++ @pytest.mark.parametrize("backend", ["unsloth", "mlx"])+ def test_no_tip_and_no_questions(self, monkeypatch, backend):+ import soup_cli.commands.train as train_mod++ def unexpected(*args):+ raise AssertionError(f"asked on backend: {backend}")++ monkeypatch.setattr(unsloth_mod, "is_unsloth_available", unexpected)+ monkeypatch.setattr(train_mod, "_loads_on_unsloth", unexpected)+ cfg = load_config_from_string(yaml.safe_dump({**_raw(), "backend": backend}))++ assert _unsloth_tip_applies(cfg) is False++ def test_on_transformers_it_is_asked_and_answered(self, monkeypatch):+ """Guard on the test above: the same function says yes on transformers."""+ monkeypatch.setattr(unsloth_mod, "is_unsloth_available", lambda: True)+ cfg = load_config_from_string(yaml.safe_dump(_raw()))++ assert _unsloth_tip_applies(cfg) is True