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
test(peft): count the MLX LoRA builder in the LoRA+ wiring scan (#1324 follow-up) (#1516)
Mohammad Hijjawi65265a8b86ab
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 07b73f08..841d84fb 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -403,7 +403,7 @@ training:alpha: 16```-- **Compatibility:** Wired on every Trainer-based task that trains a LoRA adapter, including the preference and RL tasks (`dpo`, `kto`, `orpo`, `simpo`, `ipo`, `bco`, `grpo`, `online_dpo`, `ppo`, `reward_model`, `distill`). Most attach the LoRA+ optimizer once the trainer is built; `ppo` passes it to the trainer's constructor instead, because trl's PPO trainer builds its optimizer and LR scheduler eagerly, and adds the value model to it at the base learning rate, as trl's default optimizer does. `classifier`, `reranker`, `cross_encoder` and `asr` full fine-tune by default, so LoRA+ applies there only with `classifier_lora: true` / `asr_lora: true` and `lora.r > 0`. Refused at config parse on tasks with no trainable LoRA $B$ matrix: `prm` (full fine-tune), `moe_lora_routing` (only the routing gate trains), and `classifier` / `reranker` / `cross_encoder` / `asr` without their LoRA flag. Also refused on `unlearn`, which runs its own optimizer loop rather than a Trainer. Refused with `lora.use_vera` (VeRA trains scaling vectors, not $A$/$B$ matrices, so every trainable tensor would run at `lr * ratio`). Also refused on the `mlx` backend (#1324): the MLX optimizer Soup builds (`trainer/mlx_optim.py`) runs every LoRA tensor at one learning rate (no parameter groups), so the ratio would be silently ignored; remove it or use `backend: transformers`. Mutually exclusive with `use_lorafa`.+- **Compatibility:** Wired on every Trainer-based task that trains a LoRA adapter, including the preference and RL tasks (`dpo`, `kto`, `orpo`, `simpo`, `ipo`, `bco`, `grpo`, `online_dpo`, `ppo`, `reward_model`, `distill`). Most attach the LoRA+ optimizer once the trainer is built; `ppo` passes it to the trainer's constructor instead, because trl's PPO trainer builds its optimizer and LR scheduler eagerly, and adds the value model to it at the base learning rate, as trl's default optimizer does. `classifier`, `reranker`, `cross_encoder` and `asr` full fine-tune by default, so LoRA+ applies there only with `classifier_lora: true` / `asr_lora: true` and `lora.r > 0`. Refused at config parse on tasks with no trainable LoRA $B$ matrix: `prm` (full fine-tune), `moe_lora_routing` (only the routing gate trains), and `classifier` / `reranker` / `cross_encoder` / `asr` without their LoRA flag. Also refused on `unlearn`, which runs its own optimizer loop rather than a Trainer. Refused with `lora.use_vera` (VeRA trains scaling vectors, not $A$/$B$ matrices, so every trainable tensor would run at `lr * ratio`). Also refused on the `mlx` backend (#1324): the MLX optimizer Soup builds (`trainer/mlx_optim.py`) runs every LoRA tensor at one learning rate (no parameter groups), so the ratio would be silently ignored; remove it or use `backend: transformers`. `backend: unsloth` gets the same LoRA+ optimizer as `transformers`. Mutually exclusive with `use_lorafa`.## LoRA-FA (Frozen-A LoRA)diff --git a/tests/test_issue1324_mlx_loraplus_refusal.py b/tests/test_issue1324_mlx_loraplus_refusal.pyindex 779d125c..9fda94cd 100644--- a/tests/test_issue1324_mlx_loraplus_refusal.py+++ b/tests/test_issue1324_mlx_loraplus_refusal.py@@ -132,3 +132,113 @@ def test_mlx_doctor_table_has_no_loraplus_row():# A refused-at-load field must not appear in the doctor table (#958).names = {entry.field for entry in _MLX_SFT}assert "training.loraplus_lr_ratio" not in names+++# --------------------------------------------------------------------------+# More paths to the same refusal, and the controls around it+# --------------------------------------------------------------------------++_REFUSAL = "training.loraplus_lr_ratio is not implemented on backend='mlx'"++[email protected]("ratio", ["16", "1.0", "0.5", "2"])+def test_every_ratio_is_refused_on_mlx(ratio):+ """The refusal is about the backend, not the size of the ratio."""+ text = _MLX_LORAPLUS.replace("loraplus_lr_ratio: 16", f"loraplus_lr_ratio: {ratio}")+ with pytest.raises(ValueError) as excinfo:+ load_config_from_string(text)+ assert _REFUSAL in _plain(str(excinfo.value))+++def test_direct_construction_is_refused_too():+ """``soup sweep``, ``soup rewind`` and autopilot build ``SoupConfig`` directly,+ without going through the YAML loader."""+ from soup_cli.config.schema import SoupConfig++ with pytest.raises(ValueError) as excinfo:+ SoupConfig(+ base="mlx-community/Qwen2.5-0.5B-Instruct-4bit",+ task="sft",+ backend="mlx",+ data={"train": "t.jsonl"},+ training={"loraplus_lr_ratio": 16.0},+ )+ assert _REFUSAL in _plain(str(excinfo.value))+++def test_an_explicit_null_ratio_still_loads_on_mlx():+ cfg = load_config_from_string(+ _MLX_LORAPLUS.replace("loraplus_lr_ratio: 16", "loraplus_lr_ratio: null")+ )+ assert cfg.backend == "mlx"+ assert cfg.training.loraplus_lr_ratio is None++[email protected]("backend", ["transformers", "unsloth"])[email protected]("task, data_format", [("pretrain", "plaintext"), ("dpo", "dpo")])+def test_the_wired_backends_keep_the_ratio_beyond_sft(backend, task, data_format):+ """#1080 wired LoRA+ after the backend branch of these trainers too, so the+ refusal must stay on mlx and not spread to the other backends' tasks."""+ text = (+ _transformers_variant(backend)+ .replace("task: sft", f"task: {task}")+ .replace("format: alpaca", f"format: {data_format}")+ )+ cfg = load_config_from_string(text)+ assert cfg.backend == backend+ assert cfg.task == task+ assert cfg.training.loraplus_lr_ratio == pytest.approx(16.0)+++def _write_runnable_config(tmp_path: Path) -> Path:+ train = tmp_path / "train.jsonl"+ train.write_text('{"instruction": "q", "output": "a"}\n' * 4, encoding="utf-8")+ path = tmp_path / "soup.yaml"+ path.write_text(+ _MLX_LORAPLUS.replace("./data/train.jsonl", train.as_posix()).replace(+ "./output", (tmp_path / "out").as_posix()+ ),+ encoding="utf-8",+ )+ return path+++def test_plain_soup_train_stops_at_config_load(tmp_path, monkeypatch):+ """Not only ``--dry-run``: a real ``soup train`` must stop before the data or+ the model is touched."""+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ monkeypatch.chdir(tmp_path)+ config = _write_runnable_config(tmp_path)++ result = CliRunner().invoke(app, ["train", "--config", str(config)])++ output = _plain(result.output)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert _REFUSAL in output, output+ for later_line in ("Config valid.", "Ready to train", "Data OK", "Training Setup"):+ assert later_line not in output, (later_line, output)+++def test_soup_doctor_config_reports_the_config_as_unloadable(tmp_path, capsys):+ """``soup doctor --config`` printed its all-clear for this config before+ #1324; an unloadable config is exit 2."""+ import typer++ from soup_cli.commands.doctor import doctor++ config = _write_runnable_config(tmp_path)++ with pytest.raises(typer.Exit) as excinfo:+ doctor(nccl=False, disk=False, config=str(config))++ assert excinfo.value.exit_code == 2+ assert _REFUSAL in _plain(capsys.readouterr().out)+++def test_the_loraplus_docs_state_the_mlx_refusal_and_the_unsloth_wiring():+ root = Path(__file__).resolve().parents[1]+ text = (root / "docs" / "peft-and-efficiency.md").read_text(encoding="utf-8")+ section = text.split("## LoRA+ (Differentiated Learning Rates)", 1)[1]+ flat = " ".join(section.split("\n## ", 1)[0].split())+ assert "Also refused on the `mlx` backend (#1324)" in flat, flat+ assert "`backend: unsloth` gets the same LoRA+ optimizer as `transformers`" in flat, flatdiff --git a/tests/test_issue724_loraplus_wiring_coverage.py b/tests/test_issue724_loraplus_wiring_coverage.pyindex bf1bc1c2..229643fc 100644--- a/tests/test_issue724_loraplus_wiring_coverage.py+++ b/tests/test_issue724_loraplus_wiring_coverage.py@@ -43,6 +43,9 @@ A wrapper counts as building a LoRA adapter when it calls ``get_peft_model``itself OR hands a ``peft_config=`` to a TRL trainer that applies the adapter inits own ``__init__`` (``online_dpo.py``). Until #745's second round the scanonly knew the first shape, so online_dpo ignored ``loraplus_lr_ratio`` unseen.+The MLX trainer builds its adapter with mlx-lm's ``linear_to_lora_layers``+instead; until #1324 the scan did not count it, so ``backend: mlx`` ignored+``loraplus_lr_ratio`` unseen too.Coverage is derived by SCANNING ``soup_cli/trainer/`` (following``tests/test_issue359_deepspeed_guard_coverage.py``) rather than a hand-written@@ -67,7 +70,7 @@ _TRAINER_SOURCES = sorted(_TRAINER_DIR.glob("*.py"))#: that applies the adapter inside its own ``__init__`` (``online_dpo.py``). The#: second shape is detected on the AST (see :func:`_hands_peft_config_to_trl`),#: since ``self.peft_config = ...`` assignments share the spelling.-_BUILDS_PEFT = re.compile(r"get_peft_model\s*\(")+_BUILDS_PEFT = re.compile(r"(?:get_peft_model|linear_to_lora_layers)\s*\(")#: The two wiring shapes (see the module docstring): attach after construction,#: or build before it and inject via ``optimizers=``. A wrapper counts as wiring#: LoRA+ if it does either.@@ -88,6 +91,12 @@ _LORAPLUS_EXEMPT = {"is refused at config parse for task='unlearn' instead of being silently ""ignored (see test_unlearn_loraplus_is_refused_at_config_parse)."),+ "mlx_sft.py": (+ "builds its adapter with mlx-lm's linear_to_lora_layers and its optimizer "+ "from one learning rate (plan_optimizer), so there is no LoRA B group to "+ "give lr * ratio. loraplus_lr_ratio is refused at config parse for "+ "backend='mlx' instead (#1324, tests/test_issue1324_mlx_loraplus_refusal.py)."+ ),}@@ -268,6 +277,17 @@ class TestLoraPlusWiringCoverage:"_LORAPLUS_EXEMPT — it is wired, not exempt.")+ def test_the_test_files_an_exemption_names_exist(self):+ """A reason that points at a test file is only evidence while that file+ exists; a rename would otherwise leave the pointer stale without a word."""+ repo_root = _TRAINER_DIR.parents[2]+ for name, reason in _LORAPLUS_EXEMPT.items():+ for rel in re.findall(r"tests/[\w/]+\.py", reason):+ assert (repo_root / rel).is_file(), (+ f"the _LORAPLUS_EXEMPT reason for {name} names {rel}, which "+ "does not exist; point it at the file that pins the refusal."+ )+def test_the_patterns_would_catch_the_unwired_shape(self):"""A scanner nobody has watched fail is indistinguishable from a brokenone. All three detectors are exercised here, comments included."""@@ -302,6 +322,14 @@ class TestLoraPlusWiringCoverage:the scan could not see it, so it silently ignored loraplus_lr_ratio."""assert _builds_peft(_TRAINER_DIR / "online_dpo.py")+ def test_the_mlx_trainer_counts_as_a_peft_builder(self):+ """#1324: mlx-lm applies LoRA through linear_to_lora_layers, not peft.+ Before the scan knew that call, mlx_sft.py was neither wired nor exempt+ and backend: mlx ignored loraplus_lr_ratio without a test noticing."""+ assert _BUILDS_PEFT.search(" linear_to_lora_layers(model, n, cfg)")+ assert not _source_builds_peft(" # linear_to_lora_layers(model) runs later")+ assert _builds_peft(_TRAINER_DIR / "mlx_sft.py")+def test_a_comment_mentioning_the_call_does_not_satisfy_it(self):"""The positive check reads code, not prose — otherwise the note thatexplains the wiring would pass without calling it."""