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): native DPO on Apple Silicon (#1846)
dryn85-max34cfd4b4453d
diff --git a/changelog.d/0.76.0/1846.added.md b/changelog.d/0.76.0/1846.added.mdnew file mode 100644index 00000000..5315aaac--- /dev/null+++ b/changelog.d/0.76.0/1846.added.md@@ -0,0 +1,11 @@+- **DPO runs natively on Apple Silicon: `task: dpo` with `backend: mlx` (#1846 by @dryn85-max).**+ It was refused at config load because the MLX wrapper was scaffolding. Soup now runs its own+ MLX loop with TRL's default sigmoid loss and `training.dpo_beta`. Rows are read by the same+ `format: dpo` converter as on the transformers backend and tokenized the way TRL 0.29 does,+ except that ties and rows the chat template cannot slice are skipped with a count, and per-row+ `tools` are not applied. No second model is loaded: reference log-probs are precomputed from+ the base model. `training.seed` and `training.data_seed` are honoured, and the vocabulary head+ runs in checkpointed chunks to keep long pairs in memory. Measured once on an M4 Pro,+ Qwen2.5-0.5B-Instruct trained faster than TRL on MPS with the same bf16 weights and less+ process memory. Try: `soup train --config soup.yaml` with `task: dpo`, `backend: mlx` and+ `base: mlx-community/Qwen2.5-0.5B-Instruct-4bit`.diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 0015faef..9b3a02f1 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -117,7 +117,42 @@ training:alpha: 32```-MLX backend supports SFT. `backend: mlx` with `task: dpo` or `task: grpo` is refused when the config is loaded, with an error naming the task — upstream `mlx-lm` ships no DPO/GRPO training helper, so those wrappers exist only as a backstop for callers that bypass config validation. Requires `mlx-lm >= 0.31.3`. Use `soup recipes search mlx` for ready-made Apple Silicon configs.+MLX backend supports SFT and DPO. Any other task with `backend: mlx` (`grpo`, `ipo`, `kto`, ...) is refused when the config is loaded, with an error naming the task. Requires `mlx-lm >= 0.31.3`. Use `soup recipes search mlx` for ready-made Apple Silicon configs.++#### DPO on MLX++`task: dpo` with `backend: mlx` runs Soup's own training loop (`mlx-lm` ships no DPO helper), with the sigmoid loss TRL uses by default and `training.dpo_beta`.++```yaml+base: mlx-community/Qwen2.5-0.5B-Instruct-4bit+task: dpo+backend: mlx++data:+ train: ./prefs.jsonl+ format: dpo+ max_length: 1024++training:+ lr: 2e-5+ dpo_beta: 0.1+ batch_size: 2+ gradient_accumulation_steps: 4+ gradient_checkpointing: true+ seed: 42+ lora:+ r: 16+ alpha: 32+```++- **No second model in memory.** LoRA `B` starts at zero, so before the first update the policy *is* the base model. Reference log-probs are computed once from it before training, which is what TRL's `precompute_ref_log_probs` does. `--resume` computes them before the checkpoint loads, so the reference is always the base model.+- **The rows `load_dataset` gives every backend.** Each row is read by the loader's own `format: dpo` converter, so MLX accepts exactly the layouts the transformers backend does: text (three strings) or conversational (a message-list prompt, or full `chosen` / `rejected` conversations that repeat the user turn, as the bundled examples do). Text rows get EOS appended; conversational rows go through the model's chat template; the prompt is capped at `max_length // 2` and completions at what remains, as on TRL 0.29. Where this differs from TRL, it does on purpose: a pair whose `chosen` equals its `rejected` is skipped with a count (TRL trains it at a constant loss and zero gradient), and a row the chat template is not prefix-stable for is skipped with a count and the first row's index (TRL warns and slices anyway). Fewer pairs than `training.batch_size` after skipping is refused, naming both.+- **Seeded.** `training.seed` seeds `mx.random` (LoRA init, dropout) and the batch order; `training.data_seed`, when set, owns the batch order instead. Two runs with the same seed reproduce each other's losses.+- **Memory.** Log-probs are computed from the first completion position on, with the vocabulary head run in checkpointed chunks, so the full-vocabulary logits of a batch are never held at once. The chunked path is checked against the full model on the first batch and dropped, with a warning, for an architecture that changes logits after the head. Set `training.gradient_checkpointing: true` for long sequences: measured once on an M4 Pro, Qwen2.5-0.5B-4bit with 792-token pairs, it took a training step from 10.05 GB to 3.63 GB.+- **Learning rate.** DPO is more sensitive than SFT. In one run on UltraFeedback pairs with Qwen2.5-0.5B-4bit, LoRA r=16 on attention, `lr: 5e-5` diverged to NaN within a dozen updates while `lr: 2e-5` trained; start at `2e-5` or below.+- **Progress.** The panel and `soup ui` show loss and validation loss. Reward accuracy and margin print per logged step when there is no live panel, and are returned in the run result; the reference precompute prints its progress before the panel starts.+- **Refused at load:** `modality: vision` / `audio` (MLX DPO trains on text and chat rows) and `training.lora.r: 0` (the reference is the untrained LoRA policy, so an adapter must exist), plus `dpo_beta_schedule` / `dpo_ref_regen_epochs` and LoRA+.+- **Not applied on MLX:** `data.chat_template`, per-row `tools` / `chat_template_kwargs` columns (TRL reads them; MLX DPO renders with the model's own template and nothing else), NEFTune, Liger, FlashAttention and the other CUDA-path options MLX SFT also warns about.#### DoRA on MLX@@ -180,7 +215,7 @@ what ran is recoverable from the output directory.### Transformers on MPS-The regular `backend: transformers` path can run more than MLX's SFT-only+The regular `backend: transformers` path can run more than MLX's SFT and DPOsurface. On a live MPS runtime that accepts bfloat16, Soup enables BF16 autocastfor the hardware-validated text trainers: SFT, DPO, GRPO/RLVR, reward modelling,and PRM.diff --git a/docs/models.md b/docs/models.mdindex e085465e..ed1db56f 100644--- a/docs/models.md+++ b/docs/models.md@@ -142,7 +142,7 @@ spelling is unchanged. See [the README's install section](../README.md#1-install| `fast` | `pip install "soup-cli[fast]"` | Unsloth backend (2-5x faster, lower VRAM) || `vision` | `pip install "soup-cli[vision]"` | Vision / multimodal fine-tuning (Pillow) || `audio` | `pip install "soup-cli[audio]"` | Audio / speech fine-tuning (librosa, soundfile) |-| `mlx` | `pip install "soup-cli[mlx]"` | Standalone Apple Silicon SFT backend for local data; `[train]` is not required |+| `mlx` | `pip install "soup-cli[mlx]"` | Standalone Apple Silicon SFT and DPO backend for local data; `[train]` is not required || `qat` | `pip install "soup-cli[qat]"` | torchao: FP8 training (`quantization_aware: fp8`), FP8 attention, NVFP4, the `ao_adamw_*` optimizers and `soup export --format torchao` || `serve` | `pip install "soup-cli[serve]"` | Inference server (FastAPI + uvicorn) || `serve-fast` | `pip install "soup-cli[serve-fast]"` | vLLM inference backend (2-4x throughput) |diff --git a/src/soup_cli/config/backend_support.py b/src/soup_cli/config/backend_support.pyindex 842cc94a..3f0e345f 100644--- a/src/soup_cli/config/backend_support.py+++ b/src/soup_cli/config/backend_support.py@@ -19,8 +19,8 @@ drift -- every entry must name a real field, and every dotted field name inthe truth; it can only stop it rotting, which is the failure that produced #749.Scope today: ``task=sft`` on ``backend=mlx`` and on ``backend=unsloth`` (#1124;-both apply to every modality), plus multimodal vision and audio on-``backend=transformers`` (#1156). Other combinations report nothing rather+both apply to every modality), ``task=dpo`` on ``backend=mlx``, plus multimodal+vision and audio on ``backend=transformers`` (#1156). Other combinations report nothing ratherthan guessing, which is the honest default for a table that has not beenreviewed for them."""@@ -219,9 +219,33 @@ _TRANSFORMERS_AUDIO_SFT: tuple[SupportEntry, ...] = (_UNSLOTH_SFT: tuple[SupportEntry, ...] = ()+#: Fields MLX SFT warns about that have no meaning for DPO, or that MLX DPO+#: honours: the seeds (its own loop seeds ``mx.random`` and the batch order)+#: and SFT's response-masking switches (DPO supervises completions by design).+_NOT_DPO_GAPS = frozenset({+ "training.seed",+ "training.data_seed",+ "data.train_on_messages_with_train_field",+ "data.mask_history",+ "data.train_on_prompt",+})++_MLX_DPO: tuple[SupportEntry, ...] = tuple(+ entry for entry in _MLX_SFT if entry.field not in _NOT_DPO_GAPS+) + (+ SupportEntry(+ "data.chat_template",+ IGNORED,+ "MLX DPO renders conversational rows with the model's own chat template",+ trainer_reads=True,+ ),+)++#: ``(task, backend, modality)`` -> the settings that combination does not honour.REGISTRY: dict[tuple[str, str, str], tuple[SupportEntry, ...]] = {("sft", "mlx", "text"): _MLX_SFT,+ ("dpo", "mlx", "text"): _MLX_DPO,("sft", "unsloth", "text"): _UNSLOTH_SFT,("sft", "transformers", "vision"): _TRANSFORMERS_VISION_SFT,("sft", "transformers", "audio"): _TRANSFORMERS_AUDIO_SFT,@@ -251,6 +275,13 @@ TRAINER_MODULES: dict[tuple[str, str, str], tuple[str, ...]] = {"soup_cli/trainer/rewind_mlx.py","soup_cli/trainer/loss_summary.py",),+ ("dpo", "mlx", "text"): (+ "soup_cli/trainer/mlx_dpo.py",+ "soup_cli/trainer/mlx_sft.py",+ "soup_cli/trainer/mlx_optim.py",+ "soup_cli/trainer/_trl_compat.py",+ "soup_cli/trainer/loss_summary.py",+ ),# utils/unsloth.py handles the loader path. trainer/sft.py::_setup_unsloth is not listed# here because listing sft.py would cause the drift guard to inspect transformers-only# precision reads; an AST test in test_issue1124 guards _setup_unsloth instead.diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 9f7e00c8..af6f3068 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -4899,6 +4899,11 @@ UNSLOTH_SETUP_TASKS: frozenset[str] = frozenset({"pretrain", "embedding", "tts",})+#: The tasks with a trainer on ``backend: mlx``: SFT through mlx-lm's tuner and+#: DPO through Soup's own loop (``trainer/mlx_dpo.py``). Validators that defer+#: to :meth:`SoupConfig._validate_mlx_task_support` read this, not ``"sft"``.+MLX_TASKS: frozenset[str] = frozenset({"sft", "dpo"})+#: #1497 — the tasks whose trainer reads ``training.freeze_layers`` /#: ``training.freeze_ratio``: ``SFTTrainerWrapper._setup_transformers``, which#: ``tts`` inherits. Every other trainer ignores both, so they are refused there.@@ -5329,7 +5334,7 @@ class SoupConfig(BaseModel):return selfif self.backend == "unsloth" and self.task not in UNSLOTH_SETUP_TASKS:return self # that task's own backend refusal names the real problem- if self.backend == "mlx" and self.task != "sft":+ if self.backend == "mlx" and self.task not in MLX_TASKS:return self # _validate_mlx_task_support refuses the task itselfwhy = {"unsloth": "its setup loads the model and attaches LoRA in one call, with "@@ -8190,21 +8195,38 @@ class SoupConfig(BaseModel):@model_validator(mode="after")def _validate_mlx_task_support(self) -> "SoupConfig":- """MLX backend only supports sft, dpo, and grpo tasks (v0.25.0).+ """MLX backend supports sft and dpo.- DPO and GRPO wrappers are scaffolding in v0.25.0 — they raise- NotImplementedError at ``train()`` time because upstream mlx-lm has- not yet shipped DPO/GRPO training helpers. Users who pick them will- instead see this friendly error at config-load time.+ SFT runs through mlx-lm's tuner; DPO through Soup's own loop in+ ``trainer/mlx_dpo.py``. Every other task -- GRPO included, whose MLX+ wrapper is still scaffolding -- is refused here rather than at+ ``train()`` time."""if self.backend != "mlx":return self- if self.task == "sft":+ if self.task == "dpo":+ # MLX DPO tokenizes text and chat rows only, and takes its reference+ # log-probs from the policy before training, which is the base+ # model only because a LoRA adapter's B starts at zero.+ if self.modality != "text":+ raise ValueError(+ f"modality='{self.modality}' is not supported by task='dpo' on "+ "backend='mlx': MLX DPO trains on text and chat rows only. "+ "Use backend=transformers, or modality: text."+ )+ if int(self.training.lora.r) < 1:+ raise ValueError(+ "training.lora.r must be at least 1 for task='dpo' on "+ "backend='mlx': the reference model is the untrained LoRA "+ "policy, which needs a LoRA adapter to exist."+ )+ return self+ if self.task in MLX_TASKS:return selfraise ValueError(- f"MLX backend only ships SFT in v0.25.0; task='{self.task}' "- "is not yet implemented (upstream mlx-lm does not expose a "- f"training helper). Use backend=transformers for task={self.task}."+ f"MLX backend only ships SFT and DPO; task='{self.task}' has no "+ "trainer on backend='mlx'. "+ f"Use backend=transformers for task={self.task}.")@model_validator(mode="after")diff --git a/src/soup_cli/trainer/mlx_dpo.py b/src/soup_cli/trainer/mlx_dpo.pyindex 99365f22..7460efbf 100644--- a/src/soup_cli/trainer/mlx_dpo.py+++ b/src/soup_cli/trainer/mlx_dpo.py@@ -1,54 +1,798 @@-"""MLX DPO trainer — Apple Silicon preference alignment (Part E of v0.25.0)."""+"""MLX DPO trainer — native preference alignment on Apple Silicon.++``mlx-lm`` ships no DPO helper, so the loop is Soup's own, built on the same+pieces as MLX SFT: ``linear_to_lora_layers`` for the adapter, the #686+optimizer plan and the #749 gradient clipping wrapper.++Three decisions shape it:++- **The reference model is never loaded.** ``mlx-lm`` initialises LoRA ``B`` to+ zeros, so before the first update the policy *is* the base model. Reference+ log-probs are therefore computed once, in eval mode, before training starts+ -- TRL's ``precompute_ref_log_probs`` -- which halves memory against a second+ frozen copy. A warm start (``--resume``) computes them before the+ checkpoint's weights are loaded, so the reference stays the base model.+- **Tokenization mirrors TRL 0.29's DPO trainer** (text rows get EOS appended,+ conversational rows go through the chat template, the prompt is capped at+ ``max_length // 2`` and completions at what remains), so a ``soup.yaml``+ trains on the same tokens on either backend. Where TRL only *warns* that a+ template is not prefix-stable and then slices at the wrong offset, this+ refuses: a wrong slice supervises the wrong tokens.+- **The run is seeded.** ``training.seed`` seeds ``mx.random`` (LoRA ``A`` init,+ dropout) and the batch order; ``training.data_seed``, when set, owns the batch+ order instead, as it does on the transformers path.+"""from __future__ import annotations-from typing import Optional+import json+import math+import random+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Optionalfrom rich.console import Console-from soup_cli.config.schema import SoupConfig+from soup_cli.trainer._trl_compat import _truncate_tokens+from soup_cli.trainer.loss_summary import summarize_training_loss+from soup_cli.trainer.mlx_sft import (+ MLXSFTTrainerWrapper,+ _clipping_optimizer,+ build_mlx_adapter_config,+)console = Console()-class MLXDPOTrainerWrapper:- """Minimal DPO training wrapper for MLX backend."""+class PreferenceRowError(ValueError):+ """A preference row this trainer cannot turn into supervised tokens."""- def __init__(self, config: SoupConfig) -> None:- self.config = config- self.model = None- self.ref_model = None- self.tokenizer = None- def _require_mlx(self) -> None:- try:- import mlx # noqa: F401- import mlx.core # noqa: F401- except ImportError as exc:- raise ImportError(- "MLX backend requires the 'mlx' and 'mlx-lm' packages. "- "Install with: pip install \"soup-cli[mlx]\""- ) from exc-- def setup(self, dataset: dict) -> None:+class IdenticalPairError(PreferenceRowError):+ """Chosen and rejected are the same: the pair has zero DPO gradient.++ Real preference sets contain ties (UltraFeedback does). TRL trains on them+ at a constant ``log 2``; the trainer skips them and says how many.+ """+++@dataclass(frozen=True)+class PreferenceExample:+ """One tokenized pair: a shared prompt and the two completions after it."""++ prompt_ids: list+ chosen_ids: list+ rejected_ids: list+++# --------------------------------------------------------------------------+# Tokenization+# --------------------------------------------------------------------------+++def _as_ids(value: Any) -> list:+ """``apply_chat_template`` returns ids, or a dict of them under+ ``return_dict`` on some tokenizer builds; normalise to a flat list."""+ if isinstance(value, dict) or hasattr(value, "keys"):+ value = value["input_ids"]+ if value and isinstance(value[0], list):+ value = value[0]+ return list(value)+++class PrefixUnstableError(PreferenceRowError):+ """The template renders the prompt differently once a completion follows."""+++def _normalise_row(row: dict) -> dict:+ """The row in ONE of TRL's two layouts, via the loader's own converter.++ ``soup_cli.data.formats._convert_dpo`` is the contract every backend gets+ from ``load_dataset`` (#1866): text (three strings) or explicit+ conversational (a message-list prompt, answers without the prompt turns).+ It is idempotent, so rows the loader already converted pass through, and+ rows handed straight to ``setup()`` get the same reading and the same+ refusals, which name the field.+ """+ from soup_cli.data.formats import _convert_dpo++ try:+ return _convert_dpo(row)+ except (TypeError, ValueError) as exc:+ raise PreferenceRowError(str(exc)) from exc+++def build_preference_example(+ row: dict,+ tokenizer: Any,+ *,+ max_length: int,+ max_prompt_length: int,+ truncation_mode: str = "keep_start",+) -> PreferenceExample:+ """Tokenize one ``{prompt, chosen, rejected}`` row the way TRL 0.29 does.++ Differences from TRL, on purpose: a tie (``chosen == rejected``) raises+ :class:`IdenticalPairError` so the caller can skip it (TRL trains it at a+ constant loss, zero gradient), and a template that is not prefix-stable for+ the row raises :class:`PrefixUnstableError` where TRL warns and slices+ anyway. Per-row ``tools`` / ``chat_template_kwargs`` are not applied.+ """+ row = _normalise_row(row)+ prompt, chosen, rejected = row["prompt"], row["chosen"], row["rejected"]+ if chosen == rejected:+ raise IdenticalPairError(+ "dpo row has identical chosen and rejected completions; there is "+ "no completion to prefer"+ )++ if isinstance(prompt, list):+ prompt_ids = _as_ids(+ tokenizer.apply_chat_template(prompt, add_generation_prompt=True, tokenize=True)+ )+ full_chosen = _as_ids(tokenizer.apply_chat_template(prompt + chosen, tokenize=True))+ full_rejected = _as_ids(tokenizer.apply_chat_template(prompt + rejected, tokenize=True))+ else:+ eos = getattr(tokenizer, "eos_token", None) or ""++ def with_eos(text: str) -> str:+ return text if not eos or text.endswith(eos) else text + eos++ prompt_ids = list(tokenizer.encode(prompt))+ full_chosen = list(tokenizer.encode(prompt + with_eos(chosen)))+ full_rejected = list(tokenizer.encode(prompt + with_eos(rejected)))++ if full_chosen == full_rejected:+ raise IdenticalPairError(+ "dpo row has identical chosen and rejected completions; there is "+ "no completion to prefer"+ )+ n = len(prompt_ids)+ if full_chosen[:n] != prompt_ids or full_rejected[:n] != prompt_ids:+ raise PrefixUnstableError(+ "the tokenized prompt is not a prefix of the tokenized prompt + "+ "completion, so the completion cannot be located; this tokenizer or "+ "chat template is not prefix-stable for this row"+ )++ prompt_ids = _truncate_tokens(prompt_ids, max_prompt_length, truncation_mode)+ room = max(0, max_length - len(prompt_ids))+ return PreferenceExample(+ prompt_ids=prompt_ids,+ chosen_ids=full_chosen[n:][:room],+ rejected_ids=full_rejected[n:][:room],+ )+++# --------------------------------------------------------------------------+# Batching+# --------------------------------------------------------------------------+++def plan_batches(n_rows: int, batch_size: int, epochs: int, seed: int) -> list:+ """Every epoch's full batches, shuffled reproducibly from ``seed``.++ The order is drawn from a private ``random.Random`` so nothing else that+ touches the global RNGs can change it. A trailing partial batch is+ dropped, as ``mlx-lm`` does.+ """+ if n_rows < batch_size:+ raise ValueError(+ f"dpo dataset has {n_rows} row(s), fewer than batch_size={batch_size}"+ )+ rng = random.Random(seed)+ plan = []+ for _ in range(max(1, int(epochs))):+ order = list(range(n_rows))+ rng.shuffle(order)+ plan.extend(+ order[i : i + batch_size]+ for i in range(0, n_rows - batch_size + 1, batch_size)+ )+ return plan+++def collate_pairs(examples: list) -> tuple[list, list]:+ """Stack chosen sequences, then rejected ones, right-padded with 0.++ The mask marks completion tokens -- the only ones whose log-probs DPO sums.+ Padding id 0 is never read: attention is causal and the mask is 0 there.+ """+ seqs, masks = [], []+ for side in ("chosen_ids", "rejected_ids"):+ for ex in examples:+ completion = getattr(ex, side)+ seqs.append(list(ex.prompt_ids) + list(completion))+ masks.append([0] * len(ex.prompt_ids) + [1] * len(completion))+ width = max(len(s) for s in seqs)+ tokens = [s + [0] * (width - len(s)) for s in seqs]+ mask = [m + [0] * (width - len(m)) for m in masks]+ return tokens, mask+++# --------------------------------------------------------------------------+# Loss+# --------------------------------------------------------------------------+++#: Positions per vocab-head chunk. A chunk's float32 logits are+#: ``2 * batch_size * chunk_size * vocab * 4`` bytes: 640 MB for Qwen2.5's+#: 152k vocab at batch_size 2. Only one chunk is alive at a time.+DEFAULT_LOGIT_CHUNK = 128+++def resolve_head_split(model: Any) -> Optional[tuple]:+ """``(backbone, head)`` for an mlx-lm causal LM, or None if unrecognised.++ mlx-lm models compute ``head(self.model(x))`` where the head is the tied+ embedding (``embed_tokens.as_linear``) or ``lm_head``. Some architectures+ do more after the head (Gemma's logit soft-capping), so the trainer checks+ the split against the full model on real data before relying on it.+ """+ from mlx.utils import tree_flatten++ backbone = getattr(model, "model", None)+ if backbone is None or not callable(backbone):+ return None+ args = getattr(model, "args", None)+ embed = getattr(backbone, "embed_tokens", None)+ if getattr(args, "tie_word_embeddings", False) and embed is not None:+ owner, head = embed, embed.as_linear+ elif getattr(model, "lm_head", None) is not None:+ owner = head = model.lm_head+ else:+ return None+ # The checkpointed chunk closes over the head's weights as constants, so a+ # head that trains (LoRA on lm_head, a full fine-tune) would get no+ # gradient through it. Only a frozen head may take the chunked path.+ if tree_flatten(owner.trainable_parameters()):+ return None+ return backbone, head+++def _chunk_logps(head: Any, hidden: Any, targets: Any, mask: Any) -> Any:+ import mlx.core as mx+ import mlx.nn as nn++ logits = head(hidden).astype(mx.float32)+ nll = nn.losses.cross_entropy(logits, targets, reduction="none")+ return -(nll * mask).sum(axis=-1)+++def sequence_logps(+ model: Any,+ tokens: Any,+ mask: Any,+ *,+ head_split: Optional[tuple] = None,+ chunk_size: int = DEFAULT_LOGIT_CHUNK,+) -> Any:+ """Summed log-prob of every masked token, one value per sequence.++ Without ``head_split`` the whole model runs and every position's logits are+ materialised (and kept for the backward pass): about 17 MB per padded+ position at batch_size 2 on a 152k vocab, which put a 1024-token batch past+ 38 GB. With it, the backbone runs once and the head runs in checkpointed+ chunks from the first completion position on -- prompt positions never+ reach the head, and each chunk's logits are recomputed in the backward pass+ instead of stored.+ """+ import mlx.core as mx++ targets = tokens[:, 1:]+ target_mask = mask[:, 1:].astype(mx.float32)+ if head_split is None:+ import mlx.nn as nn++ logits = model(tokens[:, :-1]).astype(mx.float32)+ nll = nn.losses.cross_entropy(logits, targets, reduction="none")+ return -(nll * target_mask).sum(axis=-1)++ backbone, head = head_split+ hidden = backbone(tokens[:, :-1])+ active = target_mask.max(axis=0)+ width = int(active.shape[0])+ start = int(mx.argmax(active).item()) if width else 0+ total = mx.zeros((tokens.shape[0],), dtype=mx.float32)+ for lo in range(start, width, max(1, int(chunk_size))):+ hi = min(width, lo + int(chunk_size))+ # Only the hidden states are a checkpoint input: mx.checkpoint+ # differentiates every argument, and targets are not differentiable.+ chunk = mx.checkpoint(+ lambda h, t=targets[:, lo:hi], m=target_mask[:, lo:hi]: _chunk_logps(+ head, h, t, m+ )+ )+ total = total + chunk(hidden[:, lo:hi])+ return total+++def dpo_loss(+ policy_chosen: Any,+ policy_rejected: Any,+ ref_chosen: Any,+ ref_rejected: Any,+ beta: float,+) -> tuple[Any, dict]:+ """Sigmoid DPO loss (Rafailov et al.), TRL's ``loss_type="sigmoid"``.++ ``-log σ(z)`` is computed as ``logaddexp(0, -z)`` so a large margin in+ either direction stays finite.+ """+ import mlx.core as mx++ chosen_rewards = beta * (policy_chosen - ref_chosen)+ rejected_rewards = beta * (policy_rejected - ref_rejected)+ z = chosen_rewards - rejected_rewards+ loss = mx.logaddexp(mx.zeros_like(z), -z).mean()+ metrics = {+ "reward_accuracy": (chosen_rewards > rejected_rewards).astype(mx.float32).mean(),+ "reward_margin": z.mean(),+ }+ return loss, metrics+++# --------------------------------------------------------------------------+# Trainer+# --------------------------------------------------------------------------+++def _clear_allocator_cache() -> None:+ import mlx.core as mx++ if mx.get_cache_memory() > 0:+ mx.clear_cache()+++class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):+ """DPO on MLX. Reuses MLX SFT's model loading, LoRA attach and warm start."""++ def _check_unsupported(self) -> None:+ tcfg = self.config.training+ unsupported = []+ if tcfg.quantization == "8bit":+ unsupported.append("quantization=8bit (use mlx-community 4bit models)")+ if self.config.data.chat_template:+ unsupported.append(+ "data.chat_template (MLX DPO renders with the model's own template)"+ )+ for name, label in (+ ("use_galore", "GaLore"),+ ("use_lorafa", "training.use_lorafa"),+ ("use_ring_attention", "Ring Attention"),+ ("use_flash_attn", "FlashAttention (MLX has its own attention kernels)"),+ ("use_liger", "training.use_liger"),+ ("use_mod", "training.use_mod"),+ ("moe_lora", "training.moe_lora"),+ ("quantization_aware", "training.quantization_aware"),+ ("use_fsdp2_compile", "training.use_fsdp2_compile"),+ ):+ if getattr(tcfg, name, False):+ unsupported.append(label)+ if tcfg.neftune_alpha is not None:+ unsupported.append("training.neftune_alpha")+ if isinstance(tcfg.gradient_checkpointing, str):+ unsupported.append(+ f"gradient_checkpointing tier {tcfg.gradient_checkpointing!r} "+ "(MLX has a single on/off switch; enabling it)"+ )+ if unsupported:+ console.print(+ "[yellow]MLX backend ignores: " + ", ".join(unsupported) + "[/]"+ )++ # -- data -------------------------------------------------------------++ def _examples(self, rows: list, split: str = "train") -> tuple[list, int]:+ """Tokenized pairs, and how many tied rows were skipped.++ A row the template is not prefix-stable for is skipped too, counted and+ reported with the first offender, rather than ending a run whose model+ has already loaded: with a BPE tokenizer one text row whose prompt ends+ in a space is enough. A row the converter refuses still stops the run,+ with its index: that is malformed data, not a tokenizer quirk.+ """+ cfg = self.config+ max_length = int(getattr(cfg.data, "max_length", 2048) or 2048)+ examples, ties, unstable = [], 0, []+ for index, row in enumerate(rows):+ try:+ examples.append(+ build_preference_example(+ row,+ self.tokenizer,+ max_length=max_length,+ max_prompt_length=max_length // 2,+ )+ )+ except IdenticalPairError:+ ties += 1+ except PrefixUnstableError:+ unstable.append(index)+ except PreferenceRowError as exc:+ raise PreferenceRowError(f"dpo {split} row {index}: {exc}") from exc+ if unstable:+ console.print(+ f"[yellow]MLX DPO: skipped {len(unstable)} {split} row(s) whose "+ "completion could not be located (the chat template or tokenizer "+ "renders the prompt differently once a completion follows; first: "+ f"row {unstable[0]})[/]"+ )+ return examples, ties++ @staticmethod+ def _to_arrays(examples: list) -> tuple[Any, Any]:+ import mlx.core as mx++ tokens, mask = collate_pairs(examples)+ return mx.array(tokens), mx.array(mask)++ def _reference_logps(self, examples: list, batch_size: int) -> tuple[Any, Any]:+ """Log-probs of the still-untrained policy: the reference model."""+ import mlx.core as mx++ self.model.eval()+ chosen, rejected = [], []+ total = len(examples)+ console.print(f"[dim]MLX DPO: computing reference log-probs for {total} pair(s)[/]")+ every = max(batch_size, (total // 10) // batch_size * batch_size)+ for start in range(0, total, batch_size):+ if start and start % every == 0:+ console.print(f"[dim] reference log-probs: {start}/{total}[/]")+ chunk = examples[start : start + batch_size]+ tokens, mask = self._to_arrays(chunk)+ logps = mx.stop_gradient(+ sequence_logps(self.model, tokens, mask, head_split=self._head_split)+ )+ mx.eval(logps)+ chosen.append(logps[: len(chunk)])+ rejected.append(logps[len(chunk) :])+ _clear_allocator_cache()+ self.model.train()+ return mx.concatenate(chosen), mx.concatenate(rejected)++ _head_split: Optional[tuple] = None++ def _verified_head_split(self, sample: list) -> Optional[tuple]:+ """The chunked head path, if it reproduces the full model on ``sample``.++ An architecture that post-processes logits after the head (soft-capping,+ scaling) would silently train against different log-probs; one batch of+ real data decides, and a mismatch costs memory, not correctness.+ """+ import mlx.core as mx++ split = resolve_head_split(self.model)+ if split is None or not sample:+ if split is None:+ console.print(+ "[yellow]MLX DPO: computing log-probs over the full vocabulary "+ "for every position (no frozen vocab head found); long "+ "sequences need more memory[/]"+ )+ return split+ self.model.eval()+ tokens, mask = self._to_arrays(sample)+ full = sequence_logps(self.model, tokens, mask)+ chunked = sequence_logps(self.model, tokens, mask, head_split=split)+ same = mx.allclose(full, chunked, rtol=1e-3, atol=1e-2).item()+ self.model.train()+ if not same:+ console.print(+ "[yellow]MLX DPO: this architecture changes logits after the vocab "+ "head; using the full-vocabulary path (more memory)[/]"+ )+ return None+ return split++ # -- loop -------------------------------------------------------------++ def train(self, display=None, tracker=None, run_id=None, resume_from_checkpoint=None) -> dict:self._require_mlx()- from soup_cli.utils.mlx import load_mlx_model++ import mlx.core as mx+ import mlx.nn as nn+ from mlx.utils import tree_flatten, tree_map++ from soup_cli.trainer.mlx_optim import build_optimizer, plan_optimizercfg = self.config- console.print(f"[dim]Loading MLX model for DPO: {cfg.base}[/]")- self.model, self.tokenizer = load_mlx_model(- cfg.base, quantization=cfg.training.quantization+ tcfg = cfg.training+ if self.model is None or self.tokenizer is None:+ raise RuntimeError("MLX backend: setup(dataset) must be called before train()")++ from soup_cli.utils.seeding import resolve_training_seed++ seed = resolve_training_seed(tcfg)+ data_seed = seed if tcfg.data_seed is None else int(tcfg.data_seed)+ mx.random.seed(seed)++ output_dir = Path(cfg.output)+ output_dir.mkdir(parents=True, exist_ok=True)+ batch_size = int(tcfg.batch_size) if isinstance(tcfg.batch_size, int) else 1+ accum = max(1, int(tcfg.gradient_accumulation_steps))+ beta = float(tcfg.dpo_beta)++ train_examples, train_ties = self._examples(list(self._dataset.get("train", [])))+ val_examples, val_ties = self._examples(list(self._dataset.get("val", [])), "val")+ skipped = train_ties + val_ties+ if skipped:+ console.print(+ f"[yellow]MLX DPO: skipped {skipped} dpo row(s) with identical "+ "chosen and rejected (a tie carries no preference signal)[/]"+ )+ if len(train_examples) < batch_size:+ raise ValueError(+ f"MLX DPO: {len(train_examples)} training pair(s) remain, fewer than "+ f"training.batch_size ({batch_size})"+ + (f", after skipping {train_ties} tie(s)" if train_ties else "")+ + f". Lower training.batch_size to at most {max(1, len(train_examples))} "+ "or add rows."+ )+ plan = plan_batches(len(train_examples), batch_size, int(tcfg.epochs), data_seed)+ iters = len(plan)+ if accum > 1:+ # Like MLX SFT: no partial accumulation group is ever flushed.+ iters = max(accum, iters - iters % accum)+ plan = (plan * math.ceil(iters / len(plan)))[:iters]+ total_updates = max(1, iters // accum)+ batches_per_epoch = max(1, len(train_examples) // batch_size)++ self._apply_lora(self.model)+ if tcfg.gradient_checkpointing:+ from mlx_lm.tuner.trainer import grad_checkpoint++ grad_checkpoint(self.model.layers[0])+ self._head_split = self._verified_head_split(train_examples[:batch_size])++ # Before any adapter weights move: this is the base model.+ ref_train = self._reference_logps(train_examples, batch_size)+ ref_val = (+ self._reference_logps(val_examples, batch_size) if val_examples else None)- # Reference model: frozen copy of base- self.ref_model, _ = load_mlx_model(cfg.base, quantization=cfg.training.quantization)- self._dataset = dataset+ if resume_from_checkpoint is not None:+ self._load_checkpoint_weights(resume_from_checkpoint)- def train(self, resume_from: Optional[str] = None) -> None:- """MLX DPO training loop (delegates to mlx_lm.dpo when available)."""- self._require_mlx()- # Delegation to a real MLX DPO implementation would go here.- raise NotImplementedError(- "MLX DPO training loop requires mlx-lm ≥ 0.25 with DPO support. "- "This wrapper is scaffolding for the v0.25.0 release; full "- "training loop lands when mlx-lm upstream lands its DPO helper."+ optimizer_plan = plan_optimizer(+ lr=float(tcfg.lr),+ optimizer=str(getattr(tcfg, "optimizer", "adamw_torch")),+ scheduler=str(getattr(tcfg, "scheduler", "cosine")),+ warmup_ratio=float(getattr(tcfg, "warmup_ratio", 0.0) or 0.0),+ weight_decay=float(getattr(tcfg, "weight_decay", 0.0) or 0.0),+ total_updates=total_updates,+ )+ for warning in optimizer_plan.warnings:+ console.print(f"[yellow]MLX backend: {warning}[/]")+ optimizer = _clipping_optimizer(+ build_optimizer(optimizer_plan), float(tcfg.max_grad_norm)+ )++ def loss_fn(model, tokens, mask, ref_chosen, ref_rejected):+ logps = sequence_logps(model, tokens, mask, head_split=self._head_split)+ half = ref_chosen.shape[0]+ loss, metrics = dpo_loss(+ logps[:half], logps[half:], ref_chosen, ref_rejected, beta+ )+ return loss, metrics++ loss_and_grad = nn.value_and_grad(self.model, loss_fn)++ def evaluate() -> Optional[dict]:+ if not val_examples:+ return None+ self.model.eval()+ losses, accs = [], []+ for start in range(0, len(val_examples), batch_size):+ chunk = val_examples[start : start + batch_size]+ tokens, mask = self._to_arrays(chunk)+ end = start + len(chunk)+ loss, metrics = loss_fn(+ self.model, tokens, mask, ref_val[0][start:end], ref_val[1][start:end]+ )+ mx.eval(loss, metrics["reward_accuracy"])+ losses.append(loss.item() * len(chunk))+ accs.append(metrics["reward_accuracy"].item() * len(chunk))+ self.model.train()+ return {+ "val_loss": sum(losses) / len(val_examples),+ "val_reward_accuracy": sum(accs) / len(val_examples),+ }++ def save(path: Path) -> None:+ mx.save_safetensors(str(path), dict(tree_flatten(self.model.trainable_parameters())))++ save_steps = int(getattr(tcfg, "save_steps", 0) or 0)+ logging_steps = max(1, int(getattr(tcfg, "logging_steps", 10) or 10))+ epochs = float(tcfg.epochs)+ losses: list = []+ final_eval: Optional[dict] = None+ logged_at = 0+ if display is not None:+ display.start(iters)++ self.model.train()+ grads = None+ group_loss = group_acc = group_margin = 0.0+ t0 = tic = time.time()+ try:+ for it, batch in enumerate(plan, start=1):+ chunk = [train_examples[i] for i in batch]+ tokens, mask = self._to_arrays(chunk)+ idx = mx.array(batch)+ (loss, metrics), step_grads = loss_and_grad(+ self.model, tokens, mask, ref_train[0][idx], ref_train[1][idx]+ )+ grads = (+ step_grads+ if grads is None+ else tree_map(lambda a, b: a + b, grads, step_grads)+ )+ mx.eval(loss, metrics["reward_accuracy"], metrics["reward_margin"], grads)+ # mlx-lm's default (`clear_cache_threshold: 0`): free the+ # allocator cache every iteration. Batches have a new padded+ # width almost every step, so cached buffers rarely fit the+ # next one; kept, they grew the process to ~40 GB on a run+ # whose largest step needs under 4 GB.+ _clear_allocator_cache()+ group_loss += loss.item()+ group_acc += metrics["reward_accuracy"].item()+ group_margin += metrics["reward_margin"].item()++ # Counted in iterations, as mlx-lm's `steps_per_save` is for MLX+ # SFT, so the file names line up with `--resume auto`. Checked+ # before the accumulation gate: inside it, a cadence that is not+ # a multiple of the group size skipped saves. Mid-group, the+ # weights saved are those of the last update.+ if save_steps > 0 and it % save_steps == 0:+ save(output_dir / f"{it:07d}_adapters.safetensors")+ if it % accum:+ continue+ if accum > 1:+ grads = tree_map(lambda g: g / accum, grads)+ optimizer.update(self.model, grads)+ mx.eval(self.model.parameters(), optimizer.state)+ grads = None+ update = it // accum+ step_loss = group_loss / accum+ losses.append(step_loss)+ reward_acc, margin = group_acc / accum, group_margin / accum+ group_loss = group_acc = group_margin = 0.0++ # Evaluate once per epoch: when this update crossed an epoch+ # boundary, or on the last update.+ crossed = it // batches_per_epoch > (it - accum) // batches_per_epoch+ val = evaluate() if crossed or it == iters else None+ if val is not None:+ final_eval = val++ if update % logging_steps == 0 or it == iters or val is not None:+ now = time.time()+ speed = (it - logged_at) / max(now - tic, 1e-9)+ tic, logged_at = now, it+ self._report(+ display, tracker, run_id,+ step=it, epoch=it / iters * epochs,+ loss=step_loss, lr=self._current_lr(optimizer, tcfg.lr),+ speed=speed, reward_acc=reward_acc, margin=margin, val=val,+ )++ finally:+ if display is not None:+ display.stop()+ duration = time.time() - t0++ save(output_dir / "adapters.safetensors")+ self._write_adapter_config(+ output_dir, batch_size=batch_size, iters=iters, accum=accum,+ optimizer_plan=optimizer_plan, seed=seed, data_seed=data_seed,+ )++ result = {+ **summarize_training_loss([{"loss": loss} for loss in losses]),+ "losses": losses,+ "total_steps": iters,+ "duration_secs": duration,+ "duration": f"{duration:.0f}s",+ "output_dir": str(output_dir),+ "skipped_identical_pairs": skipped,+ }+ if final_eval is not None:+ result.update(final_eval)+ console.print(f"[green]MLX DPO training complete:[/] {output_dir}")+ return result++ # -- helpers ----------------------------------------------------------++ @staticmethod+ def _current_lr(optimizer: Any, fallback: float) -> float:+ try:+ return float(optimizer.learning_rate)+ except (TypeError, ValueError, AttributeError):+ return float(fallback)++ @staticmethod+ def _report(display, tracker, run_id, *, step, epoch, loss, lr, speed,+ reward_acc, margin, val) -> None:+ val_loss = val["val_loss"] if val else None+ try:+ import mlx.core as mx++ peak = (getattr(mx, "get_peak_memory", None) or mx.metal.get_peak_memory)()+ gpu_mem = f"{peak / 1e9:.3f} GB"+ except Exception: # noqa: BLE001 — telemetry must not kill a run+ gpu_mem = ""+ if display is not None:+ display.update(+ step=step, epoch=epoch, loss=loss, lr=lr, speed=speed,+ gpu_mem=gpu_mem, val_loss=val_loss,+ )+ else:+ msg = (+ f"step {step}: loss {loss:.4f}, reward acc {reward_acc:.2f}, "+ f"margin {margin:.4f}"+ )+ if val:+ msg += (+ f", val loss {val['val_loss']:.4f}, "+ f"val reward acc {val['val_reward_accuracy']:.2f}"+ )+ console.print(f"[dim]{msg}[/]")+ if tracker is not None and run_id:+ try:+ tracker.log_metrics(+ run_id=run_id, step=step, epoch=epoch, loss=loss, lr=lr,+ speed=speed, gpu_mem=gpu_mem, val_loss=val_loss,+ )+ except Exception: # noqa: BLE001 — telemetry must not kill a run+ pass+ if display is not None:+ # `soup ui` / GET /api/train/stream, in MLX SFT's shape. Only with a+ # display, as on the transformers path. Reward accuracy and margin+ # have no event field: they are printed without a display and+ # returned in train()'s result.+ try:+ from soup_cli.utils.sse_train_stream import TrainEvent+ from soup_cli.utils.train_event_buffer import push_train_event++ push_train_event(+ TrainEvent(+ type="metric", step=step, epoch=float(epoch), loss=float(loss),+ lr=float(lr), val_loss=val_loss,+ )+ )+ except Exception: # noqa: BLE001 — telemetry must not kill a run+ pass++ def _write_adapter_config(self, output_dir: Path, *, batch_size, iters, accum,+ optimizer_plan, seed, data_seed) -> None:+ """The same loadable shape MLX SFT writes, plus what DPO ran with."""+ cfg = self.config+ (output_dir / "adapter_config.json").write_text(+ json.dumps(+ {+ "fine_tune_type": "lora",+ "model": str(cfg.base),+ "num_layers": len(getattr(self.model, "layers", [])),+ "batch_size": batch_size,+ "iters": iters,+ "learning_rate": float(cfg.training.lr),+ "max_seq_length": int(getattr(cfg.data, "max_length", 2048) or 2048),+ "adapter_path": str(output_dir),+ "lora_parameters": build_mlx_adapter_config(+ cfg.training.lora, adapter_path=str(output_dir)+ )["lora_parameters"],+ "grad_accumulation_steps": accum,+ **optimizer_plan.as_metadata(),+ "max_grad_norm": float(cfg.training.max_grad_norm),+ "task": "dpo",+ "dpo_beta": float(cfg.training.dpo_beta),+ "dpo_loss_type": "sigmoid",+ "reference": "precomputed from the base model",+ "seed": seed,+ "data_seed": data_seed,+ },+ indent=2,+ ))diff --git a/tests/test_issue1324_mlx_loraplus_refusal.py b/tests/test_issue1324_mlx_loraplus_refusal.pyindex 9fda94cd..de3c86c8 100644--- a/tests/test_issue1324_mlx_loraplus_refusal.py+++ b/tests/test_issue1324_mlx_loraplus_refusal.py@@ -94,7 +94,7 @@ def test_train_dry_run_exits_nonzero_on_mlx_loraplus(tmp_path: Path):@pytest.mark.parametrize("task, data_format",- [("dpo", "dpo"), ("kto", "kto"), ("pretrain", "plaintext"), ("embedding", "alpaca")],+ [("ipo", "dpo"), ("kto", "kto"), ("pretrain", "plaintext"), ("embedding", "alpaca")],)def test_a_task_mlx_cannot_run_is_refused_for_that_first(task, data_format):"""The MLX task gate runs first: switching backend is the whole fix there."""diff --git a/tests/test_issue1358_vocab_expansion_refused.py b/tests/test_issue1358_vocab_expansion_refused.pyindex 2c12c37a..331b5abd 100644--- a/tests/test_issue1358_vocab_expansion_refused.py+++ b/tests/test_issue1358_vocab_expansion_refused.py@@ -276,7 +276,7 @@ class TestABackendTheTaskCannotRunOnIsNamedFirst:@pytest.mark.parametrize(("task", "backend", "expected"), [("online_dpo", "unsloth", "task='online_dpo' requires backend='transformers'"),- ("dpo", "mlx", "MLX backend only ships SFT"),+ ("ipo", "mlx", "MLX backend only ships SFT"),("kto", "mlx", "MLX backend only ships SFT"),])def test_the_backend_refusal_comes_first(self, task, backend, expected):diff --git a/tests/test_issue353_mlx_seed_warning.py b/tests/test_issue353_mlx_seed_warning.pyindex 64c016b9..a30e648e 100644--- a/tests/test_issue353_mlx_seed_warning.py+++ b/tests/test_issue353_mlx_seed_warning.py@@ -96,9 +96,12 @@ def test_the_mlx_wrappers_still_do_not_read_the_seed(monkeypatch):commit instead of leaving a run lying about itself."""import inspect- from soup_cli.trainer import mlx_dpo, mlx_grpo, mlx_sft+ from soup_cli.trainer import mlx_grpo, mlx_sft- for module in (mlx_sft, mlx_dpo, mlx_grpo):+ # mlx_dpo is not here: it runs its own loop and seeds `mx.random` and the+ # batch order (tests/test_mlx_dpo.py pins the reproducibility), so it never+ # carried the warning.+ for module in (mlx_sft, mlx_grpo):source = inspect.getsource(module)# `_check_unsupported` legitimately mentions the field it is warning# about, so the sources are checked for an actual RNG call instead.diff --git a/tests/test_issue353_seed_every_task.py b/tests/test_issue353_seed_every_task.pyindex f73f56ee..20812f5e 100644--- a/tests/test_issue353_seed_every_task.py+++ b/tests/test_issue353_seed_every_task.py@@ -514,7 +514,6 @@ _NOT_SEEDED = {"model_copy carries the seed into","bitnet": "raises before it builds anything; hardware-gated path","mlx_sft": "MLX backend, which seeds nothing on any path yet",- "mlx_dpo": "MLX backend, which seeds nothing on any path yet","mlx_grpo": "MLX backend, which seeds nothing on any path yet",}diff --git a/tests/test_mlx_backend.py b/tests/test_mlx_backend.pyindex 3b6917f7..52fa89dd 100644--- a/tests/test_mlx_backend.py+++ b/tests/test_mlx_backend.py@@ -282,8 +282,8 @@ class TestMLXRecipes:assert cfg.base == "mlx-community/gemma-3-4b-it-4bit"assert cfg.backend == "mlx"- def test_mlx_dpo_config_rejected_at_load(self):- """backend=mlx + task=dpo is rejected by the SoupConfig validator."""+ def test_mlx_dpo_config_loads(self):+ """backend=mlx + task=dpo has a trainer (trainer/mlx_dpo.py) and loads."""from soup_cli.config.loader import load_config_from_stringyaml_str = """@@ -298,8 +298,8 @@ training:lr: 1e-6output: ./output"""- with pytest.raises(ValueError, match="MLX backend only ships SFT"):- load_config_from_string(yaml_str)+ cfg = load_config_from_string(yaml_str)+ assert (cfg.task, cfg.backend) == ("dpo", "mlx")def test_mlx_grpo_config_rejected_at_load(self):from soup_cli.config.loader import load_config_from_stringdiff --git a/tests/test_mlx_dispatch.py b/tests/test_mlx_dispatch.pyindex 69b2c593..6013185b 100644--- a/tests/test_mlx_dispatch.py+++ b/tests/test_mlx_dispatch.py@@ -75,11 +75,12 @@ def test_resolve_trainer_forwards_trainer_kwargs():def test_schema_rejects_mlx_for_non_sft_tasks():- """The schema gate (#270 prerequisite): mlx + dpo/grpo/ppo must not- reach the trainer dispatch with a silent fallthrough."""+ """The schema gate (#270 prerequisite): mlx + grpo/ppo/ipo must not+ reach the trainer dispatch with a silent fallthrough. (dpo has an MLX+ trainer now; tests/test_mlx_dpo.py covers it.)"""from soup_cli.config.loader import load_config_from_string- for task in ("dpo", "grpo", "ppo"):+ for task in ("grpo", "ppo", "ipo"):with pytest.raises(ValueError, match="MLX backend"):load_config_from_string("base: mlx-community/tiny\n"diff --git a/tests/test_mlx_dpo.py b/tests/test_mlx_dpo.pynew file mode 100644index 00000000..5383cc6e--- /dev/null+++ b/tests/test_mlx_dpo.py@@ -0,0 +1,991 @@+"""Native MLX DPO trainer: tokenization, batching, loss and the training loop.++The tokenization tests run everywhere with a character-level fake tokenizer.+The loss, log-prob and training-loop tests need ``mlx`` and skip without it.+"""++from __future__ import annotations++import json+import math+import re++import pytest+++def _strip_ansi(text: str) -> str:+ """Rich styles numbers and wraps at the console width; compare plain words."""+ return " ".join(re.sub(r"\x1b\[[0-9;]*m", "", text).split())+++# --------------------------------------------------------------------------+# A character-level tokenizer with a deterministic chat template+# --------------------------------------------------------------------------++BOS = 1+EOS = 3+++class FakeTokenizer:+ """One token per character, BOS prepended, ``\\x03`` as EOS."""++ eos_token = "\x03"+ eos_token_id = EOS+ pad_token_id = 0++ def encode(self, text: str) -> list[int]:+ return [BOS] + [ord(c) for c in text]++ def _render(self, messages, add_generation_prompt: bool) -> str:+ out = "".join(f"<{m['role']}>{m['content']}\x03" for m in messages)+ if add_generation_prompt:+ out += "<assistant>"+ return out++ def apply_chat_template(+ self, messages, add_generation_prompt=False, tokenize=True, return_dict=False+ ):+ text = self._render(messages, add_generation_prompt)+ if not tokenize:+ return text+ ids = self.encode(text)+ return {"input_ids": ids} if return_dict else ids+++def _decode(ids: list[int]) -> str:+ return "".join(chr(i) for i in ids if i != BOS)+++# --------------------------------------------------------------------------+# build_preference_example+# --------------------------------------------------------------------------+++class TestBuildPreferenceExample:+ def _build(self, row, max_length=1024, max_prompt_length=512, mode="keep_start"):+ from soup_cli.trainer.mlx_dpo import build_preference_example++ return build_preference_example(+ row,+ FakeTokenizer(),+ max_length=max_length,+ max_prompt_length=max_prompt_length,+ truncation_mode=mode,+ )++ def test_text_row_matches_trl_layout(self):+ """Text rows: prompt tokens, then prompt+completion+EOS sliced after them."""+ ex = self._build({"prompt": "Q:", "chosen": " yes", "rejected": " no"})+ assert ex.prompt_ids == [BOS] + [ord(c) for c in "Q:"]+ assert _decode(ex.chosen_ids) == " yes\x03"+ assert _decode(ex.rejected_ids) == " no\x03"++ def test_text_row_does_not_double_eos(self):+ ex = self._build({"prompt": "Q:", "chosen": " yes\x03", "rejected": " no"})+ assert _decode(ex.chosen_ids) == " yes\x03"++ def test_conversational_row_uses_chat_template(self):+ row = {+ "prompt": [{"role": "user", "content": "hi"}],+ "chosen": [{"role": "assistant", "content": "hello"}],+ "rejected": [{"role": "assistant", "content": "go away"}],+ }+ ex = self._build(row)+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+ # The completion is whatever follows the generation prompt.+ assert _decode(ex.chosen_ids) == "hello\x03"+ assert _decode(ex.rejected_ids) == "go away\x03"++ def test_implicit_prompt_in_full_conversations(self):+ """Soup's bundled DPO sample: a string prompt plus full chosen/rejected+ conversations that repeat the user turn. The shared leading turns are+ the prompt, not part of the supervised completion."""+ user = {"role": "user", "content": "hi"}+ row = {+ "prompt": "hi",+ "chosen": [user, {"role": "assistant", "content": "hello"}],+ "rejected": [user, {"role": "assistant", "content": "nope"}],+ }+ ex = self._build(row)+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+ assert _decode(ex.chosen_ids) == "hello\x03"+ assert _decode(ex.rejected_ids) == "nope\x03"++ def test_string_prompt_with_assistant_only_lists_becomes_user_turn(self):+ row = {+ "prompt": "hi",+ "chosen": [{"role": "assistant", "content": "hello"}],+ "rejected": [{"role": "assistant", "content": "nope"}],+ }+ ex = self._build(row)+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"++ def test_prompt_list_repeated_inside_chosen_is_not_duplicated(self):+ user = {"role": "user", "content": "hi"}+ row = {+ "prompt": [user],+ "chosen": [user, {"role": "assistant", "content": "a"}],+ "rejected": [user, {"role": "assistant", "content": "b"}],+ }+ ex = self._build(row)+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+ assert _decode(ex.chosen_ids) == "a\x03"++ def test_mixed_string_and_list_completions_refused(self):+ from soup_cli.trainer.mlx_dpo import PreferenceRowError++ with pytest.raises(PreferenceRowError, match="chosen"):+ self._build(+ {+ "prompt": "hi",+ "chosen": "hello",+ "rejected": [{"role": "assistant", "content": "x"}],+ }+ )++ def test_identical_conversations_flagged(self):+ """No turn differs, so there is no completion to prefer."""+ from soup_cli.trainer.mlx_dpo import IdenticalPairError++ user = {"role": "user", "content": "hi"}+ same = [user, {"role": "assistant", "content": "a"}]+ with pytest.raises(IdenticalPairError, match="identical"):+ self._build({"prompt": "hi", "chosen": same, "rejected": list(same)})++ def test_identical_text_completions_flagged(self):+ from soup_cli.trainer.mlx_dpo import IdenticalPairError++ with pytest.raises(IdenticalPairError):+ self._build({"prompt": "Q", "chosen": "a", "rejected": "a"})++ def test_template_that_is_not_prefix_stable_refused(self):+ """A completion that would be sliced at the wrong offset trains the+ wrong tokens; refuse instead of warning as TRL does."""+ from soup_cli.trainer.mlx_dpo import PreferenceRowError++ class Unstable(FakeTokenizer):+ def apply_chat_template(self, messages, add_generation_prompt=False, **kw):+ ids = super().apply_chat_template(messages, add_generation_prompt, **kw)+ if not add_generation_prompt:+ ids = [ids[0], 999] + ids[1:]+ return ids++ from soup_cli.trainer.mlx_dpo import build_preference_example++ row = {+ "prompt": [{"role": "user", "content": "hi"}],+ "chosen": [{"role": "assistant", "content": "a"}],+ "rejected": [{"role": "assistant", "content": "b"}],+ }+ with pytest.raises(PreferenceRowError, match="prefix"):+ build_preference_example(+ row, Unstable(), max_length=64, max_prompt_length=32+ )++ def test_prompt_capped_keep_start(self):+ ex = self._build(+ {"prompt": "abcdefgh", "chosen": "x", "rejected": "y"},+ max_length=100,+ max_prompt_length=4,+ )+ assert ex.prompt_ids == [BOS, ord("a"), ord("b"), ord("c")]++ def test_prompt_capped_keep_end(self):+ ex = self._build(+ {"prompt": "abcdefgh", "chosen": "x", "rejected": "y"},+ max_length=100,+ max_prompt_length=3,+ mode="keep_end",+ )+ assert _decode(ex.prompt_ids) == "fgh"++ def test_completion_capped_to_remaining_length(self):+ ex = self._build(+ {"prompt": "ab", "chosen": "0123456789", "rejected": "xy"},+ max_length=6,+ max_prompt_length=3,+ )+ assert len(ex.prompt_ids) == 3+ assert _decode(ex.chosen_ids) == "012"+ assert _decode(ex.rejected_ids) == "xy\x03"++ def test_null_field_refused(self):+ from soup_cli.trainer.mlx_dpo import PreferenceRowError++ with pytest.raises(PreferenceRowError, match="rejected"):+ self._build({"prompt": "a", "chosen": "b", "rejected": None})+++# --------------------------------------------------------------------------+# Batching+# --------------------------------------------------------------------------+++def _example(p, c, r):+ from soup_cli.trainer.mlx_dpo import PreferenceExample++ return PreferenceExample(prompt_ids=p, chosen_ids=c, rejected_ids=r)+++class TestBatchPlan:+ def test_plan_is_reproducible_for_a_seed(self):+ from soup_cli.trainer.mlx_dpo import plan_batches++ a = plan_batches(10, batch_size=2, epochs=3, seed=42)+ b = plan_batches(10, batch_size=2, epochs=3, seed=42)+ assert a == b++ def test_different_seeds_shuffle_differently(self):+ from soup_cli.trainer.mlx_dpo import plan_batches++ assert plan_batches(50, 2, 1, seed=1) != plan_batches(50, 2, 1, seed=2)++ def test_each_epoch_covers_every_full_batch_once(self):+ from soup_cli.trainer.mlx_dpo import plan_batches++ plan = plan_batches(9, batch_size=2, epochs=2, seed=0)+ assert len(plan) == 8 # 4 full batches per epoch, the odd row dropped+ first_epoch = sorted(i for batch in plan[:4] for i in batch)+ assert len(set(first_epoch)) == 8++ def test_fewer_rows_than_batch_size_refused(self):+ from soup_cli.trainer.mlx_dpo import plan_batches++ with pytest.raises(ValueError, match="batch_size"):+ plan_batches(1, batch_size=2, epochs=1, seed=0)+++class TestCollate:+ def test_chosen_then_rejected_with_completion_mask(self):+ from soup_cli.trainer.mlx_dpo import collate_pairs++ tokens, mask = collate_pairs(+ [_example([1, 2], [5, 6, 7], [8]), _example([1], [9], [4, 4])]+ )+ assert tokens == [+ [1, 2, 5, 6, 7],+ [1, 9, 0, 0, 0],+ [1, 2, 8, 0, 0],+ [1, 4, 4, 0, 0],+ ]+ assert mask == [+ [0, 0, 1, 1, 1],+ [0, 1, 0, 0, 0],+ [0, 0, 1, 0, 0],+ [0, 1, 1, 0, 0],+ ]+++# --------------------------------------------------------------------------+# Loss + log-probs (need mlx)+# --------------------------------------------------------------------------+++def _sigmoid(x):+ return 1.0 / (1.0 + math.exp(-x))+++class TestDpoLoss:+ def test_matches_closed_form(self):+ mx = pytest.importorskip("mlx.core")+ from soup_cli.trainer.mlx_dpo import dpo_loss++ pc, pr = mx.array([-1.0, -2.0]), mx.array([-3.0, -1.0])+ rc, rr = mx.array([-1.5, -2.0]), mx.array([-2.5, -1.5])+ beta = 0.1+ loss, metrics = dpo_loss(pc, pr, rc, rr, beta)++ expected = []+ for i in range(2):+ z = beta * ((pc[i] - rc[i]).item() - (pr[i] - rr[i]).item())+ expected.append(-math.log(_sigmoid(z)))+ assert loss.item() == pytest.approx(sum(expected) / 2, rel=1e-5)+ # chosen reward 0.05 vs rejected -0.05 for row 0; 0.0 vs 0.05 for row 1+ assert metrics["reward_accuracy"].item() == pytest.approx(0.5)+ assert metrics["reward_margin"].item() == pytest.approx(+ ((0.05 - -0.05) + (0.0 - 0.05)) / 2, rel=1e-5+ )++ def test_equal_policy_and_reference_is_log2(self):+ mx = pytest.importorskip("mlx.core")+ from soup_cli.trainer.mlx_dpo import dpo_loss++ x = mx.array([-4.0, -7.0, -1.0])+ loss, _ = dpo_loss(x, x, x, x, 0.5)+ assert loss.item() == pytest.approx(math.log(2), rel=1e-6)++ def test_stable_for_large_margins(self):+ mx = pytest.importorskip("mlx.core")+ from soup_cli.trainer.mlx_dpo import dpo_loss++ loss, _ = dpo_loss(+ mx.array([0.0]), mx.array([-1e5]), mx.array([0.0]), mx.array([0.0]), 1.0+ )+ assert math.isfinite(loss.item()) and loss.item() == pytest.approx(0.0, abs=1e-6)+ loss, _ = dpo_loss(+ mx.array([-1e5]), mx.array([0.0]), mx.array([0.0]), mx.array([0.0]), 1.0+ )+ assert loss.item() == pytest.approx(1e5, rel=1e-4)+++class TestSequenceLogps:+ def test_sums_only_masked_target_tokens(self):+ mx = pytest.importorskip("mlx.core")+ nn = pytest.importorskip("mlx.nn")+ from soup_cli.trainer.mlx_dpo import sequence_logps++ vocab = 5++ class Uniform(nn.Module):+ def __call__(self, x):+ return mx.zeros((*x.shape, vocab))++ tokens = mx.array([[1, 2, 3, 4], [1, 2, 0, 0]])+ mask = mx.array([[0, 0, 1, 1], [0, 1, 0, 0]])+ out = sequence_logps(Uniform(), tokens, mask)+ # Uniform logits: every target token has log-prob -log(5).+ assert out.tolist() == pytest.approx([-2 * math.log(vocab), -math.log(vocab)])+++class TestChunkedLogps:+ """The memory path: backbone once, then the vocab head in checkpointed+ chunks starting at the first completion token. It must equal the plain+ full-model path, value and gradient."""++ def _batch(self):+ mx = pytest.importorskip("mlx.core")+ tokens = mx.array([[5, 6, 7, 8, 9, 10, 11], [5, 6, 12, 13, 0, 0, 0]])+ mask = mx.array([[0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 0]])+ return tokens, mask++ @pytest.mark.parametrize("tied", [True, False])+ def test_matches_full_model(self, tied):+ pytest.importorskip("mlx.core")+ from soup_cli.trainer.mlx_dpo import resolve_head_split, sequence_logps++ model = _tiny_llama(tie=tied)+ model.freeze()+ tokens, mask = self._batch()+ split = resolve_head_split(model)+ assert split is not None+ full = sequence_logps(model, tokens, mask)+ chunked = sequence_logps(model, tokens, mask, head_split=split, chunk_size=2)+ assert chunked.tolist() == pytest.approx(full.tolist(), rel=1e-5, abs=1e-5)++ def test_gradients_match_full_model(self):+ mx = pytest.importorskip("mlx.core")+ nn = pytest.importorskip("mlx.nn")+ from mlx.utils import tree_flatten++ from soup_cli.trainer.mlx_dpo import resolve_head_split, sequence_logps++ model = _tiny_llama()+ # As in LoRA training: the vocab head (here the tied embedding) is+ # frozen, everything inside the backbone layers trains.+ model.freeze()+ model.model.layers[0].unfreeze()+ tokens, mask = self._batch()+ split = resolve_head_split(model)+ assert split is not None++ def loss(m, **kw):+ return sequence_logps(m, tokens, mask, **kw).sum()++ _, g_full = nn.value_and_grad(model, loss)(model)+ _, g_chunk = nn.value_and_grad(+ model, lambda m: loss(m, head_split=split, chunk_size=3)+ )(model)+ for (name, a), (_, b) in zip(tree_flatten(g_full), tree_flatten(g_chunk)):+ assert mx.allclose(a, b, rtol=1e-4, atol=1e-5).item(), name++ @pytest.mark.parametrize("tied", [True, False])+ def test_trainable_head_has_no_split(self, tied):+ """The checkpointed head sees its weights as constants, so a head that+ trains would lose its gradient: refuse the split, use the full path."""+ pytest.importorskip("mlx.core")+ from soup_cli.trainer.mlx_dpo import resolve_head_split++ model = _tiny_llama(tie=tied) # nothing frozen+ assert resolve_head_split(model) is None++ def test_unknown_architecture_has_no_split(self):+ nn = pytest.importorskip("mlx.nn")+ from soup_cli.trainer.mlx_dpo import resolve_head_split++ class Opaque(nn.Module):+ def __call__(self, x):+ return x++ assert resolve_head_split(Opaque()) is None+++# --------------------------------------------------------------------------+# Config gate+# --------------------------------------------------------------------------++_MLX_DPO_YAML = """+base: mlx-community/Qwen2.5-0.5B-Instruct-4bit+task: dpo+backend: mlx+data:+ train: ./x.jsonl+ format: dpo+training:+ epochs: 1+ lr: 1e-6+output: ./output+"""+++class TestConfig:+ def test_mlx_dpo_config_loads(self):+ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(_MLX_DPO_YAML)+ assert cfg.task == "dpo" and cfg.backend == "mlx"++ def test_add_new_tokens_refused_on_mlx_dpo(self):+ """The vocab-expansion validator used to wave every non-SFT MLX task+ through, trusting the task gate to refuse it. DPO passes that gate now,+ so the field must be refused for MLX's own reason, not dropped."""+ from soup_cli.config.loader import load_config_from_string++ yaml_str = _MLX_DPO_YAML.replace(+ " format: dpo\n", " format: dpo\n add_new_tokens: ['<x>']\n"+ )+ with pytest.raises(Exception, match="not applied on backend='mlx'"):+ load_config_from_string(yaml_str)++ def test_doctor_reports_mlx_dpo_gaps_but_not_the_seed(self):+ """`soup doctor --config` reads backend_support; the seed is honoured+ on MLX DPO, so only the genuinely ignored setting is reported."""+ from soup_cli.config.backend_support import check_config+ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(+ _MLX_DPO_YAML.replace(" lr: 1e-6\n", " lr: 1e-6\n seed: 3\n use_galore: true\n")+ )+ fields = {entry.field for entry in check_config(cfg)}+ assert fields == {"training.use_galore"}++ @pytest.mark.parametrize("task", ["ipo", "kto", "orpo", "simpo", "ppo"])+ def test_other_preference_tasks_still_refused(self, task):+ from soup_cli.config.loader import load_config_from_string++ yaml_str = _MLX_DPO_YAML.replace("task: dpo", f"task: {task}")+ with pytest.raises(Exception, match="MLX backend"):+ load_config_from_string(yaml_str)+++# --------------------------------------------------------------------------+# End-to-end on a tiny random model (needs mlx + mlx_lm)+# --------------------------------------------------------------------------+++def _tiny_llama(tie: bool = True):+ pytest.importorskip("mlx.core")+ pytest.importorskip("mlx_lm")+ from mlx_lm.models import llama++ args = llama.ModelArgs(+ model_type="llama",+ hidden_size=32,+ num_hidden_layers=2,+ intermediate_size=64,+ num_attention_heads=4,+ num_key_value_heads=2,+ rms_norm_eps=1e-5,+ vocab_size=200,+ tie_word_embeddings=tie,+ )+ return llama.Model(args)+++def _wrapper(tmp_path, monkeypatch, **training):+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.mlx_dpo import MLXDPOTrainerWrapper++ tmp_path.mkdir(parents=True, exist_ok=True)+ monkeypatch.chdir(tmp_path)+ extra = "".join(f" {k}: {v}\n" for k, v in training.items())+ cfg = load_config_from_string(+ _MLX_DPO_YAML.replace(" lr: 1e-6\n", " lr: 5e-3\n" + extra)+ )+ wrapper = MLXDPOTrainerWrapper(cfg)+ wrapper.model = _tiny_llama()+ wrapper.tokenizer = FakeTokenizer()+ rows = [+ {"prompt": f"q{i}:", "chosen": " good", "rejected": " bad"} for i in range(8)+ ]+ wrapper._dataset = {"train": rows, "val": rows[:2]}+ return wrapper+++class TestTrainLoop:+ def test_tied_pairs_are_skipped_with_one_warning(self, tmp_path, monkeypatch, capsys):+ """UltraFeedback-style ties carry zero DPO gradient: skip, do not abort."""+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2, seed=1)+ tie = {"prompt": "q:", "chosen": " same", "rejected": " same"}+ wrapper._dataset["train"] = wrapper._dataset["train"] + [tie, dict(tie)]+ result = wrapper.train()+ assert result["skipped_identical_pairs"] == 2+ out = _strip_ansi(capsys.readouterr().out)+ assert "skipped 2 dpo row(s) with identical chosen and rejected" in out++ def test_preference_is_learned_and_artifacts_written(self, tmp_path, monkeypatch):+ wrapper = _wrapper(+ tmp_path,+ monkeypatch,+ epochs=4,+ batch_size=2,+ gradient_accumulation_steps=1,+ warmup_ratio=0.0,+ seed=7,+ )+ result = wrapper.train()++ assert result["total_steps"] == 16+ assert result["final_loss"] < math.log(2) # learned to prefer "good"+ assert result["val_reward_accuracy"] == pytest.approx(1.0)+ out = tmp_path / "output"+ assert (out / "adapters.safetensors").exists()+ meta = json.loads((out / "adapter_config.json").read_text())+ assert meta["fine_tune_type"] == "lora"+ assert meta["task"] == "dpo"+ assert meta["dpo_beta"] == pytest.approx(0.1)+ assert meta["seed"] == 7+ assert "lora_parameters" in meta++ def test_same_seed_reproduces_losses(self, tmp_path, monkeypatch):+ first = _wrapper(tmp_path / "a", monkeypatch, seed=3, batch_size=2)+ losses_a = first.train()["losses"]+ second = _wrapper(tmp_path / "b", monkeypatch, seed=3, batch_size=2)+ losses_b = second.train()["losses"]+ assert losses_a == pytest.approx(losses_b, rel=1e-5)++ def test_reference_logps_are_the_untrained_policy(self, tmp_path, monkeypatch):+ """LoRA B starts at zero, so the reference precomputed before the first+ update equals the base model; the first-step loss is exactly log 2."""+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2, seed=0)+ result = wrapper.train()+ assert result["losses"][0] == pytest.approx(math.log(2), rel=1e-4)+++# --------------------------------------------------------------------------+# Review of #1846: the preference-row contract is the loader's (#1866)+# --------------------------------------------------------------------------++_U = {"role": "user", "content": "hi"}+_A = {"role": "assistant", "content": "a"}+_B = {"role": "assistant", "content": "b"}+++def _build_row(row, tokenizer=None, max_length=1024, max_prompt_length=512):+ from soup_cli.trainer.mlx_dpo import build_preference_example++ return build_preference_example(+ row, tokenizer or FakeTokenizer(),+ max_length=max_length, max_prompt_length=max_prompt_length,+ )+++class TestTheLoaderLayoutsAreAccepted:+ @pytest.mark.parametrize("name", ["dpo_sample.jsonl", "chat_preferences.jsonl"])+ def test_every_bundled_preference_row_tokenizes(self, name):+ """Through the real loader converter, as `load_dataset` hands rows over."""+ from pathlib import Path++ from soup_cli.data.formats import format_to_messages++ path = Path(__file__).resolve().parents[1] / "examples" / "data" / name+ raws = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()+ if line.strip()]+ assert raws+ for raw in raws:+ row = format_to_messages(raw, "dpo")+ assert row is not None+ ex = _build_row(row, max_length=4096, max_prompt_length=2048)+ user = raw["chosen"][0]["content"]+ assert _decode(ex.prompt_ids) == f"<user>{user}\x03<assistant>"+ assert _decode(ex.chosen_ids) == raw["chosen"][-1]["content"] + "\x03"+ assert _decode(ex.rejected_ids) == raw["rejected"][-1]["content"] + "\x03"++ def test_message_list_prompt_with_string_answers(self):+ """Review item 1: each string answer is one assistant turn."""+ ex = _build_row({"prompt": [_U], "chosen": "a", "rejected": "b"})+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+ assert _decode(ex.chosen_ids) == "a\x03"+ assert _decode(ex.rejected_ids) == "b\x03"++ def test_one_message_object_is_read_as_a_list_of_one(self):+ """Review item 2: a dict prompt is a message, never `str(dict)`."""+ ex = _build_row({"prompt": _U, "chosen": [_A], "rejected": [_B]})+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+ assert "role" not in _decode(ex.prompt_ids)++ @pytest.mark.parametrize("prompt", [7, True, 1.5])+ def test_a_non_text_prompt_is_refused_by_name(self, prompt):+ from soup_cli.trainer.mlx_dpo import PreferenceRowError++ with pytest.raises(PreferenceRowError, match="dpo.prompt"):+ _build_row({"prompt": prompt, "chosen": [_A], "rejected": [_B]})++ def test_a_conversation_that_continues_past_the_other(self):+ """Review item 3: the shorter side's last assistant turn is its answer."""+ u2 = {"role": "user", "content": "more"}+ ex = _build_row({"prompt": "hi", "chosen": [_U, _A], "rejected": [_U, _A, u2, _B]})+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+ assert _decode(ex.chosen_ids) == "a\x03"+ assert _decode(ex.rejected_ids).startswith("a\x03<user>more")++ def test_a_side_with_no_answer_is_a_data_error_not_a_tokenizer_one(self):+ from soup_cli.trainer.mlx_dpo import PreferenceRowError, PrefixUnstableError++ with pytest.raises(PreferenceRowError, match="no chosen answer") as excinfo:+ _build_row({"prompt": "hi", "chosen": [_U], "rejected": [_U, _B]})+ assert not isinstance(excinfo.value, PrefixUnstableError)++ def test_no_prompt_uses_the_shared_turns(self):+ """Review item 4: rows handed straight to setup() read like the loader's."""+ ex = _build_row({"chosen": [_U, _A], "rejected": [_U, _B]})+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"++ def test_messages_column_is_the_prompt(self):+ ex = _build_row({"messages": [_U], "chosen": [_A], "rejected": [_B]})+ assert _decode(ex.prompt_ids) == "<user>hi\x03<assistant>"+++class _Unstable(FakeTokenizer):+ def apply_chat_template(self, messages, add_generation_prompt=False, **kw):+ ids = super().apply_chat_template(messages, add_generation_prompt, **kw)+ if not add_generation_prompt and messages[0]["content"] == "bad":+ ids = [ids[0], 999] + ids[1:]+ return ids+++def _bare_wrapper(**training):+ """A wrapper with a tokenizer and no model: enough for `_examples`."""+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.mlx_dpo import MLXDPOTrainerWrapper++ extra = "".join(f" {k}: {v}\n" for k, v in training.items())+ yaml_str = _MLX_DPO_YAML.replace(" lr: 1e-6\n", " lr: 1e-6\n" + extra)+ return MLXDPOTrainerWrapper(load_config_from_string(yaml_str))+++class TestRowsTheTemplateCannotSlice:+ def test_skipped_with_a_count_and_the_first_offender(self, capsys):+ wrapper = _bare_wrapper()+ wrapper.tokenizer = _Unstable()+ bad = {"prompt": [{"role": "user", "content": "bad"}], "chosen": [_A], "rejected": [_B]}+ good = {"prompt": [_U], "chosen": [_A], "rejected": [_B]}+ examples, ties = wrapper._examples([good, bad, good, bad])+ assert (len(examples), ties) == (2, 0)+ out = _strip_ansi(capsys.readouterr().out)+ assert "skipped 2 train row(s)" in out and "first: row 1" in out++ def test_a_malformed_row_still_stops_with_its_index(self):+ from soup_cli.trainer.mlx_dpo import PreferenceRowError++ wrapper = _bare_wrapper()+ wrapper.tokenizer = FakeTokenizer()+ good = {"prompt": "q", "chosen": "a", "rejected": "b"}+ with pytest.raises(PreferenceRowError, match="dpo train row 1"):+ wrapper._examples([good, {"prompt": "q", "chosen": "a", "rejected": [_B]}])+++class TestPromptCapIsWired:+ def test_examples_cap_the_prompt_at_half_max_length(self):+ wrapper = _bare_wrapper()+ wrapper.config.data.max_length = 40+ wrapper.tokenizer = FakeTokenizer()+ long_prompt = "x" * 100+ (example,), _ = wrapper._examples([{"prompt": long_prompt, "chosen": "a", "rejected": "b"}])+ assert len(example.prompt_ids) == 20+ assert len(example.prompt_ids) + len(example.chosen_ids) <= 40+++class TestConfigRefusals:+ def _load(self, extra_top="", extra_training=""):+ from soup_cli.config.loader import load_config_from_string++ yaml_str = _MLX_DPO_YAML.replace("backend: mlx\n", "backend: mlx\n" + extra_top)+ yaml_str = yaml_str.replace(" lr: 1e-6\n", " lr: 1e-6\n" + extra_training)+ return load_config_from_string(yaml_str)++ def test_lora_rank_zero_is_refused(self):+ with pytest.raises(Exception, match="lora.r must be at least 1"):+ self._load(extra_training=" lora: {r: 0}\n")++ @pytest.mark.parametrize("modality", ["vision", "audio"])+ def test_non_text_modality_is_refused(self, modality):+ with pytest.raises(Exception, match=f"modality='{modality}'"):+ self._load(extra_top=f"modality: {modality}\n")++ def test_loraplus_is_still_refused_on_mlx_dpo(self):+ with pytest.raises(Exception, match="loraplus_lr_ratio"):+ self._load(extra_training=" loraplus_lr_ratio: 16\n")++ def test_the_ignored_settings_are_printed(self, monkeypatch):+ from io import StringIO++ from rich.console import Console++ from soup_cli.trainer import mlx_dpo++ buffer = StringIO()+ monkeypatch.setattr(mlx_dpo, "console", Console(file=buffer, width=400))+ cfg = self._load(extra_training=" use_galore: true\n")+ mlx_dpo.MLXDPOTrainerWrapper(cfg)._check_unsupported()+ assert "MLX backend ignores: GaLore" in _strip_ansi(buffer.getvalue())+++# --------------------------------------------------------------------------+# sequence_logps scores the NEXT token+# --------------------------------------------------------------------------+++class _Oracle:+ """Logits that put all mass on ``tokens[t + 1]`` at position ``t``+ (``shift=1``) or on ``tokens[t]`` (``shift=0``: copies its input)."""++ def __new__(cls, tokens, vocab, shift):+ nn = pytest.importorskip("mlx.nn")+ mx = pytest.importorskip("mlx.core")++ class Backbone(nn.Module):+ def __call__(self, x):+ width = x.shape[1]+ targets = tokens[:, shift : shift + width]+ return mx.eye(vocab)[targets]++ class Model(nn.Module):+ def __init__(self):+ super().__init__()+ self.model = Backbone()+ self.lm_head = nn.Linear(vocab, vocab, bias=False)+ self.lm_head.weight = mx.eye(vocab) * 50.0+ self.args = type("Args", (), {"tie_word_embeddings": False})()++ def __call__(self, x):+ return self.lm_head(self.model(x))++ model = Model()+ model.freeze()+ return model+++class TestTargetAlignment:+ @pytest.mark.parametrize("chunked", [False, True])+ def test_the_real_continuation_scores_near_zero(self, chunked):+ mx = pytest.importorskip("mlx.core")+ from soup_cli.trainer.mlx_dpo import resolve_head_split, sequence_logps++ tokens = mx.array([[1, 5, 9, 3, 7, 2]])+ mask = mx.array([[0, 0, 1, 1, 1, 1]])+ right = _Oracle(tokens, 16, shift=1)+ copier = _Oracle(tokens, 16, shift=0)+ kw = {}+ if chunked:+ assert resolve_head_split(right) is not None+ kw = {"head_split": resolve_head_split(right), "chunk_size": 2}+ assert sequence_logps(right, tokens, mask, **kw).item() == pytest.approx(0.0, abs=1e-3)+ kw_copy = {"head_split": resolve_head_split(copier), "chunk_size": 2} if chunked else {}+ assert sequence_logps(copier, tokens, mask, **kw_copy).item() < -100+++# --------------------------------------------------------------------------+# Train-loop guarantees the docs state+# --------------------------------------------------------------------------+++def _seeded_wrapper(tmp_path, monkeypatch, model_seed=0, **training):+ mx = pytest.importorskip("mlx.core")+ wrapper = _wrapper(tmp_path, monkeypatch, **training)+ mx.random.seed(model_seed)+ wrapper.model = _tiny_llama()+ return wrapper+++class TestResume:+ def test_reference_is_taken_before_the_checkpoint_loads(self, tmp_path, monkeypatch):+ from soup_cli.trainer import mlx_dpo++ first = _seeded_wrapper(tmp_path / "a", monkeypatch, batch_size=2, epochs=3, seed=1)+ first.train()+ checkpoint = tmp_path / "a" / "output" / "adapters.safetensors"+ assert checkpoint.exists()++ order = []+ real_ref = mlx_dpo.MLXDPOTrainerWrapper._reference_logps+ real_load = mlx_dpo.MLXDPOTrainerWrapper._load_checkpoint_weights+ monkeypatch.setattr(mlx_dpo.MLXDPOTrainerWrapper, "_reference_logps",+ lambda self, *a: order.append("reference") or real_ref(self, *a))+ monkeypatch.setattr(mlx_dpo.MLXDPOTrainerWrapper, "_load_checkpoint_weights",+ lambda self, *a: order.append("load") or real_load(self, *a))+ resumed = _seeded_wrapper(tmp_path / "b", monkeypatch, batch_size=2, seed=1)+ result = resumed.train(resume_from_checkpoint=str(checkpoint))++ assert order[-1] == "load" and "reference" in order[:-1]+ # The policy starts trained, the reference is the base model, so the+ # first loss is already below log 2 (it is exactly log 2 from scratch).+ assert result["losses"][0] < math.log(2) - 1e-3+++class TestGradientAccumulation:+ def test_two_micro_batches_of_one_equal_one_batch_of_two(self, tmp_path, monkeypatch):+ mx = pytest.importorskip("mlx.core")+ from mlx.utils import tree_flatten++ from soup_cli.trainer import mlx_dpo++ def run(path, batch_size, accum, plan):+ monkeypatch.setattr(mlx_dpo, "plan_batches", lambda *a, **k: [list(b) for b in plan])+ wrapper = _seeded_wrapper(+ path, monkeypatch, batch_size=batch_size, gradient_accumulation_steps=accum,+ optimizer="sgd", warmup_ratio=0.0, scheduler="constant", seed=4,+ )+ wrapper.config.training.lora.dropout = 0.0+ result = wrapper.train()+ return result, dict(tree_flatten(wrapper.model.trainable_parameters()))++ one, w_one = run(tmp_path / "a", 2, 1, [[0, 1]])+ two, w_two = run(tmp_path / "b", 1, 2, [[0], [1]])+ assert len(one["losses"]) == len(two["losses"]) == 1+ for name in w_one:+ assert mx.allclose(w_one[name], w_two[name], atol=1e-6).item(), name++ def test_updates_are_counted_per_accumulation_group(self, tmp_path, monkeypatch):+ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=2,+ gradient_accumulation_steps=2, seed=1)+ result = wrapper.train()+ assert result["total_steps"] == 4 # 8 rows / batch 2, one epoch+ assert len(result["losses"]) == 2 # one loss per optimizer update+++class TestDataSeed:+ def test_data_seed_owns_the_batch_order(self, tmp_path, monkeypatch):+ from soup_cli.trainer import mlx_dpo++ plans = []+ real = mlx_dpo.plan_batches++ def recording(*args, **kwargs):+ plan = real(*args, **kwargs)+ plans.append(plan)+ return plan++ monkeypatch.setattr(mlx_dpo, "plan_batches", recording)+ for path, training in (("a", {"seed": 1, "data_seed": 2}),+ ("b", {"seed": 3, "data_seed": 2}),+ ("c", {"seed": 3})):+ _seeded_wrapper(tmp_path / path, monkeypatch, batch_size=2, epochs=2,+ **training).train()+ assert plans[0] == plans[1]+ assert plans[1] != plans[2]+++class TestValidation:+ def test_one_val_row_with_batch_two_is_evaluated(self, tmp_path, monkeypatch):+ """The #1851 shape: a partial last chunk, not a crash."""+ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=2, seed=1)+ wrapper._dataset["val"] = wrapper._dataset["val"][:1]+ result = wrapper.train()+ assert "val_loss" in result and math.isfinite(result["val_loss"])++ def test_val_loss_is_the_mean_over_rows_not_over_chunks(self, tmp_path, monkeypatch):+ pytest.importorskip("mlx.core")+ from soup_cli.trainer import mlx_dpo++ refs = []+ real = mlx_dpo.MLXDPOTrainerWrapper._reference_logps+ monkeypatch.setattr(mlx_dpo.MLXDPOTrainerWrapper, "_reference_logps",+ lambda self, ex, bs: refs.append(real(self, ex, bs)) or refs[-1])+ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=2, epochs=3, seed=2)+ # Three rows, one reversed: chunks of 2 + 1 with different losses.+ wrapper._dataset["val"] = [+ {"prompt": "v0:", "chosen": " good", "rejected": " bad"},+ {"prompt": "v1:", "chosen": " good", "rejected": " bad"},+ {"prompt": "v2:", "chosen": " bad", "rejected": " good"},+ ]+ result = wrapper.train()++ examples, _ = wrapper._examples(wrapper._dataset["val"], "val")+ ref_c, ref_r = refs[1]+ wrapper.model.eval()+ per_row = []+ for i, example in enumerate(examples):+ tokens, mask = wrapper._to_arrays([example])+ lp = mlx_dpo.sequence_logps(wrapper.model, tokens, mask, head_split=wrapper._head_split)+ loss, _ = mlx_dpo.dpo_loss(lp[:1], lp[1:], ref_c[i : i + 1], ref_r[i : i + 1], 0.1)+ per_row.append(loss.item())+ assert result["val_loss"] == pytest.approx(sum(per_row) / 3, rel=1e-4)+++class TestCheckpoints:+ def test_save_steps_files_are_found_by_resume_auto(self, tmp_path, monkeypatch):+ from soup_cli.commands.train import _resolve_mlx_checkpoint++ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=2, epochs=2,+ save_steps=2, seed=1)+ wrapper.train()+ out = tmp_path / "output"+ numbered = sorted(p.name for p in out.glob("*_adapters.safetensors"))+ assert numbered == [f"{n:07d}_adapters.safetensors" for n in (2, 4, 6, 8)]+ resolved = _resolve_mlx_checkpoint("auto", str(out))+ assert resolved is not None and resolved.endswith("0000008_adapters.safetensors")+++class TestHeadSplitFallback:+ def test_a_mismatching_head_falls_back_with_a_warning(self, tmp_path, monkeypatch):+ from io import StringIO++ from rich.console import Console++ from soup_cli.trainer import mlx_dpo++ real = mlx_dpo.resolve_head_split++ def scaled(model):+ split = real(model)+ backbone, head = split+ return backbone, (lambda h: head(h) * 2.0)++ monkeypatch.setattr(mlx_dpo, "resolve_head_split", scaled)+ buffer = StringIO()+ monkeypatch.setattr(mlx_dpo, "console", Console(file=buffer, width=400))+ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=2, seed=1)+ result = wrapper.train()+ assert wrapper._head_split is None+ assert "using the full-vocabulary path" in _strip_ansi(buffer.getvalue())+ assert result["losses"][0] == pytest.approx(math.log(2), rel=1e-4)+++class TestRefusalsAndReporting:+ def test_too_few_pairs_after_ties_names_batch_size_and_ties(self, tmp_path, monkeypatch):+ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=4, seed=1)+ tie = {"prompt": "q:", "chosen": " same", "rejected": " same"}+ wrapper._dataset["train"] = wrapper._dataset["train"][:3] + [tie, dict(tie)]+ with pytest.raises(ValueError, match=r"3 training pair.*batch_size \(4\).*2 tie"):+ wrapper.train()++ def test_metrics_reach_the_live_stream_with_a_display(self, tmp_path, monkeypatch):+ from soup_cli.utils import train_event_buffer++ events = []+ monkeypatch.setattr(train_event_buffer, "push_train_event", events.append)++ class Display:+ def start(self, total):+ pass++ def update(self, **kw):+ pass++ def stop(self):+ pass++ wrapper = _seeded_wrapper(tmp_path, monkeypatch, batch_size=2, seed=1)+ wrapper.train(display=Display())+ assert events and all(e.type == "metric" and e.loss is not None for e in events)+ assert any(e.val_loss is not None for e in events)diff --git a/tests/test_trl_preference_config_contract.py b/tests/test_trl_preference_config_contract.pyindex 5a8ea280..7881574d 100644--- a/tests/test_trl_preference_config_contract.py+++ b/tests/test_trl_preference_config_contract.py@@ -264,6 +264,9 @@ class TestTheCanaryCoversWhatItClaims:for path in trainer_dir.glob("*.py")if any(marker in path.read_text(encoding="utf-8") for marker in markers)and path.stem != "_trl_compat" # the helper defines it, does not pass it+ # Builds no trl config: its `max_prompt_length=` goes to its own+ # tokenizer (tests/test_mlx_dpo.py pins the cap).+ and path.stem != "mlx_dpo"}assert users, "found no trainer passing a prompt-length cap — did the path move?"uncovered = sorted(users - set(_ALL_SIX))