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(mlx): add native SFT loss watchdog (#1989) (#2115)
AmixDigital6d63d1437630
diff --git a/changelog.d/0.76.0/2115.added.md b/changelog.d/0.76.0/2115.added.mdnew file mode 100644index 00000000..10e63635--- /dev/null+++ b/changelog.d/0.76.0/2115.added.md@@ -0,0 +1 @@+- MLX text SFT supports the loss watchdog: consecutive high-loss reports stop at a completed optimizer update, save the last loadable adapter and record the stop reason and actual completed work. (#2115, closes #1989 by @Amix29)diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 96d86401..7403b6a8 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -119,6 +119,12 @@ Soup triggers each evaluation when mlx-lm asks for the next training batch,which mlx-lm 0.31 and 0.32 do only after the previous step; if a release readsbatches ahead, the run says once that the evaluation ran before its update.+MLX text SFT also supports the opt-in [loss watchdog](peft-and-efficiency.md#loss-watchdog)+with the existing threshold and patience fields. Its reports count completed+optimizer updates; a triggering report stops further updates and saves the last+adapter with the actual completed work and termination reason in+`adapter_config.json`. Recovery and watchdogs on preference tasks remain refused.+```yamlbase: mlx-community/Llama-3.2-3B-Instruct-4bittask: sftdiff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex a34fffc6..87434f8f 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -721,10 +721,40 @@ Auto-stop training when loss spikes above a threshold (like Axolotl's `loss_watctraining:loss_watchdog: true # Enable loss spike detectionloss_watchdog_threshold: 3.0 # Stop if loss exceeds this value- loss_watchdog_patience: 5 # Consecutive steps above threshold before stopping+ loss_watchdog_patience: 5 # Consecutive loss reports above threshold before stopping```-> **Backend Note:** Setting `loss_watchdog: true` is refused on `backend: mlx` at config validation (Soup does not implement the watchdog on the MLX callback, which has no stop control).+The comparison is strictly `loss > loss_watchdog_threshold`; a report at or below+the threshold resets patience. A missing/`None` loss neither advances nor resets it.++**MLX text SFT:** reports occur every `logging_steps` completed optimizer updates+(every `logging_steps × gradient_accumulation_steps` micro-batches), plus at the+end of the budget. Each loss averages the micro-batches since the preceding+report. On the triggering report, training stops immediately after its completed+update, with no later update or partial accumulation group. Soup saves the current+`adapters.safetensors` and loadable `adapter_config.json`, runs the final validation+when `eval_steps` is configured, and releases the display and rewind recorder.+This saves the last state, not a best-loss or rollback checkpoint; a high loss can+already have affected its weights. No full optimizer-state resume is claimed.++The returned summary and `adapter_config.json` record `training_outcome`+(`stopped` or `completed`), `stop_reason` (`loss_watchdog` or `budget_completed`),+`completed_updates` and `completed_iterations`. `total_steps` remains in MLX+micro-batch units and counts only executed iterations. A controlled stop is a+successful command after saving; the CLI says **Training Stopped**, while the+tracker's `completed` status means the run finalized successfully. Consult the+adapter metadata for the termination reason. Non-finite reported training loss+raises an error immediately; save failures, other errors and keyboard interruption+propagate rather than becoming successful watchdog stops.++**Difference from Transformers:** its current watchdog applies the threshold+comparison to the losses reported by Trainer, with no separate non-finite check+in that callback. On MLX, a reported NaN, +Inf or -Inf is an immediate training+error, regardless of patience. The Transformers callback is unchanged.++With the watchdog disabled, existing MLX report cadence and behavior are unchanged.+Other MLX tasks/modalities still refuse it, and MLX continues to refuse+`loss_spike_recovery` because checkpoint recovery is a separate feature.## Training Stability & Auto-Tuning@@ -784,7 +814,8 @@ training:loss_spike_recovery_lr_decay: 0.5 # halve LR each recovery```-> **Backend Note:** Setting `loss_spike_recovery: true` is refused on `backend: mlx` at config validation (spike recovery is driven by the watchdog and the watchdog cannot fire on MLX).+> **Backend Note:** Setting `loss_spike_recovery: true` is refused on `backend: mlx`+> at config validation: MLX does not implement checkpoint rollback or recovery hints.### Convergence Detectordiff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex 6af7d701..1991fddd 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -2097,7 +2097,9 @@ def train(f"{merge_hint}\n"f"Export GGUF: [bold]soup export --model {result['output_dir']}[/]\n"f"Run details: [bold]soup runs show {run_id}[/]",- title="[bold green]Training Complete![/]",+ title=("[bold yellow]Training Stopped — Loss watchdog[/]"+ if result.get("stop_reason") == "loss_watchdog"+ else "[bold green]Training Complete![/]"),))diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 90b8b519..c2a50558 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -8660,10 +8660,9 @@ class SoupConfig(BaseModel):@model_validator(mode="after")def _validate_callback_monitoring_task_compat(self) -> "SoupConfig":"""#802, #1069 — prm, moe_lora_routing, and unlearn attach no- SoupTrainerCallback, and on backend=mlx the callback has no stop control,- no checkpoint-rollback path, and no VRAM budget, so reject loss_watchdog,- loss_spike_recovery, and grad_accum_auto_tune when set to True on these- tasks or on backend=mlx.+ SoupTrainerCallback. MLX text SFT implements its own watchdog (#1989),+ but other native tasks do not; MLX has no checkpoint-recovery path or+ VRAM budget for grad_accum_auto_tune."""unsupported = ("prm", "moe_lora_routing", "unlearn")if self.task in unsupported:@@ -8688,14 +8687,14 @@ class SoupConfig(BaseModel):if getattr(tcfg, "loss_spike_recovery", False):raise ValueError(f"training.loss_spike_recovery is not supported for backend={self.backend!r} "- "because spike recovery is driven by the watchdog and the watchdog "- "cannot fire on MLX"+ "because MLX does not implement checkpoint rollback or recovery hints")- if getattr(tcfg, "loss_watchdog", False):+ if getattr(tcfg, "loss_watchdog", False) and (+ self.task != "sft" or self.modality != "text"+ ):raise ValueError(f"training.loss_watchdog is not supported for backend={self.backend!r} "- "because Soup does not implement the watchdog on the MLX callback, "- "which has no stop control"+ "because the native watchdog supports only MLX text SFT")if getattr(tcfg, "grad_accum_auto_tune", False):raise ValueError(diff --git a/src/soup_cli/trainer/mlx_sft.py b/src/soup_cli/trainer/mlx_sft.pyindex a9198a31..837fbccc 100644--- a/src/soup_cli/trainer/mlx_sft.py+++ b/src/soup_cli/trainer/mlx_sft.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport jsonimport mathimport time+from dataclasses import dataclassfrom pathlib import Pathfrom rich.console import Console@@ -32,6 +33,27 @@ console = Console()_CHAT_KEY = "messages"+class _LossWatchdogStop(Exception): # noqa: N818 — a control signal, not a training error+ """Internal control signal, raised only after a completed optimizer update."""+++@dataclass+class _LossWatchdog:+ """Count consecutive measured reports strictly above an absolute threshold."""++ threshold: float+ patience: int+ counter: int = 0++ def observe(self, loss: float | None) -> bool:+ if loss is None:+ return False+ if not math.isfinite(loss):+ raise FloatingPointError("MLX loss watchdog: non-finite training loss")+ self.counter = self.counter + 1 if loss > self.threshold else 0+ return self.counter >= self.patience++def _count_safetensors_tensors(path: str) -> int:"""Number of tensors declared in a ``.safetensors`` file's own header.@@ -447,15 +469,10 @@ class MLXSFTTrainerWrapper:f"gradient_checkpointing tier {tcfg.gradient_checkpointing!r} ""(MLX has a single on/off switch; enabling it)")- if getattr(tcfg, "loss_watchdog", False):- unsupported.append(- "training.loss_watchdog (Soup does not implement the watchdog "- "on the MLX callback, which has no stop control)"- )if getattr(tcfg, "loss_spike_recovery", False):unsupported.append("training.loss_spike_recovery "- "(spike recovery is driven by the watchdog and the watchdog cannot fire on MLX)"+ "(MLX does not implement checkpoint rollback or recovery hints)")if getattr(tcfg, "grad_accum_auto_tune", False):unsupported.append(@@ -716,6 +733,16 @@ class MLXSFTTrainerWrapper:# tier string ("selective"/"medium"/"full"/"auto") resolves to True here too.grad_checkpoint = bool(cfg.training.gradient_checkpointing)grad_accumulation_steps = int(cfg.training.gradient_accumulation_steps)+ watchdog = (+ _LossWatchdog(cfg.training.loss_watchdog_threshold,+ cfg.training.loss_watchdog_patience)+ if cfg.training.loss_watchdog else None+ )+ if watchdog is not None:+ # mlx-lm reports after executing a micro-batch. An enabled watchdog+ # reports every logging_steps *updates*, so a stop never discards a+ # partial accumulation group. The disabled cadence is unchanged.+ steps_per_report *= grad_accumulation_steps# mlx-lm updates the optimizer only when it % accum == 0 (trainer.py) and# never flushes a partial group, so round iters down to a whole number of# groups, keeping at least one group so a small dataset does not train@@ -963,6 +990,23 @@ class MLXSFTTrainerWrapper:passdef on_train_loss_report(self, train_info: dict) -> None:+ should_stop = (+ watchdog.observe(train_info.get("train_loss"))+ if watchdog is not None else False+ )+ self._report_train_loss(train_info)+ if should_stop:+ iteration = int(train_info["iteration"])+ if iteration <= 0 or iteration % grad_accumulation_steps:+ raise RuntimeError("MLX watchdog report is not at an optimizer boundary")+ # Verify the native optimizer too, rather than trusting a+ # callback index if a future mlx-lm changes loop ordering.+ if int(optimizer.step.item()) != iteration // grad_accumulation_steps:+ raise RuntimeError("MLX watchdog report precedes its optimizer update")+ captured["completed_iterations"] = iteration+ raise _LossWatchdogStop++ def _report_train_loss(self, train_info: dict) -> None:loss = train_info.get("train_loss", 0.0)captured.setdefault("losses", []).append(loss)# Carried for the validation row, which has no training numbers@@ -1121,30 +1165,53 @@ class MLXSFTTrainerWrapper:train_hooks = {**train_hooks, "loss": rewind.loss}t0 = time.time()+ completed_iterations = iters+ stopped = Falsetry:- train(- model=self.model,- optimizer=optimizer,- train_dataset=train_dataset,- val_dataset=val_dataset,- args=args,- training_callback=callback,- **train_hooks,- )- last_update = iters // max(1, grad_accumulation_steps)+ try:+ train(+ model=self.model,+ optimizer=optimizer,+ train_dataset=train_dataset,+ val_dataset=val_dataset,+ args=args,+ training_callback=callback,+ **train_hooks,+ )+ except _LossWatchdogStop:+ import mlx.core as mx+ from mlx.utils import tree_flatten++ stopped = True+ completed_iterations = captured["completed_iterations"]+ # Raising out of mlx-lm bypasses its trailing final save. Save+ # precisely the completed state; a save error remains an error.+ if mx.distributed.init().rank() == 0:+ mx.save_safetensors(+ args.adapter_file, dict(tree_flatten(self.model.trainable_parameters()))+ )+ last_update = completed_iterations // max(1, grad_accumulation_steps)if eval_every is not None and (not eval_log or eval_log[-1]["update"] != last_update):# The last update has no next fetch to trigger it.run_eval(last_update)finally:# The final iteration has no next fetch to flush it, and it is the# one that matters most when a non-finite loss ends the run.- if rewind is not None:- rewind.finish()- # A Live display left attached would corrupt the terminal if- # mlx-lm raises, so this is a finally rather than a trailing call.- if display is not None:- display.stop()+ try:+ if rewind is not None:+ rewind.finish()+ finally:+ # Even a recorder/save failure must release the live display.+ if display is not None:+ display.stop()duration = time.time() - t0+ outcome = ({+ "training_outcome": "stopped" if stopped else "completed",+ "stop_reason": "loss_watchdog" if stopped else "budget_completed",+ "completed_iterations": completed_iterations,+ "completed_updates": last_update,+ "watchdog_report_unit": "optimizer updates",+ } if watchdog is not None else {})# mlx-lm's tuner only saves adapters.safetensors; write the# adapter_config.json so the output dir is directly loadable with@@ -1158,6 +1225,7 @@ class MLXSFTTrainerWrapper:"num_layers": len(getattr(self.model, "layers", [])),"batch_size": batch_size,"iters": iters,+ **outcome,"learning_rate": float(cfg.training.lr),"steps_per_report": steps_per_report,"steps_per_eval": steps_per_eval,@@ -1194,7 +1262,8 @@ class MLXSFTTrainerWrapper:)result = {**loss_summary,- "total_steps": iters,+ "total_steps": completed_iterations,+ **outcome,"duration_secs": duration,"duration": f"{duration:.0f}s","output_dir": str(output_dir),@@ -1202,5 +1271,13 @@ class MLXSFTTrainerWrapper:if eval_log:result["val_loss"] = eval_log[-1]["val_loss"]result["eval_updates"] = [entry["update"] for entry in eval_log]- console.print(f"[green]MLX training complete:[/] {output_dir}")+ if stopped:+ console.print(+ f"[yellow]Loss watchdog stopped MLX training after {last_update} "+ f"optimizer updates ({completed_iterations} iterations); "+ f"loss exceeded {watchdog.threshold} for {watchdog.patience} "+ f"consecutive reports. Last adapter saved:[/] {output_dir}"+ )+ else:+ console.print(f"[green]MLX training complete:[/] {output_dir}")return resultdiff --git a/tests/test_issue1069_mlx_callback_monitoring_compat.py b/tests/test_issue1069_mlx_callback_monitoring_compat.pyindex 1e8c1362..da326b80 100644--- a/tests/test_issue1069_mlx_callback_monitoring_compat.py+++ b/tests/test_issue1069_mlx_callback_monitoring_compat.py@@ -1,5 +1,6 @@-"""Tests for Issue #1069: loss_watchdog, loss_spike_recovery and grad_accum_auto_tune-are refused at config load on backend: mlx; no unreachable doctor row remains.+"""#1069 monitoring refusals, updated for native SFT watchdog support (#1989).++Recovery and auto-tuning remain refused on MLX."""from __future__ import annotations@@ -15,23 +16,16 @@ from tests.conftest import strip_ansiclass TestSchemaRejectionOnMlxBackend:- """Validate that backend: mlx rejects watchdog, spike recovery,- and grad_accum_auto_tune at config validation time with exact reasons.+ """MLX still rejects recovery and auto-tuning with exact reasons."""@pytest.mark.parametrize(("field", "training_payload", "reason"),[- (- "loss_watchdog",- {"loss_watchdog": True},- "Soup does not implement the watchdog on the MLX callback, "- "which has no stop control",- ),("loss_spike_recovery",{"loss_watchdog": True, "loss_spike_recovery": True},- "spike recovery is driven by the watchdog and the watchdog cannot fire on MLX",+ "MLX does not implement checkpoint rollback or recovery hints",),("grad_accum_auto_tune",@@ -96,9 +90,9 @@ class TestBackendSupportRegistryAndDoctor:class TestMlxTrainerCheckUnsupported:- """Verify MLXSFTTrainerWrapper._check_unsupported prints warnings for all three fields."""+ """The internal trainer guard warns only about the remaining refused fields."""- def test_trainer_warns_on_all_three_fields(self, capsys) -> None:+ def test_trainer_warns_only_on_refused_fields(self, capsys) -> None:from soup_cli.trainer.mlx_sft import MLXSFTTrainerWrapperwrapper = object.__new__(MLXSFTTrainerWrapper)@@ -114,33 +108,28 @@ class TestMlxTrainerCheckUnsupported:wrapper._check_unsupported()out = " ".join(strip_ansi(capsys.readouterr().out).split())- expected_watchdog = (- "training.loss_watchdog (Soup does not implement the watchdog "- "on the MLX callback, which has no stop control)"- )expected_spike = ("training.loss_spike_recovery "- "(spike recovery is driven by the watchdog and the watchdog cannot fire on MLX)"+ "(MLX does not implement checkpoint rollback or recovery hints)")expected_tune = ("training.grad_accum_auto_tune ""(there is no VRAM total to measure pressure against on unified memory)")- assert expected_watchdog in out+ assert "training.loss_watchdog" not in outassert expected_spike in outassert expected_tune in outclass TestReasonStringsByteIdenticalAcrossSurfaces:"""Verify the reason strings across schema.py, backend_support.py, and mlx_sft.py- are byte-identical for all three monitoring fields.+ are byte-identical for the refused monitoring fields."""@pytest.mark.parametrize("field",[- "loss_watchdog","loss_spike_recovery","grad_accum_auto_tune",],diff --git a/tests/test_mlx_dora_native.py b/tests/test_mlx_dora_native.pyindex 4e566b2a..f8ac6a71 100644--- a/tests/test_mlx_dora_native.py+++ b/tests/test_mlx_dora_native.py@@ -1,4 +1,7 @@-"""Native DoRA lifecycle on a tiny, local random Llama; no model downloads."""+"""Native adapter lifecycles (DoRA and SFT watchdog); no model downloads.++Kept together because mlx-smoke already selects this file on Apple Silicon.+"""import jsonimport math@@ -247,3 +250,129 @@ def test_plain_lora_still_constructs_lora_layers(tmp_path):assert isinstance(wrapper.model.layers[0].self_attn.q_proj, LoRALinear)assert not any(name.endswith(".m")for name, _ in tree_flatten(wrapper.model.trainable_parameters()))+++def _watchdog_wrapper(base, output, *, accum=1, enabled=True, patience=2, epochs=3, train_count=4):+ mx.random.seed(17)+ cfg = _config(base, output, dora=False)+ cfg.training.epochs = epochs+ cfg.training.gradient_accumulation_steps = accum+ cfg.training.loss_watchdog = enabled+ cfg.training.loss_watchdog_threshold = 0.000001+ cfg.training.loss_watchdog_patience = patience+ cfg.training.logging_steps = 1+ cfg.training.rewind_log = False+ # Validate through the same serialized configuration loader as the CLI.+ from soup_cli.config.loader import load_config_from_string++ wrapper = MLXSFTTrainerWrapper(load_config_from_string(cfg.model_dump_json()))+ wrapper.setup({"train": _rows()["train"][:1] * train_count})+ return wrapper++[email protected]("accum, logging, patience", [(1, 1, 2), (2, 1, 2), (3, 1, 2), (2, 2, 1)])+def test_native_watchdog_stops_at_exact_update_and_reloads(+ tmp_path, monkeypatch, accum, logging, patience+):+ import soup_cli.trainer.mlx_optim as optim++ base = _checkpoint(tmp_path / "base")+ built = []+ build = optim.build_optimizer++ def record(plan):+ optimizer = build(plan)+ built.append(optimizer)+ return optimizer++ monkeypatch.setattr(optim, "build_optimizer", record)+ wrapper = _watchdog_wrapper(base, tmp_path / "stopped", accum=accum, patience=patience)+ wrapper.config.training.logging_steps = logging+ result = wrapper.train()+ assert result["stop_reason"] == "loss_watchdog"+ assert result["training_outcome"] == "stopped"+ assert result["completed_updates"] == 2+ assert result["total_steps"] == 2 * accum+ assert built[0].step.item() == 2+ metadata = json.loads((tmp_path / "stopped" / "adapter_config.json").read_text())+ assert metadata["completed_updates"] == 2+ assert metadata["completed_iterations"] == 2 * accum+ assert metadata["training_outcome"] == "stopped"+ assert metadata["stop_reason"] == "loss_watchdog"+ assert metadata["watchdog_report_unit"] == "optimizer updates"+ restored, _ = load(str(base), adapter_path=str(tmp_path / "stopped"))+ wrapper.model.eval()+ tokens = mx.array([[5, 6, 7]])+ assert mx.allclose(restored(tokens), wrapper.model(tokens), atol=1e-5, rtol=1e-5).item()++ # Identical initial model/data/constant LR: the stopped parameters must equal+ # exactly two updates, and differ from a disabled run's complete budget.+ control = _watchdog_wrapper(base, tmp_path / "control", accum=accum, enabled=False,+ epochs=1, train_count=2 * accum)+ control.train()+ stopped_weights = dict(tree_flatten(wrapper.model.trainable_parameters()))+ control_weights = dict(tree_flatten(control.model.trainable_parameters()))+ assert built[1].step.item() == 2+ assert all(mx.allclose(value, control_weights[name], atol=1e-6, rtol=1e-6).item()+ for name, value in stopped_weights.items())+ full = _watchdog_wrapper(base, tmp_path / "full", accum=accum, enabled=False)+ full_result = full.train()+ full_weights = dict(tree_flatten(full.model.trainable_parameters()))+ assert full_result["total_steps"] > result["total_steps"]+ assert built[2].step.item() > 2+ assert any(not mx.array_equal(value, full_weights[name]).item()+ for name, value in stopped_weights.items())+++def test_public_cli_watchdog_reports_early_stop_and_saves(tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ base = _checkpoint(tmp_path / "base")+ wrapper = _watchdog_wrapper(base, tmp_path / "out", accum=2)+ wrapper.config.training.rewind_log = True+ data = tmp_path / "data.jsonl"+ data.write_text("\n".join(json.dumps(row) for row in _rows()["train"]) + "\n")+ wrapper.config.data.train = str(data)+ wrapper.config.data.format = "plaintext"+ wrapper.config.data.val_split = 0+ config = tmp_path / "soup.json"+ config.write_text(wrapper.config.model_dump_json())+ outcome = CliRunner().invoke(app, ["train", "--config", str(config), "--yes"])+ assert outcome.exit_code == 0, (outcome.output, repr(outcome.exception))+ assert "Loss watchdog" in outcome.output+ assert "Training Stopped" in outcome.output+ assert "Training Complete!" not in outcome.output+ metadata = json.loads((tmp_path / "out" / "adapter_config.json").read_text())+ assert metadata["completed_updates"] == 2+ assert metadata["stop_reason"] == "loss_watchdog"+ from soup_cli.experiment.tracker import ExperimentTracker++ tracker = ExperimentTracker()+ run = tracker.list_runs()[0]+ assert run["status"] == "completed" # successful finalization, documented separately+ assert run["total_steps"] == 4+ assert [row["step"] for row in tracker.get_metrics(run["run_id"])+ if row["loss"] is not None] == [2, 4]+ records = [json.loads(line) for line in (tmp_path / "out" / "rewind.jsonl")+ .read_text().splitlines()]+ assert [(row["step"], row["micro"]) for row in records if row["kind"] == "batch"] == [+ (1, 0), (1, 1), (2, 0), (2, 1),+ ]+ restored, _ = load(str(base), adapter_path=str(tmp_path / "out"))+ assert mx.isfinite(restored(mx.array([[5, 6, 7]]))).all().item()+++def test_native_watchdog_runs_final_eval_at_stopped_update(tmp_path):+ base = _checkpoint(tmp_path / "base")+ wrapper = _watchdog_wrapper(base, tmp_path / "out", accum=2)+ wrapper.config.training.eval_steps = 3+ wrapper._dataset["val"] = _rows()["train"][:1]+ result = wrapper.train()+ assert result["completed_updates"] == 2+ assert result["eval_updates"] == [2]+ assert wrapper._eval_log[0]["optimizer_step"] == 2+ assert math.isfinite(result["val_loss"])diff --git a/tests/test_mlx_loss_watchdog.py b/tests/test_mlx_loss_watchdog.pynew file mode 100644index 00000000..1a8723c5--- /dev/null+++ b/tests/test_mlx_loss_watchdog.py@@ -0,0 +1,252 @@+"""Portable contracts for the native SFT loss watchdog (#1989)."""++import json+import sys+from pathlib import Path+from types import ModuleType, SimpleNamespace++import pytest++from soup_cli.config.loader import load_config_from_string+++def test_public_config_accepts_mlx_sft_watchdog():+ cfg = load_config_from_string("""+base: ./local-model+backend: mlx+task: sft+data:+ train: ./train.jsonl+training:+ quantization: none+ loss_watchdog: true+""")+ assert cfg.training.loss_watchdog is True++[email protected]("values, patience, expected", [+ ([3, 2, 3.1], 1, [False, False, True]),+ ([4, 3, 4, 4], 2, [False, False, False, True]),+ ([4, None, 4], 2, [False, False, True]),+ ([4, 2, 4, 2, 4, 4, 4], 3, [False] * 6 + [True]),+])+def test_report_threshold_patience_and_reset(values, patience, expected):+ from soup_cli.trainer.mlx_sft import _LossWatchdog++ watchdog = _LossWatchdog(3.0, patience)+ assert [watchdog.observe(value) for value in values] == expected++[email protected]("value", [float("nan"), float("inf"), -float("inf")])+def test_nonfinite_loss_is_an_error(value):+ from soup_cli.trainer.mlx_sft import _LossWatchdog++ with pytest.raises(FloatingPointError, match="non-finite.*loss"):+ _LossWatchdog(3.0, 1).observe(value)++[email protected]("field, value", [+ ("loss_watchdog_threshold", 0), ("loss_watchdog_threshold", -1),+ ("loss_watchdog_threshold", float("nan")),+ ("loss_watchdog_threshold", float("inf")),+ ("loss_watchdog_patience", 0), ("loss_watchdog_patience", 1001),+])+def test_invalid_watchdog_bounds(field, value):+ from soup_cli.config.schema import TrainingConfig++ with pytest.raises(ValueError, match=field):+ TrainingConfig(**{field: value})++[email protected]("task", ["dpo", "orpo"])+def test_other_native_tasks_still_refuse_watchdog(task):+ from soup_cli.config.schema import SoupConfig++ with pytest.raises(ValueError, match="loss_watchdog.*MLX text SFT"):+ SoupConfig(base="./model", backend="mlx", task=task,+ data={"train": "./data.jsonl"}, training={"loss_watchdog": True})+++def test_nontext_sft_still_refuses_watchdog():+ from soup_cli.config.schema import SoupConfig++ with pytest.raises(ValueError, match="loss_watchdog.*MLX text SFT"):+ SoupConfig(base="./model", backend="mlx", task="sft", modality="vision",+ data={"train": "./data.jsonl"}, training={"loss_watchdog": True})+++def loop(monkeypatch, tmp_path):+ """Real Soup control flow, simulated vendor loop/optimizer and disk boundary.++ This tests orchestration on every platform; the native CI file separately+ compares real tensors, optimizer states and reloadable safetensors.+ """+ from soup_cli.trainer import mlx_optim+ from tests.test_issue634_mlx_resume import (+ _FakeMlxModel,+ _install_fake_mlx,+ _mlx_wrapper,+ )++ _install_fake_mlx(monkeypatch)+ wrapper = _mlx_wrapper(tmp_path, epochs=1, loss_watchdog=True, loss_watchdog_threshold=3,+ loss_watchdog_patience=2, batch_size=1, logging_steps=1,+ gradient_accumulation_steps=2, rewind_log=False)+ wrapper.config.data.train_on_responses_only = False+ model = _FakeMlxModel()+ model.weight = 10+ model.trainable_parameters = lambda: {"adapter": model.weight}+ wrapper.model, wrapper.tokenizer = model, object()+ wrapper._dataset = {"train": [{"text": "x"}] * 16, "val": []}+ optimizer = SimpleNamespace(completed=0)+ optimizer.step = SimpleNamespace(item=lambda: optimizer.completed)+ monkeypatch.setattr(mlx_optim, "build_optimizer", lambda plan: optimizer)+ utils = ModuleType("mlx.utils")+ utils.tree_flatten = lambda weights: list(weights.items())+ monkeypatch.setitem(sys.modules, "mlx.utils", utils)+ core = sys.modules["mlx.core"]+ core.distributed = SimpleNamespace(init=lambda: SimpleNamespace(rank=lambda: 0))+ core.save_safetensors = lambda path, weights: Path(path).write_text(json.dumps(weights))+ state = SimpleNamespace(wrapper=wrapper, optimizer=optimizer, core=core,+ losses=[4] * 16, failure=None, reports=[], stopped=False)+ state.display = SimpleNamespace(start=lambda total: None,+ update=lambda **kwargs: state.reports.append(kwargs),+ stop=lambda: setattr(state, "stopped", True))++ def train(**kwargs):+ args = kwargs["args"]+ state.args = args+ reports = iter(state.losses)+ for iteration in range(1, args.iters + 1):+ if state.failure is not None:+ raise state.failure+ if iteration % args.grad_accumulation_steps == 0:+ optimizer.completed += 1+ model.weight -= 1+ if iteration % args.steps_per_report == 0 or iteration == args.iters:+ payload = {"iteration": iteration, "train_loss": next(reports)}+ kwargs["training_callback"].on_train_loss_report(payload)++ sys.modules["mlx_lm.tuner.trainer"].train = train+ return state++[email protected]("accum, logging, patience", [(1, 1, 1), (2, 2, 2), (3, 1, 2)])+def test_public_configuration_controls_exact_stop(loop, accum, logging, patience):+ wrapper = loop.wrapper+ wrapper.config.training.gradient_accumulation_steps = accum+ wrapper.config.training.logging_steps = logging+ wrapper.config.training.loss_watchdog_patience = patience+ result = wrapper.train(display=loop.display)+ updates = logging * patience+ assert loop.optimizer.completed == updates+ assert wrapper.model.weight == 10 - updates+ assert result["total_steps"] == updates * accum+ assert result["completed_updates"] == updates+ assert result["stop_reason"] == "loss_watchdog"+ assert loop.reports[-1]["step"] == updates * accum+ assert loop.stopped+ output = Path(wrapper.config.output)+ assert json.loads((output / "adapters.safetensors").read_text()) == {"adapter": 10 - updates}+ assert json.loads((output / "adapter_config.json").read_text())["training_outcome"] == "stopped"+++def test_missing_reports_neither_reset_nor_advance_patience(loop):+ loop.losses = [4, None, 4]+ result = loop.wrapper.train()+ assert result["completed_updates"] == 3+ assert loop.wrapper.model.weight == 7+++def test_enabled_watchdog_can_complete_budget(loop):+ loop.losses = [1] * 16+ result = loop.wrapper.train()+ assert result["stop_reason"] == "budget_completed"+ assert result["training_outcome"] == "completed"+ assert result["completed_updates"] == 8+ assert loop.wrapper.model.weight == 2+++def test_disabled_mode_keeps_original_report_cadence(loop):+ loop.wrapper.config.training.loss_watchdog = False+ result = loop.wrapper.train(display=loop.display)+ assert loop.args.steps_per_report == 1+ assert len(loop.reports) == 16+ assert loop.optimizer.completed == 8+ assert "stop_reason" not in result++[email protected]("failure", [ValueError("vendor failure"), KeyboardInterrupt()])+def test_unrelated_failure_is_not_a_watchdog_stop(loop, failure):+ loop.failure = failure+ with pytest.raises(type(failure)) as caught:+ loop.wrapper.train(display=loop.display)+ assert caught.value is failure+ assert loop.stopped+ assert loop.optimizer.completed == 0+ assert not (Path(loop.wrapper.config.output) / "adapter_config.json").exists()+++def test_nonfinite_report_fails_and_cleans_up(loop):+ loop.losses = [float("nan")]+ with pytest.raises(FloatingPointError, match="non-finite training loss"):+ loop.wrapper.train(display=loop.display)+ assert loop.optimizer.completed == 1+ assert loop.stopped+ assert not (Path(loop.wrapper.config.output) / "adapter_config.json").exists()+++def test_failed_final_save_propagates_and_releases_recorder_and_display(loop, monkeypatch):+ from soup_cli.trainer import mlx_sft++ finished = []+ recorder = SimpleNamespace(wrap=lambda rows: rows, loss=object(),+ finish=lambda: finished.append(True))+ monkeypatch.setattr(mlx_sft, "_start_rewind", lambda **kwargs: recorder)+ loop.wrapper.config.training.rewind_log = True++ def fail_save(*args):+ raise OSError("disk full")++ monkeypatch.setattr(loop.core, "save_safetensors", fail_save)+ with pytest.raises(OSError, match="disk full"):+ loop.wrapper.train(display=loop.display)+ assert finished == [True]+ assert loop.stopped+ assert loop.optimizer.completed == 2+ assert not (Path(loop.wrapper.config.output) / "adapter_config.json").exists()+++def test_failing_recorder_finish_still_releases_the_display(loop, monkeypatch):+ from soup_cli.trainer import mlx_sft++ def failing_finish():+ raise OSError("recorder finish failed")++ recorder = SimpleNamespace(wrap=lambda rows: rows, loss=object(), finish=failing_finish)+ monkeypatch.setattr(mlx_sft, "_start_rewind", lambda **kwargs: recorder)+ loop.wrapper.config.training.rewind_log = True+ with pytest.raises(OSError, match="recorder finish failed"):+ loop.wrapper.train(display=loop.display)+ assert loop.stopped++[email protected]("iteration, updates, diagnostic", [+ (1, 0, "not at an optimizer boundary"),+ (2, 0, "precedes its optimizer update"),+])+def test_changed_vendor_callback_order_is_an_error(loop, iteration, updates, diagnostic):+ loop.wrapper.config.training.loss_watchdog_patience = 1+ loop.optimizer.completed = updates++ def misordered_train(**kwargs):+ kwargs["training_callback"].on_train_loss_report(+ {"iteration": iteration, "train_loss": 4}+ )++ sys.modules["mlx_lm.tuner.trainer"].train = misordered_train+ with pytest.raises(RuntimeError, match=diagnostic):+ loop.wrapper.train(display=loop.display)+ assert loop.stopped+ assert not (Path(loop.wrapper.config.output) / "adapter_config.json").exists()