Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(mlx): a split smaller than one batch no longer crashes the run (#1851) (#1857)

dryn85-max0d49d542ecbc
diff --git a/changelog.d/0.76.0/1857.fixed.md b/changelog.d/0.76.0/1857.fixed.md
new file mode 100644
index 00000000..d8a26e62
--- /dev/null
+++ b/changelog.d/0.76.0/1857.fixed.md
@@ -0,0 +1,8 @@
+- **`backend: mlx` no longer crashes when a split is smaller than one batch (#1851 by
+ @dryn85-max in #1857).** mlx-lm trains and evaluates in whole batches. A one-row validation
+ split, which the default `val_split: 0.1` gives on the bundled 10-row `alpaca_tiny.jsonl`,
+ crashed at the first evaluation with `Dataset must have at least batch_size=2 examples`, after
+ the model had loaded. Such a split is now skipped with a warning that names both numbers and
+ says `val_loss` will be absent, and the run trains. A training split smaller than one batch is
+ refused before the model loads. Try: `soup train --config soup.yaml` with `backend: mlx`,
+ `data.train: examples/data/alpaca_tiny.jsonl` and `batch_size: 2`.
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index 9b3a02f1..1609e01b 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -100,6 +100,14 @@ dependency; the local file path below does not.
CUDA-shaped analytical VRAM preflight is skipped on the MLX path because Apple
unified memory is managed by Metal, not a fixed CUDA VRAM pool.
+mlx-lm trains and evaluates in whole batches of `training.batch_size`
+([#1851](https://github.com/MakazhanAlpamys/Soup/issues/1851)). A validation
+split with fewer rows than one batch, which the default `data.val_split: 0.1`
+produces on a small file, is not evaluated: the run warns, naming both numbers,
+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 rows
+than one batch is refused before the model loads.
+
```yaml
base: mlx-community/Llama-3.2-3B-Instruct-4bit
task: sft
diff --git a/src/soup_cli/trainer/mlx_sft.py b/src/soup_cli/trainer/mlx_sft.py
index 80980c33..f4286d9f 100644
--- a/src/soup_cli/trainer/mlx_sft.py
+++ b/src/soup_cli/trainer/mlx_sft.py
@@ -260,6 +260,12 @@ def build_mlx_adapter_config(lora_cfg: object, *, adapter_path: str, **extra: ob
return config
+def _resolved_batch_size(tcfg: object) -> int:
+ """``training.batch_size`` as MLX runs it: anything but an int (``auto``) is 1."""
+ value = getattr(tcfg, "batch_size", 1)
+ return int(value) if isinstance(value, int) else 1
+
+
class MLXSFTTrainerWrapper:
"""High-level wrapper for MLX supervised fine-tuning."""
@@ -386,10 +392,29 @@ class MLXSFTTrainerWrapper:
"[yellow]MLX backend ignores: " + ", ".join(unsupported) + "[/]"
)
+ def _check_train_split_size(self, dataset: dict) -> None:
+ """#1851: a training split smaller than one batch cannot train at all.
+
+ mlx-lm's ``iterate_batches`` -- like ``masked_iterate_batches`` -- raises
+ on a dataset smaller than one batch, which surfaced after the model had
+ loaded. Refused here, before the load. (A short *validation* split is
+ skipped with a warning in ``train()`` instead.)
+ """
+ batch_size = _resolved_batch_size(self.config.training)
+ train_rows = len(dataset.get("train") or [])
+ if 0 < train_rows < batch_size:
+ raise ValueError(
+ f"MLX backend: the training split has {train_rows} row(s), fewer "
+ f"than training.batch_size ({batch_size}), and mlx-lm trains in "
+ f"whole batches. Lower training.batch_size to at most {train_rows} "
+ "or add rows."
+ )
+
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)
from soup_cli.utils.mlx import load_mlx_model
@@ -555,13 +580,21 @@ class MLXSFTTrainerWrapper:
if resume_from_checkpoint is not None:
self._load_checkpoint_weights(resume_from_checkpoint)
- batch_size = (
- int(cfg.training.batch_size)
- if isinstance(cfg.training.batch_size, int)
- else 1
- )
+ 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:
+ # #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.
+ console.print(
+ f"[yellow]MLX backend: the validation split has {len(val_rows)} "
+ f"row(s), fewer than training.batch_size ({batch_size}); mlx-lm "
+ "evaluates in whole batches, so it is not evaluated and val_loss "
+ "will be absent. Lower batch_size, raise data.val_split, or set "
+ "data.val_split: 0 to train on those rows.[/]"
+ )
+ val_rows = []
iters = int(
cfg.training.epochs * max(1, math.ceil(len(train_rows) / batch_size))
)
diff --git a/tests/test_mlx_split_smaller_than_batch.py b/tests/test_mlx_split_smaller_than_batch.py
new file mode 100644
index 00000000..c8b42ccf
--- /dev/null
+++ b/tests/test_mlx_split_smaller_than_batch.py
@@ -0,0 +1,139 @@
+"""#1851 — a split smaller than one batch on ``backend: mlx``.
+
+mlx-lm trains and evaluates in batches of ``training.batch_size``, and both its
+``iterate_batches`` and Soup's ``masked_iterate_batches`` raise on a dataset
+smaller than one batch. The bundled ``alpaca_tiny.jsonl`` (10 rows, default
+``val_split: 0.1`` -> 1 held-out row) with ``batch_size: 2`` died at the first
+evaluation, after the model had loaded:
+
+ ValueError: Dataset must have at least batch_size=2 examples but only has 1.
+
+* A **validation** split smaller than one batch is not evaluated: the run warns,
+ naming both numbers and that ``val_loss`` will be absent, and trains as the
+ no-validation branch does. The default ``val_split`` keeps working, and the
+ rows are not withheld in silence (#1223).
+* A **training** split smaller than one batch cannot train at all, so it is
+ refused in ``setup()``, before the model loads.
+
+Driven through the shared fake-MLX harness: ``train()`` runs its real body.
+"""
+
+from __future__ import annotations
+
+import sys
+from io import StringIO
+
+import pytest
+
+from tests.conftest import strip_ansi
+from tests.test_issue634_mlx_resume import _FakeMlxModel, _install_fake_mlx
+
+
+def _cfg(batch_size):
+ from soup_cli.config.schema import DataConfig, SoupConfig, TrainingConfig
+
+ return SoupConfig(
+ base="mlx-community/tiny",
+ task="sft",
+ backend="mlx",
+ data=DataConfig(train="./d.jsonl", format="plaintext"),
+ training=TrainingConfig(epochs=1, batch_size=batch_size),
+ output="./out",
+ )
+
+
+def _rows(n):
+ return [{"text": f"row {i}"} for i in range(n)]
+
+
+def _quiet_console(monkeypatch):
+ from rich.console import Console
+
+ from soup_cli.trainer import mlx_sft
+
+ buffer = StringIO()
+ monkeypatch.setattr(mlx_sft, "console", Console(file=buffer, width=400))
+ return buffer
+
+
+def _train(tmp_path, monkeypatch, *, batch_size, train_rows, val_rows):
+ """Run the real ``train()``; return (kwargs mlx-lm's train got, printed text)."""
+ from soup_cli.trainer.mlx_sft import MLXSFTTrainerWrapper
+
+ _install_fake_mlx(monkeypatch)
+ seen: dict = {}
+ monkeypatch.setattr(
+ sys.modules["mlx_lm.tuner.trainer"], "train", lambda **kw: seen.update(kw)
+ )
+ printed = _quiet_console(monkeypatch)
+ monkeypatch.chdir(tmp_path)
+
+ wrapper = MLXSFTTrainerWrapper(_cfg(batch_size))
+ wrapper.model = _FakeMlxModel()
+ wrapper.tokenizer = object()
+ wrapper._dataset = {"train": _rows(train_rows), "val": _rows(val_rows)}
+ wrapper.train()
+ return seen, printed.getvalue()
+
+
+class TestAShortValidationSplitIsSkippedWithAWarning:
+ def test_the_issue_case_trains_without_evaluating(self, tmp_path, monkeypatch):
+ seen, printed = _train(tmp_path, monkeypatch, batch_size=2, train_rows=9, val_rows=1)
+
+ assert seen["val_dataset"] is None
+ args = seen["args"]
+ # The no-validation cadence: evaluation never comes due.
+ assert args.steps_per_eval > args.iters
+
+ # Rich styles the numbers on a colour terminal; compare the plain text.
+ text = " ".join(strip_ansi(printed).split())
+ assert "validation split has 1 row" in text
+ assert "training.batch_size (2)" in text
+ assert "val_loss" in text
+
+ def test_control_a_full_validation_batch_is_still_evaluated(self, tmp_path, monkeypatch):
+ seen, printed = _train(tmp_path, monkeypatch, batch_size=2, train_rows=9, val_rows=2)
+
+ assert seen["val_dataset"] is not None
+ assert seen["args"].steps_per_eval <= seen["args"].iters
+ assert "validation split has" not in printed
+
+ def test_control_no_validation_split_says_nothing(self, tmp_path, monkeypatch):
+ seen, printed = _train(tmp_path, monkeypatch, batch_size=4, train_rows=9, val_rows=0)
+
+ assert seen["val_dataset"] is None
+ assert "validation split has" not in printed
+
+ def test_batch_size_auto_counts_as_one(self, tmp_path, monkeypatch):
+ """MLX resolves ``batch_size: auto`` to 1, so one row is a full batch."""
+ seen, _ = _train(tmp_path, monkeypatch, batch_size="auto", train_rows=3, val_rows=1)
+
+ assert seen["val_dataset"] is not None
+
+
+class TestAShortTrainingSplitIsRefusedBeforeTheModelLoads:
+ def _setup(self, monkeypatch, *, batch_size, train_rows):
+ from soup_cli.trainer.mlx_sft import MLXSFTTrainerWrapper
+
+ _install_fake_mlx(monkeypatch)
+ loads: list = []
+
+ def _load(path, *args, **kwargs):
+ loads.append(path)
+ return _FakeMlxModel(), object()
+
+ monkeypatch.setattr(sys.modules["mlx_lm"], "load", _load, raising=False)
+ _quiet_console(monkeypatch)
+ wrapper = MLXSFTTrainerWrapper(_cfg(batch_size))
+ return wrapper, loads
+
+ def test_refused_naming_batch_size(self, monkeypatch):
+ wrapper, loads = self._setup(monkeypatch, batch_size=8, train_rows=5)
+ with pytest.raises(ValueError, match=r"training split has 5 row.*batch_size \(8\)"):
+ wrapper.setup({"train": _rows(5), "val": []})
+ assert loads == [], "the model loaded before the split was checked"
+
+ def test_control_a_full_batch_loads(self, monkeypatch):
+ wrapper, loads = self._setup(monkeypatch, batch_size=4, train_rows=4)
+ wrapper.setup({"train": _rows(4), "val": _rows(1)})
+ assert loads == ["mlx-community/tiny"]