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): honour training.eval_steps on MLX SFT, in optimizer updates (#1990) (#2074)
dryn85-max38228c4cfa45
diff --git a/changelog.d/0.76.0/2074.added.md b/changelog.d/0.76.0/2074.added.mdnew file mode 100644index 00000000..966724ad--- /dev/null+++ b/changelog.d/0.76.0/2074.added.md@@ -0,0 +1,9 @@+- **`training.eval_steps` works on `backend: mlx` for SFT, counted in optimizer updates (#1990 by+ @dryn85-max in #2074).** The field was refused on MLX. MLX SFT now evaluates after every+ N completed optimizer updates (after gradient accumulation, as on transformers) and once after+ the last one. Every validation row counts, including a tail smaller than one batch, weighted by+ supervised tokens. The evaluations do not move the training order or take a step. A validation+ split smaller than one batch is evaluated rather than skipped when the field is set, and an+ empty split is refused before the model loads. Unset, MLX keeps mlx-lm's own cadence. The run+ result reports `val_loss`, and `adapter_config.json` records the interval. Try:+ `soup train --config soup.yaml` with `backend: mlx` and `training.eval_steps: 10`.diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 57d2861c..94ad2e6a 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -108,6 +108,17 @@ and records no `val_loss`. Lower `batch_size`, raise `val_split`, or set`val_split: 0` to train on those rows instead. A training split with fewer rowsthan one batch is refused before the model loads.+`training.eval_steps: N` on MLX SFT evaluates after every N completed optimizer+updates and after the last one, over every validation row including a short+tail, and is recorded in `adapter_config.json` as `eval_steps` / `eval_unit`+([#1990](https://github.com/MakazhanAlpamys/Soup/issues/1990)); with it set, a+split smaller than one batch is evaluated rather than skipped. The validation+loss uses the training loss: for plain-text rows that is mlx-lm's+`default_loss`, which also scores the first padding token after each row.+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 reads+batches ahead, the run says once that the evaluation ran before its update.+```yamlbase: mlx-community/Llama-3.2-3B-Instruct-4bittask: sftdiff --git a/docs/training.md b/docs/training.mdindex a22a4621..d2e56d19 100644--- a/docs/training.md+++ b/docs/training.md@@ -121,8 +121,18 @@ read training generations only. `ppo` and `online_dpo` refuse`evaluate()` crashes on prompt-only rows. A generation-based evaluation forthose two is a separate feature.-**Refused at config load.** `training.eval_steps` on `backend: mlx` (mlx-lm-evaluates the split on its own cadence, #739), on `task: unlearn` (it trains on+**On `backend: mlx`** (#1990) `task: sft` honours `training.eval_steps` in the+same unit: completed optimizer updates, after gradient accumulation. Soup runs+those evaluations itself, after updates N, 2N, ... and once after the last+update, over every validation row (a tail smaller than one batch included),+weighted by supervised tokens. mlx-lm's own pass would evaluate before the+update it is scheduled at and read at most 25 whole batches. An evaluation+takes no step and leaves the training order and the model's mode as they were.+Unset, MLX keeps mlx-lm's cadence (a quarter of the run). The MLX preference+tasks (`dpo`, `orpo`) evaluate once per epoch and refuse the field.++**Refused at config load.** `training.eval_steps` on the MLX preference tasks+(see above), on `task: unlearn` (it trains on`forget_set` / `retain_set` and has no validation split), and with`val_split: 0` on local files or remote URIs, where there would be nothing toevaluate.diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 147aa491..5b5694f0 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -8662,8 +8662,8 @@ class SoupConfig(BaseModel):def _validate_eval_steps_compat(self) -> "SoupConfig":"""#1223 — refuse a ``training.eval_steps`` nothing would read.- mlx-lm runs its own validation loop over the split (#739), and three- tasks have no evaluation pass at all. Separately, a split of 0 on a+ On MLX only SFT honours it (#1990, in completed optimizer updates);+ three tasks have no evaluation pass at all. Separately, a split of 0 on asource that cannot carry its own validation split leaves no rows toevaluate. A source that CAN carry one (an HF-hub dataset, apre-tokenized cache) is let through: whether it does is only known at@@ -8673,11 +8673,13 @@ class SoupConfig(BaseModel):if self.training.eval_steps is None:return self- if self.backend == "mlx":+ if self.backend == "mlx" and self.task != "sft":+ # #1990 honours it for MLX SFT. The native preference loops evaluate+ # once per epoch and do not read it yet.raise ValueError(- f"training.eval_steps is not supported for backend={self.backend!r} "- "because mlx-lm evaluates the validation split on its own cadence "- "(#1223)"+ f"training.eval_steps is not supported for task={self.task!r} on "+ "backend='mlx': only task='sft' honours it there (#1990); the MLX "+ "preference loop evaluates once per epoch")reason = EVAL_STEPS_UNSUPPORTED_TASKS.get(self.task)if reason is not None:diff --git a/src/soup_cli/trainer/mlx_sft.py b/src/soup_cli/trainer/mlx_sft.pyindex f4286d9f..a9198a31 100644--- a/src/soup_cli/trainer/mlx_sft.py+++ b/src/soup_cli/trainer/mlx_sft.py@@ -266,6 +266,81 @@ def _resolved_batch_size(tcfg: object) -> int:return int(value) if isinstance(value, int) else 1+def scheduled_eval_updates(total_updates: int, every: int) -> list[int]:+ """#1990: the completed optimizer updates an explicit ``eval_steps`` evaluates at.++ Every multiple of ``every`` up to the budget, plus the final update when it+ is not one of them; ``every`` past the budget is just the final update.+ """+ total = max(1, int(total_updates))+ every = max(1, int(every))+ updates = list(range(every, total + 1, every))+ if not updates or updates[-1] != total:+ updates.append(total)+ return updates+++def evaluate_all_rows(model, dataset, *, batch_size: int, max_seq_length: int,+ loss_fn, iterate_fn) -> float:+ """#1990: validation loss over **every** row, token-weighted.++ mlx-lm's own evaluation reads at most ``val_batches`` (25 by default) whole+ batches and drops a tail smaller than one batch. Here the rows are cut into+ consecutive chunks of ``batch_size`` (the last may be shorter) and each chunk+ is one batch, so every supervised token counts once; the result is+ ``sum(loss * tokens) / sum(tokens)``, the reduction mlx-lm uses per batch.++ The batching helpers draw from numpy's global RNG even for a single batch;+ its state is saved and restored, so an evaluation never moves the training+ order (#1850). The model's training mode is restored too, and no gradient+ or optimizer state is touched.+ """+ import mlx.core as mx+ import numpy as np+ from mlx_lm.tuner.datasets import CacheDataset++ class _Rows(CacheDataset):+ def __init__(self, base, indices): # noqa: D401 — a view, not a cache+ self._base, self._indices = base, list(indices)++ def __len__(self):+ return len(self._indices)++ def __getitem__(self, i):+ return self._base[self._indices[i]]++ def itemlen(self, i):+ return self._base.itemlen(self._indices[i])++ was_training = bool(getattr(model, "training", True))+ rng_state = np.random.get_state()+ total_loss = mx.array(0.0)+ total_tokens = mx.array(0)+ model.eval()+ try:+ n = len(dataset)+ for start in range(0, n, batch_size):+ chunk = _Rows(dataset, range(start, min(n, start + batch_size)))+ for batch in iterate_fn(+ dataset=chunk, batch_size=len(chunk), max_seq_length=max_seq_length+ ):+ losses, tokens = loss_fn(model, *batch)+ total_loss = total_loss + losses * tokens+ total_tokens = total_tokens + tokens+ mx.eval(total_loss, total_tokens)+ finally:+ np.random.set_state(rng_state)+ if was_training:+ model.train()+ tokens = int(total_tokens.item())+ if tokens == 0:+ raise ValueError(+ "MLX backend: the validation split has no supervised token to evaluate "+ "(every row is masked or empty); training.eval_steps needs one"+ )+ return float((total_loss / total_tokens).item())++class MLXSFTTrainerWrapper:"""High-level wrapper for MLX supervised fine-tuning."""@@ -410,11 +485,30 @@ class MLXSFTTrainerWrapper:"or add rows.")+ def _check_eval_steps_has_rows(self, dataset: dict) -> None:+ """#1990: an explicit ``training.eval_steps`` needs validation rows.++ The schema refuses ``val_split: 0`` on a source that cannot carry its+ own split; a source that can (an HF-hub dataset, a cache) is known only+ after loading, so the rows that arrived are checked here, before the+ model loads.+ """+ if self.config.training.eval_steps is None:+ return+ if not (dataset.get("val") or []):+ raise ValueError(+ f"MLX backend: training.eval_steps is "+ f"{self.config.training.eval_steps}, but the validation split is "+ "empty after loading. Set data.val_split above 0, supply a "+ "validation split, or remove training.eval_steps."+ )+def setup(self, dataset: dict) -> None:"""Load MLX model, configure LoRA, prepare dataset."""self._require_mlx()self._check_unsupported()self._check_train_split_size(dataset)+ self._check_eval_steps_has_rows(dataset)from soup_cli.utils.mlx import load_mlx_model@@ -583,7 +677,8 @@ class MLXSFTTrainerWrapper:batch_size = _resolved_batch_size(cfg.training)train_rows = list(self._dataset.get("train", []))val_rows = list(self._dataset.get("val", []))- if 0 < len(val_rows) < batch_size:+ eval_every = cfg.training.eval_steps+ if 0 < len(val_rows) < batch_size and eval_every is None:# #1851: mlx-lm evaluates in whole batches of `batch_size` and raises# on a smaller split. Evaluating nothing is the no-val branch below;# the warning keeps it from being #1223's silent hold-out.@@ -607,6 +702,13 @@ class MLXSFTTrainerWrapper:# Real eval cadence when a val split exists; otherwise the value is# irrelevant (val_dataset stays None and mlx-lm skips evaluation).steps_per_eval = max(1, iters // 4) if val_rows else max(1000, iters + 1)+ # #1990: an explicit eval_steps is honoured by Soup (scheduled_eval_updates+ # below), not by mlx-lm, whose evaluation runs *before* the step at+ # iteration `it`: under accumulation it would miss the update that+ # completes at `it`, its "final" pass precedes the last update, and it+ # reads at most 25 whole batches. Its own cadence is pushed past the run.+ if eval_every is not None:+ steps_per_eval = max(1000, iters + 1)# mlx-lm's TrainingArgs.grad_checkpoint is a single bool with no concept# of a granularity tier; bool() is the same coercion commands/train.py's# hardware-fit predictor and layer_stream.should_enable_hf_gradient_checkpointing@@ -932,6 +1034,75 @@ class MLXSFTTrainerWrapper:except Exception: # noqa: BLE001 — telemetry must not kill a runpass+ callback = _Callback()+ eval_log: list = []+ self._eval_log = eval_log+ if eval_every is not None:+ from mlx_lm.tuner.trainer import default_loss+ from mlx_lm.tuner.trainer import iterate_batches as default_iterate++ eval_dataset, val_dataset = val_dataset, None+ eval_loss = train_hooks.get("loss", default_loss)+ eval_iterate = train_hooks.get("iterate_batches", default_iterate)+ accum = max(1, grad_accumulation_steps)+ schedule = scheduled_eval_updates(iters // accum, int(eval_every))+ console.print(+ f"[dim]MLX: evaluating the validation split ({len(val_rows)} rows) "+ f"after optimizer updates {schedule[:6]}{' ...' if len(schedule) > 6 else ''}"+ f" (every {eval_every} update(s) = {int(eval_every) * accum} "+ f"iteration(s), and after the last of {iters // accum})[/]"+ )++ drift_reported: list = []++ def run_eval(update: int) -> None:+ tic = time.time()+ value = evaluate_all_rows(+ self.model, eval_dataset, batch_size=batch_size,+ max_seq_length=max_seq_length, loss_fn=eval_loss,+ iterate_fn=eval_iterate,+ )+ step_state = getattr(optimizer, "state", {}).get("step")+ optimizer_step = int(step_state.item()) if step_state is not None else None+ if optimizer_step not in (None, update) and not drift_reported:+ # The trigger assumes mlx-lm fetches the batch for+ # iteration `it` only after `it - 1` ran; a release that+ # prefetches would move the schedule, so say so, once.+ drift_reported.append(update)+ console.print(+ f"[yellow]MLX: the evaluation for update {update} ran after "+ f"{optimizer_step} optimizer step(s); this mlx-lm fetches "+ "batches ahead of the step, so training.eval_steps is "+ "approximate here.[/]"+ )+ eval_log.append({+ "update": update,+ "optimizer_step": optimizer_step,+ "val_loss": value,+ })+ callback.on_val_loss_report({+ "iteration": update * accum, "val_loss": value,+ "val_time": time.time() - tic,+ })++ def scheduled_iterate(**kwargs):+ """The training stream, evaluating when update N has just+ completed: mlx-lm fetches the batch for iteration `it` after+ iterations 1..it-1 ran, so `consumed` here is completed work."""+ stream = eval_iterate(**kwargs)+ if not kwargs.get("loop"):+ yield from stream+ return+ due = set(schedule)+ consumed = 0+ for batch in stream:+ if consumed and consumed % accum == 0 and consumed // accum in due:+ run_eval(consumed // accum)+ yield batch+ consumed += 1++ train_hooks = {**train_hooks, "iterate_batches": scheduled_iterate}+if display is not None:display.start(iters)@@ -957,9 +1128,13 @@ class MLXSFTTrainerWrapper:train_dataset=train_dataset,val_dataset=val_dataset,args=args,- training_callback=_Callback(),+ training_callback=callback,**train_hooks,)+ last_update = iters // 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.@@ -986,6 +1161,9 @@ class MLXSFTTrainerWrapper:"learning_rate": float(cfg.training.lr),"steps_per_report": steps_per_report,"steps_per_eval": steps_per_eval,+ # #1990: an explicit interval, in completed optimizer updates.+ **({"eval_steps": int(eval_every), "eval_unit": "optimizer updates"}+ if eval_every is not None else {}),"steps_per_save": steps_per_save,"max_seq_length": max_seq_length,# #683: the EFFECTIVE masking, not a hardcoded False.@@ -1021,5 +1199,8 @@ class MLXSFTTrainerWrapper:"duration": f"{duration:.0f}s","output_dir": str(output_dir),}+ 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}")return resultdiff --git a/tests/test_issue1223_eval_steps_config.py b/tests/test_issue1223_eval_steps_config.pyindex d3d83143..1f1d48bb 100644--- a/tests/test_issue1223_eval_steps_config.py+++ b/tests/test_issue1223_eval_steps_config.py@@ -192,12 +192,18 @@ class TestEvalStepsFootguns:cfg = _load(_yaml(task="grpo", training_extra=" eval_steps: 5\n"))assert cfg.training.eval_steps == 5- def test_mlx_refuses_it_because_mlx_lm_evaluates_on_its_own_cadence(self):+ def test_mlx_sft_honours_it_since_1990(self):+ """Refused here until #1990, which counts it in optimizer updates on+ MLX SFT (tests/test_mlx_eval_steps.py pins the schedule)."""+ cfg = _load(_yaml(backend="mlx", training_extra=" eval_steps: 5\n"))+ assert (cfg.backend, cfg.training.eval_steps) == ("mlx", 5)++ def test_mlx_preference_tasks_still_refuse_it(self):with pytest.raises(ValueError) as info:- _load(_yaml(backend="mlx", training_extra=" eval_steps: 5\n"))+ _load(_yaml(task="dpo", backend="mlx", training_extra=" eval_steps: 5\n"))message = str(info.value)- assert "training.eval_steps is not supported for backend='mlx'" in message- assert "#1223" in message+ assert "training.eval_steps is not supported for task='dpo' on backend='mlx'" in message+ assert "#1990" in messagedef test_mlx_without_it_still_loads(self):"""The control for the refusal above: MLX itself is untouched."""diff --git a/tests/test_mlx_eval_steps.py b/tests/test_mlx_eval_steps.pynew file mode 100644index 00000000..5ed9e3e2--- /dev/null+++ b/tests/test_mlx_eval_steps.py@@ -0,0 +1,470 @@+"""#1990 — ``training.eval_steps`` on MLX SFT, in completed optimizer updates.++mlx-lm evaluates *before* the step at iteration ``it``, so under accumulation a+cadence of ``steps_per_eval`` misses the update that completes at ``it``, its+"final" pass precedes the last update, and it reads at most 25 whole batches,+dropping a tail. An explicit ``eval_steps`` is therefore run by Soup:++- after each completed update ``N, 2N, ...`` and after the last update, once;+- over every validation row, the tail included, token-weighted;+- without moving parameters, optimizer state, training mode or the seeded+ training order.++The unset field keeps today's mlx-lm cadence. Real MLX on a tiny random Llama;+no downloads. The schedule, the refusals and the trigger in ``train()`` (through+the shared fake-MLX harness) also run where MLX is not installed.+"""++from __future__ import annotations++import sys+from io import StringIO++import numpy as np+import pytest+from rich.console import Console++from tests.conftest import strip_ansi+++def native():+ """Real MLX and mlx-lm; only the classes that use this fixture skip without them."""+ pytest.importorskip("mlx.core")+ pytest.importorskip("mlx_lm")+++class _IntTokenizer:+ """Text: one id per character. Chat: role and word markers, all ids < 200."""++ eos_token_id = 2++ def encode(self, text, add_special_tokens=True):+ return ([1] if add_special_tokens else []) + [3 + ord(c) % 150 for c in text]++ def apply_chat_template(self, messages, tools=None, add_generation_prompt=False,+ return_dict=False, **_):+ out = []+ for m in messages:+ out += [160 if m["role"] == "user" else 161]+ out += [3 + ord(c) % 150 for c in m["content"]] + [162]+ if add_generation_prompt:+ out.append(161)+ return out+++def _tiny(hidden=32, quantize=False):+ import mlx.core as mx+ import mlx.nn as nn+ from mlx_lm.models import llama++ mx.random.seed(0)+ model = llama.Model(llama.ModelArgs(+ model_type="llama", hidden_size=hidden, num_hidden_layers=2,+ intermediate_size=2 * hidden, num_attention_heads=4, num_key_value_heads=2,+ rms_norm_eps=1e-5, vocab_size=200, tie_word_embeddings=True,+ ))+ if quantize:+ nn.quantize(model, group_size=32, bits=4)+ return model+++def _text_rows(n, prefix="row"):+ return [{"text": f"{prefix} {i} " + "ab" * (i % 4 + 1)} for i in range(n)]+++def _wrapper(tmp_path, *, train=8, val=4, chat=False, model=None, **training):+ from soup_cli.config.schema import DataConfig, SoupConfig, TrainingConfig+ from soup_cli.trainer.mlx_sft import MLXSFTTrainerWrapper++ training.setdefault("epochs", 1)+ training.setdefault("batch_size", 2)+ training.setdefault("lr", 1e-3)+ training.setdefault("gradient_accumulation_steps", 1)+ cfg = SoupConfig(+ base="mlx-community/tiny", task="sft", backend="mlx",+ data=DataConfig(train="./d.jsonl", format="chatml" if chat else "plaintext",+ max_length=256),+ training=TrainingConfig(logging_steps=1, **training),+ output=str(tmp_path),+ )+ wrapper = MLXSFTTrainerWrapper(cfg)+ wrapper.model = model if model is not None else _tiny()+ wrapper.tokenizer = _IntTokenizer()+ if chat:+ rows = [{"messages": [{"role": "user", "content": f"q{i}"},+ {"role": "assistant", "content": "ans" * (i % 3 + 1)}]}+ for i in range(train + val)]+ wrapper._dataset = {"train": rows[:train], "val": rows[train:]}+ else:+ wrapper._dataset = {"train": _text_rows(train), "val": _text_rows(val, "val")}+ return wrapper+++class TestTheSchedule:+ @pytest.mark.parametrize("total, every, expected", [+ (4, 1, [1, 2, 3, 4]),+ (4, 2, [2, 4]),+ (4, 3, [3, 4]),+ (4, 10, [4]),+ (1, 1, [1]),+ ])+ def test_updates(self, total, every, expected):+ from soup_cli.trainer.mlx_sft import scheduled_eval_updates++ assert scheduled_eval_updates(total, every) == expected++[email protected]("native")+class TestEvaluationsHappenAfterCompletedUpdates:+ @pytest.mark.parametrize("epochs, accum, every, expected", [+ (1, 1, 1, [1, 2, 3, 4]), # every update+ (2, 1, 3, [3, 6, 8]), # N does not divide the 8-update budget+ (2, 2, 2, [2, 4]), # accumulation: 8 iterations, 4 updates+ (2, 2, 3, [3, 4]), # accumulation, non-dividing+ (1, 1, 10, [4]), # N past the budget: once, at the end+ (1, 4, 1, [1]), # a run of one update+ ])+ def test_exact_update_indices(self, tmp_path, epochs, accum, every, expected):+ wrapper = _wrapper(tmp_path, epochs=epochs, gradient_accumulation_steps=accum,+ eval_steps=every)+ result = wrapper.train()+ log = wrapper._eval_log+ assert [e["update"] for e in log] == expected+ # The optimizer had taken exactly that many steps when each ran:+ # completed updates, not micro-batches and not callback calls.+ assert [e["optimizer_step"] for e in log] == expected+ assert result["eval_updates"] == expected+ assert result["val_loss"] == pytest.approx(log[-1]["val_loss"])++[email protected]("native")+class TestTheUnsetFieldKeepsMlxLmsCadence:+ def _seen(self, tmp_path, monkeypatch, **training):+ seen = {}+ monkeypatch.setattr(sys.modules["mlx_lm.tuner.trainer"], "train",+ lambda **kw: seen.update(kw))+ _wrapper(tmp_path, **training).train()+ return seen++ def test_unset_passes_the_split_to_mlx_lm_at_a_quarter_of_the_run(self, tmp_path, monkeypatch):+ import mlx_lm.tuner.trainer # noqa: F401 — registered before it is patched++ seen = self._seen(tmp_path, monkeypatch, epochs=2)+ assert seen["val_dataset"] is not None+ assert seen["args"].steps_per_eval == max(1, seen["args"].iters // 4)++ def test_explicit_takes_the_split_away_from_mlx_lm(self, tmp_path, monkeypatch):+ import mlx_lm.tuner.trainer # noqa: F401++ seen = self._seen(tmp_path, monkeypatch, epochs=2, eval_steps=2)+ assert seen["val_dataset"] is None+ assert seen["args"].steps_per_eval > seen["args"].iters+++class TestRefusals:+ @pytest.mark.parametrize("value, message", [+ (0, "greater than or equal to 1"),+ (-1, "greater than or equal to 1"),+ (True, "must be an int, not a bool"),+ ])+ def test_invalid_values(self, value, message):+ from pydantic import ValidationError++ from soup_cli.config.schema import TrainingConfig++ with pytest.raises(ValidationError, match=message):+ TrainingConfig(eval_steps=value)++ def test_no_validation_rows_is_refused_before_the_model_loads(self, monkeypatch):+ from soup_cli.config.schema import DataConfig, SoupConfig, TrainingConfig+ from soup_cli.trainer import mlx_sft++ def _must_not_load(*_a, **_k):+ raise AssertionError("loaded")++ monkeypatch.setattr("soup_cli.utils.mlx.load_mlx_model", _must_not_load)+ cfg = SoupConfig(+ base="m", task="sft", backend="mlx",+ data=DataConfig(train="./d.jsonl", format="plaintext"),+ training=TrainingConfig(eval_steps=2, batch_size=1), output="./o",+ )+ wrapper = mlx_sft.MLXSFTTrainerWrapper(cfg)+ monkeypatch.setattr(wrapper, "_require_mlx", lambda: None)+ with pytest.raises(ValueError, match="validation split is\\s+empty"):+ wrapper.setup({"train": _text_rows(4), "val": []})+++def _one_ahead(stream):+ pending = next(stream)+ for following in stream:+ yield pending+ pending = following+++class TestTheTriggerWithoutMlx:+ """``train()``'s real body through the shared fake-MLX harness, with a+ stand-in for mlx-lm's loop of the same shape: ``zip(range(1, iters + 1),+ iterate_batches(..., loop=True))``, the optimizer stepping only when+ ``it % accum == 0``. The evaluator is a recorder of the optimizer steps+ taken when it ran, so the schedule is checked on every CI cell."""++ def _run(self, tmp_path, monkeypatch, prefetch=False, **training):+ from soup_cli.trainer import mlx_sft+ from tests.test_issue634_mlx_resume import _FakeMlxModel, _install_fake_mlx++ _install_fake_mlx(monkeypatch)+ loop = {"steps": 0}++ class _Step:+ def item(self):+ return loop["steps"]++ class _AdamW:+ def __init__(self, **_):+ self.state = {"step": _Step()}++ monkeypatch.setattr(sys.modules["mlx.optimizers"], "AdamW", _AdamW)++ def iterate_batches(*, dataset, batch_size, loop=False, **_):+ while True:+ for start in range(0, len(dataset) - batch_size + 1, batch_size):+ yield dataset[start:start + batch_size]+ if not loop:+ return++ def train(*, optimizer, train_dataset, val_dataset, args, iterate_batches=iterate_batches,+ **_):+ loop.update(val_dataset=val_dataset, args=args)+ stream = iterate_batches(dataset=train_dataset, batch_size=args.batch_size,+ max_seq_length=args.max_seq_length, loop=True)+ if prefetch: # a loop that reads one batch ahead of its step+ stream = _one_ahead(stream)+ for it, _batch in zip(range(1, args.iters + 1), stream):+ if it % args.grad_accumulation_steps == 0:+ loop["steps"] += 1++ trainer = sys.modules["mlx_lm.tuner.trainer"]+ monkeypatch.setattr(trainer, "train", train)+ monkeypatch.setattr(trainer, "iterate_batches", iterate_batches, raising=False)+ monkeypatch.setattr(trainer, "default_loss", object(), raising=False)+ seen = []++ def recorder(_model, dataset, **_):+ seen.append((loop["steps"], len(dataset)))+ return 1.0++ monkeypatch.setattr(mlx_sft, "evaluate_all_rows", recorder)+ loop["printed"] = StringIO()+ monkeypatch.setattr(mlx_sft, "console", Console(file=loop["printed"], width=400))+ monkeypatch.chdir(tmp_path)+ loop["wrapper"] = wrapper = _wrapper(tmp_path, model=_FakeMlxModel(), **training)+ result = wrapper.train()+ return result, seen, loop++ @pytest.mark.parametrize("epochs, accum, every, expected", [+ (1, 1, 1, [1, 2, 3, 4]),+ (2, 1, 3, [3, 6, 8]),+ (2, 2, 2, [2, 4]),+ (2, 2, 3, [3, 4]),+ (1, 1, 10, [4]),+ (1, 4, 1, [1]),+ ])+ def test_evaluations_follow_completed_updates(self, tmp_path, monkeypatch,+ epochs, accum, every, expected):+ result, seen, loop = self._run(tmp_path, monkeypatch, epochs=epochs,+ gradient_accumulation_steps=accum, eval_steps=every)+ # The optimizer had taken exactly `update` steps when each evaluation+ # ran, over the whole split; the last one follows train()'s return.+ assert seen == [(update, 4) for update in expected]+ assert result["eval_updates"] == expected+ assert [e["optimizer_step"] for e in loop["wrapper"]._eval_log] == expected+ # In step, the drift warning stays silent.+ assert "fetches batches ahead" not in loop["printed"].getvalue()++ def test_a_loop_that_prefetches_is_reported_once(self, tmp_path, monkeypatch):+ """The trigger relies on mlx-lm fetching batch `it` after step+ `it - 1`; a release that reads ahead must not move it in silence."""+ _, seen, loop = self._run(tmp_path, monkeypatch, prefetch=True, eval_steps=1)+ assert [step for step, _ in seen][:3] == [0, 1, 2]+ text = " ".join(strip_ansi(loop["printed"].getvalue()).split())+ assert text.count("fetches batches ahead of the step") == 1+ assert "evaluation for update 1 ran after 0 optimizer step(s)" in text++ def test_the_split_is_taken_away_from_mlx_lm(self, tmp_path, monkeypatch):+ _, _, loop = self._run(tmp_path, monkeypatch, epochs=2, eval_steps=2)+ assert loop["val_dataset"] is None+ assert loop["args"].steps_per_eval > loop["args"].iters++ def test_unset_keeps_mlx_lms_cadence_and_runs_no_evaluation_of_its_own(+ self, tmp_path, monkeypatch,+ ):+ result, seen, loop = self._run(tmp_path, monkeypatch, epochs=2)+ assert seen == []+ assert loop["val_dataset"] is not None+ assert loop["args"].steps_per_eval == max(1, loop["args"].iters // 4)+ assert "eval_updates" not in result+++# --------------------------------------------------------------------------+# The evaluator: every row, token-weighted, no side effects+# --------------------------------------------------------------------------+++def _np_ce(model, ids, mask=None):+ """(sum of target NLL, number of targets) for one row, independently.++ Text rows follow mlx-lm 0.32's ``default_loss``, the loss MLX SFT trains+ on: its mask is ``steps <= length``, so it also scores the first padding+ token (id 0) after the row. The evaluator reuses the training loss, so its+ number is comparable with the training loss; the oracle states that rule+ rather than inheriting it. Masked chat rows score exactly their mask.+ """+ import mlx.core as mx++ ids = list(ids) + ([0] if mask is None else [])+ logits = np.array(model(mx.array([ids[:-1]]))[0].astype(mx.float32), dtype=np.float64)+ logits -= logits.max(-1, keepdims=True)+ logp = logits - np.log(np.exp(logits).sum(-1, keepdims=True))+ targets = np.array(ids[1:])+ nll = -logp[np.arange(len(targets)), targets]+ keep = np.ones(len(targets), bool) if mask is None else np.array(mask[1:], bool)+ return float(nll[keep].sum()), int(keep.sum())+++def _datasets(wrapper, chat):+ from mlx_lm.tuner.datasets import CacheDataset, create_dataset+ from mlx_lm.tuner.trainer import TrainingArgs, default_loss, iterate_batches++ rows = wrapper._dataset["val"]+ if chat:+ from soup_cli.trainer.mlx_masking import (+ MaskedChatDataset,+ masked_iterate_batches,+ masked_loss,+ )++ ds = CacheDataset(MaskedChatDataset(rows, wrapper.tokenizer, chat_key="messages"))+ return ds, masked_loss, masked_iterate_batches+ return (CacheDataset(create_dataset(rows, wrapper.tokenizer, TrainingArgs())),+ default_loss, iterate_batches)++[email protected]("native")+class TestEveryRowCounts:+ @pytest.mark.parametrize("chat", [False, True])+ def test_loss_equals_a_hand_oracle_over_every_target_tail_included(self, tmp_path, chat):+ from soup_cli.trainer.mlx_sft import evaluate_all_rows++ wrapper = _wrapper(tmp_path, val=5, chat=chat)+ ds, loss, iterate = _datasets(wrapper, chat)+ value = evaluate_all_rows(wrapper.model, ds, batch_size=2, max_seq_length=256,+ loss_fn=loss, iterate_fn=iterate)+ total, count = 0.0, 0+ for i in range(len(ds)):+ item = ds[i]+ ids, mask = (item if chat else (item[0] if isinstance(item, tuple) else item, None))+ row_sum, row_n = _np_ce(wrapper.model, list(ids), mask)+ total, count = total + row_sum, count + row_n+ assert value == pytest.approx(total / count, rel=1e-4)++ # The fifth row is a tail smaller than one batch: leaving it out changes+ # the number, so dropping it is detectable.+ head, head_n = 0.0, 0+ for i in range(4):+ item = ds[i]+ ids, mask = (item if chat else (item[0] if isinstance(item, tuple) else item, None))+ s, n = _np_ce(wrapper.model, list(ids), mask)+ head, head_n = head + s, head_n + n+ assert abs(value - head / head_n) > 1e-4++ def test_evaluation_has_no_side_effects(self, tmp_path):+ import mlx.core as mx+ from mlx.utils import tree_flatten++ from soup_cli.trainer.mlx_sft import evaluate_all_rows++ wrapper = _wrapper(tmp_path, val=5)+ ds, loss, iterate = _datasets(wrapper, False)+ wrapper.model.train()+ before = {k: np.array(v) for k, v in tree_flatten(wrapper.model.parameters())}+ np.random.seed(123)+ rng_before = np.random.get_state()[1].copy()+ mx.random.seed(9)+ evaluate_all_rows(wrapper.model, ds, batch_size=2, max_seq_length=256,+ loss_fn=loss, iterate_fn=iterate)+ after_draw = mx.random.uniform(shape=(4,)).tolist()+ mx.random.seed(9)+ assert after_draw == mx.random.uniform(shape=(4,)).tolist()+ assert (np.random.get_state()[1] == rng_before).all()+ assert wrapper.model.training+ after = {k: np.array(v) for k, v in tree_flatten(wrapper.model.parameters())}+ for name in before:+ np.testing.assert_array_equal(before[name], after[name], err_msg=name)++ def test_a_batching_helper_that_draws_randomness_still_leaves_numpy_untouched(+ self, tmp_path+ ):+ """mlx-lm's batch helpers shuffle through numpy's global RNG; whatever a+ helper draws during an evaluation is given back."""+ from soup_cli.trainer.mlx_sft import evaluate_all_rows++ wrapper = _wrapper(tmp_path, val=5)+ ds, loss, iterate = _datasets(wrapper, False)++ def drawing(**kwargs):+ np.random.random(17)+ yield from iterate(**kwargs)++ np.random.seed(5)+ state = np.random.get_state()[1].copy()+ evaluate_all_rows(wrapper.model, ds, batch_size=2, max_seq_length=256,+ loss_fn=loss, iterate_fn=drawing)+ assert (np.random.get_state()[1] == state).all()++ def test_a_split_smaller_than_one_batch_is_evaluated_not_skipped(self, tmp_path, capsys):+ """#1857 skips such a split when the cadence is mlx-lm's; with an+ explicit eval_steps every row is evaluated, so the row stays."""+ wrapper = _wrapper(tmp_path, val=1, eval_steps=2)+ result = wrapper.train()+ assert result["eval_updates"] == [2, 4]+ # Rich colours the "1" on a colour terminal; compare the plain text.+ assert "validation split has 1 row" not in strip_ansi(capsys.readouterr().out)++ def test_scheduled_evaluations_do_not_change_what_trains(self, tmp_path):+ """Evaluating after every update and only at the end train the same+ adapter: the evaluations take no step, no state and no batch."""+ import mlx.core as mx+ from mlx.utils import tree_flatten++ def adapter(path, every):+ wrapper = _wrapper(path, epochs=2, eval_steps=every)+ # Seeded the way #1855 seeds MLX SFT (numpy's global RNG draws the+ # batch order, mx.random the LoRA init), so the two runs are+ # comparable on main with or without it.+ np.random.seed(7)+ mx.random.seed(7)+ wrapper.train()+ return {k: np.array(v) for k, v in+ tree_flatten(wrapper.model.trainable_parameters())}++ often, once = adapter(tmp_path / "a", 1), adapter(tmp_path / "b", 1000)+ assert often+ for name in often:+ np.testing.assert_array_equal(often[name], once[name], err_msg=name)++[email protected]("native")+class TestNativeVariants:+ @pytest.mark.parametrize("quantize", [False, True], ids=["dense", "4bit"])+ def test_runs_and_records_its_evaluations(self, tmp_path, quantize):+ import json++ model = _tiny(hidden=64, quantize=quantize)+ wrapper = _wrapper(tmp_path, epochs=2, gradient_accumulation_steps=2, eval_steps=1,+ model=model)+ result = wrapper.train()+ assert result["eval_updates"] == [1, 2, 3, 4]+ assert all(np.isfinite(e["val_loss"]) for e in wrapper._eval_log)+ meta = json.loads((tmp_path / "adapter_config.json").read_text())+ assert (meta["eval_steps"], meta["eval_unit"]) == (1, "optimizer updates")