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.

feat(mlx): native ORPO on Apple Silicon (#2004) (#2073)

dryn85-maxa7988edf4684
diff --git a/changelog.d/0.76.0/2073.added.md b/changelog.d/0.76.0/2073.added.md
new file mode 100644
index 00000000..b68b01b4
--- /dev/null
+++ b/changelog.d/0.76.0/2073.added.md
@@ -0,0 +1,12 @@
+- **ORPO runs natively on Apple Silicon: `task: orpo` with `backend: mlx` (#2004 by @dryn85-max
+ in #2073).** It was refused at config load. Soup's own MLX loop now trains TRL 0.29.1's ORPO
+ objective with `training.orpo_beta`: the stable odds-ratio term on mean completion
+ log-probabilities, plus the chosen-sequence NLL over prompt and answer. No reference model is
+ needed. Rows are tokenized the way TRL's ORPO trainer does, so rows that fit in `max_length`
+ train on the same tokens on either backend; over-long rows are cut with Soup's usual cap, and
+ ties train as they do in TRL. The adapter loads with `mlx_lm.load`. `--resume` refuses a
+ checkpoint from another task or base. A nonfinite loss stops the run. `quantization: 8bit`,
+ `lora.r: 0` and non-text modalities are refused on MLX, and `task: preference` stays refused
+ there. Measured once on an M4 Pro: one epoch on 600 UltraFeedback pairs took about four minutes
+ with Qwen2.5-0.5B-Instruct. Try: `soup train --config soup.yaml` with `task: orpo`,
+ `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.md
index e6e24fe2..57d2861c 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -125,7 +125,7 @@ training:
alpha: 32
```
-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.
+MLX backend supports SFT, DPO and ORPO. Any other task with `backend: mlx` (`grpo`, `ipo`, `kto`, `simpo`, `preference`, ...) 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
@@ -156,12 +156,78 @@ training:
- **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.
+- **LoRA dropout applies.** `lora.dropout` (default 0.05) is active during training, as in MLX SFT; TRL's `disable_dropout` (on by default in 0.29.1) turns it off on the transformers backend. Set `lora.dropout: 0` to match it.
- **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.
+#### ORPO on MLX
+
+`task: orpo` with `backend: mlx` runs the same loop as MLX DPO with ORPO's
+objective, matched to TRL 0.29.1's ORPO trainer (the one the transformers
+backend runs): the mean log-probability of each completion, the stable
+odds-ratio term `log_odds = (a - b) - (log(1 - e^a) - log(1 - e^b))`, and
+`loss = chosen NLL - orpo_beta * mean(logsigmoid(log_odds))`, where the NLL is a
+token mean over the whole chosen sequence, prompt included. There is no
+reference model and nothing is precomputed. Qualified on
+Qwen2.5-0.5B-Instruct in bf16 and 4-bit on an M4 Pro.
+
+```yaml
+base: mlx-community/Qwen2.5-0.5B-Instruct-4bit
+task: orpo
+backend: mlx
+
+data:
+ train: ./prefs.jsonl
+ format: dpo
+ max_length: 1024
+
+training:
+ lr: 5e-5
+ orpo_beta: 0.1
+ batch_size: 2
+ gradient_accumulation_steps: 4
+ gradient_checkpointing: true
+ quantization: 4bit
+ lora:
+ r: 16
+ alpha: 32
+```
+
+- **Tokens.** Rows are read by the `format: dpo` converter and tokenized as
+ TRL's ORPO trainer does: rendered to text with the chat template (keeping
+ only the prefix the prompt and `prompt + answer` renderings share), the
+ answer located even when the tokenizer merges the last prompt token into it,
+ BOS prepended and EOS appended when missing. Over-long rows are cut as on the
+ transformers backend (prompt to `max_length // 2`, keeping its end, answers to
+ the remaining room); TRL's own earlier answer cut, which can leave the shorter
+ answer empty, is not reproduced. A pair the template cannot split is skipped
+ with a count; a row with no room for an answer is refused.
+- **Ties train.** A pair whose `chosen` equals its `rejected` is kept, as in
+ TRL: its odds-ratio term is the constant `log 2` and the NLL still learns.
+- **Stops on a nonfinite loss** instead of training on NaN. The check reads
+ the loss, not the gradient: a completion whose mean log-probability is
+ exactly 0 gives a finite loss and a NaN gradient, as in TRL.
+- **LoRA dropout applies**, as in MLX DPO above; set `lora.dropout: 0` to
+ match TRL's `disable_dropout`.
+- **Reported:** loss, NLL, log-odds ratio, mean log-odds, reward accuracy and
+ margin (`orpo_beta * logp`, as TRL logs them), per logged step and in the run
+ result (`val_*` for the validation split).
+- **Saved:** `adapters.safetensors` and `adapter_config.json` (with `task:
+ orpo`, `orpo_beta` and the base model), loadable with
+ `mlx_lm.load(base, adapter_path=output)`, both written atomically and the
+ metadata before the first step. A run that stops before its first save
+ leaves the new `adapter_config.json` beside the previous run's adapter
+ file. `--resume` refuses a checkpoint without that
+ metadata, from another task, or from another base, before any tensor loads.
+- **Refused at load:** `quantization: 8bit` (use `none`, or a pre-quantized
+ 4-bit base with `quantization: 4bit`), `training.lora.r: 0`, non-text
+ `modality`, LoRA+, and `task: preference` with `preference_loss: orpo` on
+ `backend: mlx` (use `task: orpo`). The other settings MLX DPO does not apply
+ are not applied here either.
+
#### DoRA on MLX
For text SFT, set `training.lora.use_dora: true` to use MLX-LM's native
@@ -223,7 +289,7 @@ what ran is recoverable from the output directory.
### Transformers on MPS
-The regular `backend: transformers` path can run more than MLX's SFT and DPO
+The regular `backend: transformers` path can run more than MLX's SFT, DPO and ORPO
surface. On a live MPS runtime that accepts bfloat16, Soup enables BF16 autocast
for the hardware-validated text trainers: SFT, DPO, GRPO/RLVR, reward modelling,
and PRM.
diff --git a/docs/models.md b/docs/models.md
index ed1db56f..99a87bc1 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 and DPO backend for local data; `[train]` is not required |
+| `mlx` | `pip install "soup-cli[mlx]"` | Standalone Apple Silicon SFT, DPO and ORPO 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/docs/training.md b/docs/training.md
index a829ff21..a22a4621 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1812,6 +1812,9 @@ training:
quantization: 4bit
```
+On Apple Silicon, `backend: mlx` runs ORPO natively with the same objective; see
+[ORPO on MLX](backends-and-ops.md#orpo-on-mlx).
+
## SimPO Training (Simple Preference)
diff --git a/src/soup_cli/config/backend_support.py b/src/soup_cli/config/backend_support.py
index 3f0e345f..77fbded2 100644
--- a/src/soup_cli/config/backend_support.py
+++ b/src/soup_cli/config/backend_support.py
@@ -19,9 +19,9 @@ drift -- every entry must name a real field, and every dotted field name in
the 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), ``task=dpo`` on ``backend=mlx``, plus multimodal
-vision and audio on ``backend=transformers`` (#1156). Other combinations report nothing rather
-than guessing, which is the honest default for a table that has not been
+both apply to every modality), ``task=dpo`` and ``task=orpo`` on ``backend=mlx``, plus
+multimodal vision and audio on ``backend=transformers`` (#1156). Other combinations report
+nothing rather than guessing, which is the honest default for a table that has not been
reviewed for them.
"""
@@ -241,11 +241,24 @@ _MLX_DPO: tuple[SupportEntry, ...] = tuple(
),
)
+#: MLX ORPO runs MLX DPO's loop with its own loss, so it ignores the same fields.
+_MLX_ORPO: tuple[SupportEntry, ...] = tuple(
+ entry for entry in _MLX_DPO if entry.field != "data.chat_template"
+) + (
+ SupportEntry(
+ "data.chat_template",
+ IGNORED,
+ "MLX ORPO 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,
+ ("orpo", "mlx", "text"): _MLX_ORPO,
("sft", "unsloth", "text"): _UNSLOTH_SFT,
("sft", "transformers", "vision"): _TRANSFORMERS_VISION_SFT,
("sft", "transformers", "audio"): _TRANSFORMERS_AUDIO_SFT,
@@ -282,6 +295,14 @@ TRAINER_MODULES: dict[tuple[str, str, str], tuple[str, ...]] = {
"soup_cli/trainer/_trl_compat.py",
"soup_cli/trainer/loss_summary.py",
),
+ ("orpo", "mlx", "text"): (
+ "soup_cli/trainer/mlx_orpo.py",
+ "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.py
index 15870593..f9870a06 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -4934,7 +4934,7 @@ UNSLOTH_SETUP_TASKS: frozenset[str] = frozenset({
#: 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"})
+MLX_TASKS: frozenset[str] = frozenset({"sft", "dpo", "orpo"})
#: #1497 — the tasks whose trainer reads ``training.freeze_layers`` /
#: ``training.freeze_ratio``: ``SFTTrainerWrapper._setup_transformers``, which
@@ -8266,36 +8266,51 @@ class SoupConfig(BaseModel):
@model_validator(mode="after")
def _validate_mlx_task_support(self) -> "SoupConfig":
- """MLX backend supports sft and dpo.
+ """MLX backend supports sft, dpo and orpo.
- 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.
+ SFT runs through mlx-lm's tuner; DPO and ORPO through Soup's own loop
+ in ``trainer/mlx_dpo.py`` / ``trainer/mlx_orpo.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 == "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.task in ("dpo", "orpo"):
+ # The native preference loops tokenize text and chat rows only and
+ # train a LoRA adapter. DPO's reference log-probs come from the
+ # policy before training, which is the base model only because a
+ # LoRA adapter's B starts at zero; ORPO trains LoRA only (no full
+ # fine-tune on MLX yet).
+ name = self.task.upper()
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. "
+ f"modality='{self.modality}' is not supported by task='{self.task}' "
+ f"on backend='mlx': MLX {name} trains on text and chat rows only. "
"Use backend=transformers, or modality: text."
)
if int(self.training.lora.r) < 1:
+ why = (
+ "the reference model is the untrained LoRA policy, which needs "
+ "a LoRA adapter to exist"
+ if self.task == "dpo"
+ else "MLX ORPO trains a LoRA adapter; full fine-tuning is not "
+ "implemented on backend='mlx'"
+ )
+ raise ValueError(
+ f"training.lora.r must be at least 1 for task='{self.task}' on "
+ f"backend='mlx': {why}."
+ )
+ if self.task == "orpo" and self.training.quantization == "8bit":
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."
+ "training.quantization='8bit' is not supported by task='orpo' on "
+ "backend='mlx': use quantization: none, or a pre-quantized "
+ "mlx-community 4-bit base with quantization: 4bit."
)
return self
if self.task in MLX_TASKS:
return self
raise ValueError(
- f"MLX backend only ships SFT and DPO; task='{self.task}' has no "
+ f"MLX backend only ships SFT, DPO and ORPO; task='{self.task}' has no "
"trainer on backend='mlx'. "
f"Use backend=transformers for task={self.task}."
)
diff --git a/src/soup_cli/trainer/mlx_dpo.py b/src/soup_cli/trainer/mlx_dpo.py
index 7460efbf..5aa7f9bf 100644
--- a/src/soup_cli/trainer/mlx_dpo.py
+++ b/src/soup_cli/trainer/mlx_dpo.py
@@ -356,7 +356,8 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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)"
+ f"data.chat_template (MLX {self.objective} renders with the model's own "
+ "template)"
)
for name, label in (
("use_galore", "GaLore"),
@@ -399,23 +400,18 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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,
- )
- )
+ examples.append(self._build_example(row, max_length))
except IdenticalPairError:
ties += 1
except PrefixUnstableError:
unstable.append(index)
except PreferenceRowError as exc:
- raise PreferenceRowError(f"dpo {split} row {index}: {exc}") from exc
+ raise PreferenceRowError(
+ f"{self.objective.lower()} {split} row {index}: {exc}"
+ ) from exc
if unstable:
console.print(
- f"[yellow]MLX DPO: skipped {len(unstable)} {split} row(s) whose "
+ f"[yellow]MLX {self.objective}: 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]})[/]"
@@ -468,20 +464,20 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
if split is None or not sample:
if split is None:
console.print(
- "[yellow]MLX DPO: computing log-probs over the full vocabulary "
+ f"[yellow]MLX {self.objective}: 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)
+ tokens, mask = self._verification_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 "
+ f"[yellow]MLX {self.objective}: this architecture changes logits after the vocab "
"head; using the full-vocabulary path (more memory)[/]"
)
return None
@@ -489,6 +485,78 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
# -- loop -------------------------------------------------------------
+ # -- objective hooks --------------------------------------------------
+ #
+ # The loop below is shared by every native preference objective on MLX
+ # (DPO here, ORPO in mlx_orpo.py). A subclass changes the tokenized
+ # example, the arrays a batch needs, what is prepared before the first
+ # update, the loss and its metrics -- nothing else.
+
+ #: Name used in messages and the adapter metadata.
+ objective = "DPO"
+ #: Metrics ``_loss`` returns, in report order; all are batch means.
+ metric_names: tuple = ("reward_accuracy", "reward_margin")
+
+ #: An objective whose loss has no finite value on some inputs (ORPO's
+ #: log1mexp at a mean log-prob of 0) stops the run instead of training on
+ #: NaN. DPO keeps its documented behaviour: a diverged run reports NaN.
+ fail_on_nonfinite = False
+
+ def _build_example(self, row: dict, max_length: int) -> Any:
+ return build_preference_example(
+ row, self.tokenizer, max_length=max_length, max_prompt_length=max_length // 2,
+ )
+
+ def _batch_arrays(self, examples: list) -> tuple:
+ return self._to_arrays(examples)
+
+ def _verification_arrays(self, examples: list) -> tuple:
+ """``(tokens, completion mask)`` for the head-split check."""
+ return self._to_arrays(examples)
+
+ def _check_finite(self, loss: Any, split: str) -> None:
+ import math as _math
+
+ value = loss.item()
+ if self.fail_on_nonfinite and not _math.isfinite(value):
+ raise FloatingPointError(
+ f"MLX {self.objective}: nonfinite loss ({value}) on the {split} split; "
+ "lower training.lr or check the rows"
+ )
+
+ def _prepare_objective(self, train_examples: list, val_examples: list,
+ batch_size: int) -> None:
+ """Run before the checkpoint loads: DPO's reference is the base model."""
+ self._ref = {"train": self._reference_logps(train_examples, batch_size)}
+ if val_examples:
+ self._ref["val"] = self._reference_logps(val_examples, batch_size)
+
+ def _loss(self, model: Any, arrays: tuple, split: str, rows: Any) -> tuple:
+ tokens, mask = arrays
+ ref_chosen, ref_rejected = (r[rows] for r in self._ref[split])
+ logps = sequence_logps(model, tokens, mask, head_split=self._head_split)
+ half = ref_chosen.shape[0]
+ return dpo_loss(
+ logps[:half], logps[half:], ref_chosen, ref_rejected,
+ float(self.config.training.dpo_beta),
+ )
+
+ def _format_metrics(self, metrics: dict) -> str:
+ return (
+ f"reward acc {metrics['reward_accuracy']:.2f}, "
+ f"margin {metrics['reward_margin']:.4f}"
+ )
+
+ def _objective_metadata(self) -> dict:
+ return {
+ "task": "dpo",
+ "dpo_beta": float(self.config.training.dpo_beta),
+ "dpo_loss_type": "sigmoid",
+ "reference": "precomputed from the base model",
+ }
+
+ # -- loop -------------------------------------------------------------
+
def train(self, display=None, tracker=None, run_id=None, resume_from_checkpoint=None) -> dict:
self._require_mlx()
@@ -500,6 +568,7 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
cfg = self.config
tcfg = cfg.training
+ name = self.objective
if self.model is None or self.tokenizer is None:
raise RuntimeError("MLX backend: setup(dataset) must be called before train()")
@@ -513,19 +582,18 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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)[/]"
+ f"[yellow]MLX {name}: skipped {skipped} {name.lower()} 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"MLX {name}: {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))} "
@@ -548,10 +616,7 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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
- )
+ self._prepare_objective(train_examples, val_examples, batch_size)
if resume_from_checkpoint is not None:
self._load_checkpoint_weights(resume_from_checkpoint)
@@ -569,39 +634,47 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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
+ def loss_fn(model, arrays, rows):
+ return self._loss(model, arrays, "train", rows)
loss_and_grad = nn.value_and_grad(self.model, loss_fn)
+ names = self.metric_names
def evaluate() -> Optional[dict]:
if not val_examples:
return None
self.model.eval()
- losses, accs = [], []
+ total = {"loss": 0.0, **{k: 0.0 for k in names}}
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))
+ arrays = self._batch_arrays(chunk)
+ rows = mx.arange(start, start + len(chunk))
+ loss, metrics = self._loss(self.model, arrays, "val", rows)
+ mx.eval(loss, *(metrics[k] for k in names))
+ self._check_finite(loss, "val")
+ # Weighted by the chunk's size: a partial last chunk counts
+ # for its rows, not as a whole batch.
+ total["loss"] += loss.item() * len(chunk)
+ for k in names:
+ total[k] += metrics[k].item() * len(chunk)
self.model.train()
- return {
- "val_loss": sum(losses) / len(val_examples),
- "val_reward_accuracy": sum(accs) / len(val_examples),
- }
+ out = {"val_loss": total["loss"] / len(val_examples)}
+ out.update({f"val_{k}": total[k] / len(val_examples) for k in names})
+ return out
def save(path: Path) -> None:
- mx.save_safetensors(str(path), dict(tree_flatten(self.model.trainable_parameters())))
+ # Written beside the target and renamed into place: a crash mid-write
+ # never leaves a complete-looking adapter file.
+ partial = path.with_name(path.stem + ".partial.safetensors")
+ mx.save_safetensors(str(partial), dict(tree_flatten(self.model.trainable_parameters())))
+ partial.replace(path)
+
+ # Written now as well as at the end, so a step checkpoint of a run that
+ # stops early still sits beside the metadata `--resume` checks.
+ self._write_adapter_config(
+ output_dir, batch_size=batch_size, iters=iters, accum=accum,
+ optimizer_plan=optimizer_plan, seed=seed, data_seed=data_seed,
+ )
save_steps = int(getattr(tcfg, "save_steps", 0) or 0)
logging_steps = max(1, int(getattr(tcfg, "logging_steps", 10) or 10))
@@ -614,31 +687,29 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
self.model.train()
grads = None
- group_loss = group_acc = group_margin = 0.0
+ group = {"loss": 0.0, **{k: 0.0 for k in names}}
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]
- )
+ arrays = self._batch_arrays(chunk)
+ (loss, metrics), step_grads = loss_and_grad(self.model, arrays, mx.array(batch))
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)
+ mx.eval(loss, *(metrics[k] for k in names), 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()
+ self._check_finite(loss, "train")
+ group["loss"] += loss.item()
+ for k in names:
+ group[k] += metrics[k].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
@@ -655,10 +726,9 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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
+ step = {k: v / accum for k, v in group.items()}
+ losses.append(step["loss"])
+ group = {k: 0.0 for k in group}
# Evaluate once per epoch: when this update crossed an epoch
# boundary, or on the last update.
@@ -674,8 +744,8 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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,
+ loss=step["loss"], lr=self._current_lr(optimizer, tcfg.lr),
+ speed=speed, metrics=step, val=val,
)
finally:
@@ -700,7 +770,7 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
}
if final_eval is not None:
result.update(final_eval)
- console.print(f"[green]MLX DPO training complete:[/] {output_dir}")
+ console.print(f"[green]MLX {name} training complete:[/] {output_dir}")
return result
# -- helpers ----------------------------------------------------------
@@ -712,9 +782,8 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
except (TypeError, ValueError, AttributeError):
return float(fallback)
- @staticmethod
- def _report(display, tracker, run_id, *, step, epoch, loss, lr, speed,
- reward_acc, margin, val) -> None:
+ def _report(self, display, tracker, run_id, *, step, epoch, loss, lr, speed,
+ metrics, val) -> None:
val_loss = val["val_loss"] if val else None
try:
import mlx.core as mx
@@ -729,15 +798,11 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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}"
- )
+ msg = f"step {step}: loss {loss:.4f}, {self._format_metrics(metrics)}"
if val:
- msg += (
- f", val loss {val['val_loss']:.4f}, "
- f"val reward acc {val['val_reward_accuracy']:.2f}"
- )
+ msg += f", val loss {val['val_loss']:.4f}"
+ if "val_reward_accuracy" in val:
+ msg += f", val reward acc {val['val_reward_accuracy']:.2f}"
console.print(f"[dim]{msg}[/]")
if tracker is not None and run_id:
try:
@@ -767,9 +832,11 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
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."""
+ """The same loadable shape MLX SFT writes, plus what the objective ran with."""
cfg = self.config
- (output_dir / "adapter_config.json").write_text(
+ target = output_dir / "adapter_config.json"
+ partial = output_dir / "adapter_config.json.partial"
+ partial.write_text(
json.dumps(
{
"fine_tune_type": "lora",
@@ -786,13 +853,11 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):
"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",
+ **self._objective_metadata(),
"seed": seed,
"data_seed": data_seed,
},
indent=2,
)
)
+ partial.replace(target)
diff --git a/src/soup_cli/trainer/mlx_orpo.py b/src/soup_cli/trainer/mlx_orpo.py
new file mode 100644
index 00000000..87263d27
--- /dev/null
+++ b/src/soup_cli/trainer/mlx_orpo.py
@@ -0,0 +1,392 @@
+"""MLX ORPO trainer — reference-free odds-ratio preference optimization on Apple Silicon.
+
+The objective is TRL 0.29.1's ``experimental/orpo/orpo_trainer.py``, the trainer
+Soup's transformers backend runs for ``task: orpo``:
+
+- ``a``, ``b``: the **mean** log-probability of the chosen / rejected completion
+ tokens (``get_batch_logps(..., average_log_prob=True)``);
+- ``log_odds = (a - b) - (log1mexp(a) - log1mexp(b))``, with TRL's stable
+ ``log1mexp`` (``log1p(-exp(x))`` below ``-ln 2``, ``log(-expm1(x))`` above);
+- loss = chosen NLL - ``orpo_beta * mean(logsigmoid(log_odds))``, where the NLL
+ is a token-mean cross-entropy over the **whole** chosen sequence, prompt
+ included (every position whose target is a real token), across the batch.
+
+No reference model exists and nothing is precomputed. The loop, LoRA attach,
+optimizer plan, clipping, seeding, chunked head and adapter writer are MLX DPO's
+(:class:`~soup_cli.trainer.mlx_dpo.MLXDPOTrainerWrapper`); this module adds the
+tokenized example, the two masks, the loss and its metrics.
+
+Tokenization follows TRL's ORPO ``tokenize_row`` rather than DPO's: rows are
+rendered to text first (``apply_chat_template`` with TRL's common-prefix rule),
+the answer is located with ``build_tokenized_answer`` (which tolerates a merge
+of the last prompt token into the answer), BOS is prepended and EOS appended
+when missing. Over-long rows are then cut by Soup's cap (prompt to
+``max_length // 2``, ``keep_end`` as ``ORPOConfig`` defaults, completions to the
+remaining room), the same cap ``enforce_preference_sequence_limit`` applies to
+the transformers path. TRL's own in-tokenizer answer cut, which can empty the
+shorter answer, is not reproduced; on rows that fit, the two backends see the
+same tokens.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from itertools import takewhile
+from typing import Any
+
+from rich.console import Console
+
+from soup_cli.trainer._trl_compat import _truncate_tokens
+from soup_cli.trainer.mlx_dpo import (
+ DEFAULT_LOGIT_CHUNK,
+ MLXDPOTrainerWrapper,
+ PreferenceRowError,
+ PrefixUnstableError,
+ _as_ids,
+ _normalise_row,
+)
+
+console = Console()
+
+#: ``ORPOConfig.truncation_mode``'s default in TRL 0.29.1.
+ORPO_TRUNCATION_MODE = "keep_end"
+_LN2 = 0.6931471805599453
+
+
+@dataclass(frozen=True)
+class OrpoExample:
+ """One tokenized pair: two full sequences and where each answer starts.
+
+ The prompt part of the chosen and rejected sequences can differ by one
+ token, when the tokenizer merges the last prompt token into the answer;
+ TRL tolerates exactly that, and so does this.
+ """
+
+ chosen_ids: list
+ chosen_prompt_len: int
+ rejected_ids: list
+ rejected_prompt_len: int
+
+
+# --------------------------------------------------------------------------
+# Tokenization (TRL 0.29.1 ORPOTrainer.tokenize_row / build_tokenized_answer)
+# --------------------------------------------------------------------------
+
+
+def _common_prefix(a: str, b: str) -> str:
+ return "".join(x for x, _ in takewhile(lambda p: p[0] == p[1], zip(a, b)))
+
+
+def render_preference_text(row: dict, tokenizer: Any) -> tuple[str, str, str]:
+ """``(prompt, chosen, rejected)`` text, as ``trl.data_utils.apply_chat_template``.
+
+ Text rows pass through. Conversational rows render the prompt with a
+ generation prompt (or ``continue_final_message`` after an assistant turn),
+ then each ``prompt + answer``; the prompt is narrowed to its common prefix
+ with the chosen rendering, the chosen answer taken after it, then narrowed
+ again against the rejected rendering -- the same order TRL uses.
+ """
+ prompt, chosen, rejected = row["prompt"], row["chosen"], row["rejected"]
+ if not isinstance(prompt, list):
+ return prompt, chosen, rejected
+ last_role = prompt[-1]["role"]
+ if last_role in ("user", "tool"):
+ kwargs = {"add_generation_prompt": True, "continue_final_message": False}
+ elif last_role == "assistant":
+ kwargs = {"add_generation_prompt": False, "continue_final_message": True}
+ else:
+ raise PreferenceRowError(f"the prompt ends with an unsupported role {last_role!r}")
+ prompt_text = tokenizer.apply_chat_template(prompt, tokenize=False, **kwargs)
+ chosen_full = tokenizer.apply_chat_template(prompt + chosen, tokenize=False)
+ prompt_text = _common_prefix(prompt_text, chosen_full)
+ chosen_text = chosen_full[len(prompt_text):]
+ rejected_full = tokenizer.apply_chat_template(prompt + rejected, tokenize=False)
+ prompt_text = _common_prefix(prompt_text, rejected_full)
+ rejected_text = rejected_full[len(prompt_text):]
+ return prompt_text, chosen_text, rejected_text
+
+
+def _encode(tokenizer: Any, text: str) -> list:
+ return _as_ids(tokenizer.encode(text, add_special_tokens=False))
+
+
+def _tokenized_answer(tokenizer: Any, prompt: str, answer: str) -> tuple[list, list]:
+ """``(prompt_ids, answer_ids)`` for ``prompt + answer``: TRL's
+ ``build_tokenized_answer``. The answer starts one token earlier when the
+ tokenizer merged the last prompt token into it."""
+ full = _encode(tokenizer, prompt + answer)
+ prompt_ids = _encode(tokenizer, prompt)
+ start = len(prompt_ids)
+ if prompt_ids != full[:start]:
+ start -= 1
+ return full[:start], full[start:]
+
+
+def build_orpo_example(
+ row: dict,
+ tokenizer: Any,
+ *,
+ max_length: int,
+ max_prompt_length: int,
+ truncation_mode: str = ORPO_TRUNCATION_MODE,
+) -> OrpoExample:
+ """Tokenize one preference row the way TRL 0.29.1's ORPO trainer does.
+
+ A tie (``chosen == rejected``) is kept: ORPO's odds-ratio term is a finite
+ constant there (``log_odds = 0``) and the NLL still trains, which is what
+ TRL does. A pair whose two prompt renderings differ by more than one token
+ raises :class:`PrefixUnstableError` (TRL raises a ``ValueError`` there) so
+ the caller can skip it with a count.
+ """
+ prompt, chosen, rejected = render_preference_text(_normalise_row(row), tokenizer)
+ chosen_prompt, chosen_answer = _tokenized_answer(tokenizer, prompt, chosen)
+ rejected_prompt, rejected_answer = _tokenized_answer(tokenizer, prompt, rejected)
+ diff_tokens = sum(a != b for a, b in zip(chosen_prompt, rejected_prompt))
+ if diff_tokens > 1 or abs(len(chosen_prompt) - len(rejected_prompt)) > 1:
+ raise PrefixUnstableError(
+ "the chosen and rejected renderings tokenize the prompt differently "
+ "beyond the last token, so the answers cannot be located"
+ )
+
+ bos = getattr(tokenizer, "bos_token_id", None)
+ eos = getattr(tokenizer, "eos_token_id", None)
+ sides = []
+ pairs = ((chosen_prompt, chosen_answer), (rejected_prompt, rejected_answer))
+ for prompt_ids, answer_ids in pairs:
+ prompt_ids, answer_ids = list(prompt_ids), list(answer_ids)
+ if bos is not None and (not prompt_ids or prompt_ids[0] != bos):
+ prompt_ids = [bos] + prompt_ids
+ if eos is not None and (not answer_ids or answer_ids[-1] != eos):
+ answer_ids = answer_ids + [eos]
+ # Soup's cap (enforce_preference_sequence_limit's ORPO branch).
+ prompt_ids = _truncate_tokens(prompt_ids, max_prompt_length, truncation_mode)
+ answer_ids = answer_ids[: max(0, max_length - len(prompt_ids))]
+ if not answer_ids:
+ raise PreferenceRowError(
+ f"no answer token fits in data.max_length ({max_length}) after the "
+ f"{len(prompt_ids)}-token prompt"
+ )
+ sides.append((prompt_ids, answer_ids))
+ (cp, ca), (rp, ra) = sides
+ return OrpoExample(
+ chosen_ids=cp + ca, chosen_prompt_len=len(cp),
+ rejected_ids=rp + ra, rejected_prompt_len=len(rp),
+ )
+
+
+def collate_orpo(examples: list) -> tuple[list, list, list]:
+ """``(tokens, completion_mask, sequence_mask)``: the chosen rows, then the
+ rejected rows, right-padded with 0.
+
+ ``completion_mask[i][t]`` marks a completion token at ``t`` (the preference
+ score); ``sequence_mask[i][t]`` marks every real token (the NLL). Both are
+ over token positions; :func:`token_logps` scores position ``t >= 1``.
+ """
+ seqs = [(e.chosen_ids, e.chosen_prompt_len) for e in examples]
+ seqs += [(e.rejected_ids, e.rejected_prompt_len) for e in examples]
+ width = max(len(ids) for ids, _ in seqs)
+ tokens, completion, sequence = [], [], []
+ for ids, prompt_len in seqs:
+ pad = width - len(ids)
+ tokens.append(list(ids) + [0] * pad)
+ completion.append([0] * prompt_len + [1] * (len(ids) - prompt_len) + [0] * pad)
+ sequence.append([1] * len(ids) + [0] * pad)
+ return tokens, completion, sequence
+
+
+# --------------------------------------------------------------------------
+# Scoring and loss
+# --------------------------------------------------------------------------
+
+
+def token_logps(
+ model: Any,
+ tokens: Any,
+ *,
+ head_split: Any = None,
+ chunk_size: int = DEFAULT_LOGIT_CHUNK,
+) -> Any:
+ """Log-probability of ``tokens[:, t]`` given the tokens before it, for
+ ``t = 1 .. T-1``: shape ``(B, T-1)``.
+
+ ORPO's NLL covers the prompt, so unlike DPO every position is scored. With
+ ``head_split`` the backbone runs once and the vocab head runs in
+ checkpointed chunks, so a batch's full-vocabulary logits are never all held.
+ """
+ import mlx.core as mx
+
+ inputs, targets = tokens[:, :-1], tokens[:, 1:]
+
+ def score(logits: Any, tgt: Any) -> Any:
+ logits = logits.astype(mx.float32)
+ picked = mx.take_along_axis(logits, tgt[..., None], axis=-1)[..., 0]
+ return picked - mx.logsumexp(logits, axis=-1)
+
+ if head_split is None:
+ return score(model(inputs), targets)
+ backbone, head = head_split
+ hidden = backbone(inputs)
+ width = int(hidden.shape[1])
+ step = max(1, int(chunk_size))
+ parts = []
+ for lo in range(0, width, step):
+ hi = min(width, lo + step)
+ chunk = mx.checkpoint(lambda h, t=targets[:, lo:hi]: score(head(h), t))
+ parts.append(chunk(hidden[:, lo:hi]))
+ return mx.concatenate(parts, axis=1)
+
+
+def log1mexp(x: Any) -> Any:
+ """``log(1 - exp(x))`` for ``x <= 0``, TRL's branch at ``-ln 2``.
+
+ ``mx.where`` evaluates both branches, so each one gets its argument
+ clamped to its own side of ``-ln 2``: the unused branch then stays finite
+ and leaks no NaN into the value or the gradient. At ``x = 0`` the result is
+ ``-inf``, as in TRL; the trainer stops on the nonfinite loss.
+ """
+ import mlx.core as mx
+
+ low = mx.minimum(x, -_LN2)
+ high = mx.maximum(x, -_LN2)
+ return mx.where(x < -_LN2, mx.log1p(-mx.exp(low)), mx.log(-mx.expm1(high)))
+
+
+def orpo_loss(
+ chosen_mean_logps: Any,
+ rejected_mean_logps: Any,
+ chosen_nll: Any,
+ beta: float,
+) -> tuple[Any, dict]:
+ """TRL's ORPO loss and its metrics from per-pair mean completion log-probs.
+
+ Returns ``(loss, metrics)``: ``nll_loss``, ``log_odds_ratio``
+ (``mean(logsigmoid(log_odds))``), ``log_odds_chosen`` (``mean(log_odds)``),
+ ``reward_accuracy`` and ``reward_margin`` (rewards are ``beta * logp``, as
+ TRL logs them). The trainer stops on a nonfinite loss instead of training on it.
+ """
+ import mlx.core as mx
+ import mlx.nn as nn
+
+ a = chosen_mean_logps.astype(mx.float32)
+ b = rejected_mean_logps.astype(mx.float32)
+ log_odds = (a - b) - (log1mexp(a) - log1mexp(b))
+ ratio = nn.log_sigmoid(log_odds)
+ loss = chosen_nll - beta * ratio.mean()
+ metrics = {
+ "nll_loss": chosen_nll,
+ "log_odds_ratio": ratio.mean(),
+ "log_odds_chosen": log_odds.mean(),
+ "reward_accuracy": (a > b).astype(mx.float32).mean(),
+ "reward_margin": (beta * (a - b)).mean(),
+ }
+ return loss, metrics
+
+
+def orpo_terms(model: Any, tokens: Any, completion: Any, sequence: Any, *,
+ head_split: Any = None) -> tuple[Any, Any, Any]:
+ """``(chosen mean logps, rejected mean logps, chosen NLL)`` for a collated batch."""
+ import mlx.core as mx
+
+ logps = token_logps(model, tokens, head_split=head_split)
+ comp = completion[:, 1:].astype(mx.float32)
+ seq = sequence[:, 1:].astype(mx.float32)
+ mean_logps = (logps * comp).sum(axis=-1) / comp.sum(axis=-1)
+ half = tokens.shape[0] // 2
+ chosen_seq = seq[:half]
+ nll = -(logps[:half] * chosen_seq).sum() / chosen_seq.sum()
+ return mean_logps[:half], mean_logps[half:], nll
+
+
+# --------------------------------------------------------------------------
+# Trainer
+# --------------------------------------------------------------------------
+
+
+class MLXORPOTrainerWrapper(MLXDPOTrainerWrapper):
+ """ORPO on MLX: MLX DPO's loop with ORPO's tokens, masks and loss."""
+
+ objective = "ORPO"
+ metric_names = (
+ "nll_loss", "log_odds_ratio", "log_odds_chosen", "reward_accuracy", "reward_margin",
+ )
+
+ def _build_example(self, row: dict, max_length: int) -> OrpoExample:
+ return build_orpo_example(
+ row, self.tokenizer, max_length=max_length, max_prompt_length=max_length // 2,
+ )
+
+ def _batch_arrays(self, examples: list) -> tuple:
+ import mlx.core as mx
+
+ tokens, completion, sequence = collate_orpo(examples)
+ return mx.array(tokens), mx.array(completion), mx.array(sequence)
+
+ def _verification_arrays(self, examples: list) -> tuple:
+ # The head-split check compares completion scores on the DPO-shaped
+ # batch; any token positions will do, so reuse the chosen sequences.
+ import mlx.core as mx
+
+ tokens, completion, _ = collate_orpo(examples)
+ return mx.array(tokens), mx.array(completion)
+
+ def _prepare_objective(self, train_examples: list, val_examples: list,
+ batch_size: int) -> None:
+ """Reference-free: nothing to precompute."""
+
+ fail_on_nonfinite = True
+
+ def _loss(self, model: Any, arrays: tuple, split: str, rows: Any) -> tuple:
+ tokens, completion, sequence = arrays
+ a, b, nll = orpo_terms(model, tokens, completion, sequence, head_split=self._head_split)
+ return orpo_loss(a, b, nll, float(self.config.training.orpo_beta))
+
+ def _format_metrics(self, metrics: dict) -> str:
+ return (
+ f"nll {metrics['nll_loss']:.4f}, log-odds ratio "
+ f"{metrics['log_odds_ratio']:.4f}, reward acc {metrics['reward_accuracy']:.2f}"
+ )
+
+ def _objective_metadata(self) -> dict:
+ return {
+ "task": "orpo",
+ "orpo_beta": float(self.config.training.orpo_beta),
+ "orpo_loss": "trl-0.29.1 odds ratio + chosen NLL",
+ "reference": "none (reference-free)",
+ "truncation_mode": ORPO_TRUNCATION_MODE,
+ }
+
+ def _load_checkpoint_weights(self, checkpoint_path: str) -> None:
+ """Warm start only from an ORPO adapter of the same base.
+
+ The checkpoint's directory must hold the ``adapter_config.json`` an MLX
+ ORPO run writes (it is written before the first step, so step
+ checkpoints of a run that stopped early have it too). A DPO or SFT
+ adapter, a different base model, or no metadata at all is refused
+ before any tensor loads; the tensor names and shapes are then checked
+ by MLX SFT's loader.
+ """
+ import json
+ from pathlib import Path
+
+ meta_path = Path(checkpoint_path).resolve().parent / "adapter_config.json"
+ if not meta_path.is_file():
+ raise ValueError(
+ f"MLX ORPO: no adapter_config.json beside {checkpoint_path}; cannot "
+ "confirm it is an ORPO adapter of this base model"
+ )
+ try:
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise ValueError(f"MLX ORPO: unreadable {meta_path}: {exc}") from exc
+ if meta.get("task") != "orpo":
+ raise ValueError(
+ f"MLX ORPO: {checkpoint_path} was trained with task="
+ f"{meta.get('task')!r}, not 'orpo'; start a fresh run or resume "
+ "with the matching task"
+ )
+ if str(meta.get("model")) != str(self.config.base):
+ raise ValueError(
+ f"MLX ORPO: {checkpoint_path} belongs to base {meta.get('model')!r}, "
+ f"not {self.config.base!r}"
+ )
+ super()._load_checkpoint_weights(checkpoint_path)
diff --git a/src/soup_cli/trainer/mlx_routing.py b/src/soup_cli/trainer/mlx_routing.py
index 117c14e8..fdb60a16 100644
--- a/src/soup_cli/trainer/mlx_routing.py
+++ b/src/soup_cli/trainer/mlx_routing.py
@@ -20,6 +20,10 @@ class _MLXRegistry(dict):
from soup_cli.trainer.mlx_dpo import MLXDPOTrainerWrapper
return MLXDPOTrainerWrapper
+ if task == "orpo":
+ from soup_cli.trainer.mlx_orpo import MLXORPOTrainerWrapper
+
+ return MLXORPOTrainerWrapper
if task == "grpo":
from soup_cli.trainer.mlx_grpo import MLXGRPOTrainerWrapper
@@ -27,13 +31,13 @@ class _MLXRegistry(dict):
raise KeyError(task)
def __contains__(self, key: object) -> bool:
- return key in ("sft", "dpo", "grpo")
+ return key in ("sft", "dpo", "orpo", "grpo")
def __getitem__(self, key: str):
return self._resolve(key)
def keys(self): # noqa: D401
- return ("sft", "dpo", "grpo")
+ return ("sft", "dpo", "orpo", "grpo")
MLX_TRAINER_REGISTRY: _MLXRegistry = _MLXRegistry()
diff --git a/tests/test_issue1213_dispatch_parity.py b/tests/test_issue1213_dispatch_parity.py
index 6294cfe4..9a88a9fe 100644
--- a/tests/test_issue1213_dispatch_parity.py
+++ b/tests/test_issue1213_dispatch_parity.py
@@ -77,11 +77,12 @@ _EXPECTED = {
"asr": "AsrTrainerWrapper",
}
-#: MLX rows resolve through ``mlx_routing``. Same three tasks the registry
+#: MLX rows resolve through ``mlx_routing``. Same four tasks the registry
#: accepts; the name is what ``resolve_trainer`` would have imported.
_MLX_EXPECTED = {
"sft": "MLXSFTTrainerWrapper",
"dpo": "MLXDPOTrainerWrapper",
+ "orpo": "MLXORPOTrainerWrapper",
"grpo": "MLXGRPOTrainerWrapper",
}
diff --git a/tests/test_issue1358_vocab_expansion_refused.py b/tests/test_issue1358_vocab_expansion_refused.py
index 331b5abd..4fa65be1 100644
--- a/tests/test_issue1358_vocab_expansion_refused.py
+++ b/tests/test_issue1358_vocab_expansion_refused.py
@@ -134,6 +134,15 @@ class TestTheOtherPathsThatDropThem:
assert "data.add_new_tokens is not applied on backend='mlx'" in message, message
+ @pytest.mark.parametrize("field", _FIELDS)
+ @pytest.mark.parametrize("task", ["dpo", "orpo"])
+ def test_mlx_preference_loops(self, task, field):
+ """The native DPO and ORPO loops tokenize with the base tokenizer as it is;
+ the refusal rests on both being in ``MLX_TASKS`` (review of #2073)."""
+ message = _refusal(_yaml(task, backend="mlx", field=field, data={"format": "dpo"}))
+
+ assert f"data.{field} is not applied on backend='mlx'" in message, message
+
def test_sft_layer_streaming(self):
message = _refusal(_yaml(
"sft",
diff --git a/tests/test_mlx_dpo.py b/tests/test_mlx_dpo.py
index 5383cc6e..db3cb98c 100644
--- a/tests/test_mlx_dpo.py
+++ b/tests/test_mlx_dpo.py
@@ -468,7 +468,8 @@ class TestConfig:
fields = {entry.field for entry in check_config(cfg)}
assert fields == {"training.use_galore"}
- @pytest.mark.parametrize("task", ["ipo", "kto", "orpo", "simpo", "ppo"])
+ # orpo has its own MLX trainer since #2004 (tests/test_mlx_orpo.py).
+ @pytest.mark.parametrize("task", ["ipo", "kto", "simpo", "ppo"])
def test_other_preference_tasks_still_refused(self, task):
from soup_cli.config.loader import load_config_from_string
diff --git a/tests/test_mlx_orpo.py b/tests/test_mlx_orpo.py
new file mode 100644
index 00000000..4c25bc9a
--- /dev/null
+++ b/tests/test_mlx_orpo.py
@@ -0,0 +1,766 @@
+"""Native ORPO on MLX (#2004).
+
+The objective is pinned to TRL 0.29.1's ``experimental/orpo/orpo_trainer.py``,
+which Soup's transformers backend runs for ``task: orpo``. Three layers:
+
+- tokenization against TRL's own ``ORPOTrainer.tokenize_row`` on a real
+ ``PreTrainedTokenizerFast`` (needs ``trl`` / ``transformers``, no MLX);
+- the loss, its terms and its gradients against an independent float64 NumPy
+ oracle on fixed nonconstant logits (needs MLX), with every mutation the issue
+ lists shown to move the result;
+- training, saving and a fresh-process reload on a tiny random Llama (needs
+ MLX and mlx-lm). No downloads.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import subprocess
+import sys
+import textwrap
+
+import numpy as np
+import pytest
+
+from tests.test_mlx_dpo import _strip_ansi
+
+# --------------------------------------------------------------------------
+# A character tokenizer with HF's surface: encode(add_special_tokens=...),
+# bos/eos ids and a text chat template. Ids stay inside a 200-token vocab.
+# --------------------------------------------------------------------------
+
+BOS, EOS = 1, 2
+
+
+class CharTokenizer:
+ bos_token_id = BOS
+ eos_token_id = EOS
+ eos_token = "</s>"
+ pad_token_id = 0
+
+ def encode(self, text, add_special_tokens=True):
+ ids = [3 + (ord(c) % 190) for c in text]
+ return ([BOS] if add_special_tokens else []) + ids
+
+ def apply_chat_template(self, messages, tokenize=True, add_generation_prompt=False,
+ continue_final_message=False, **_):
+ parts = [f"<{m['role']}>{m['content']}|" for m in messages]
+ if continue_final_message:
+ parts[-1] = parts[-1][:-1]
+ text = "".join(parts) + ("<assistant>" if add_generation_prompt else "")
+ return self.encode(text, add_special_tokens=False) if tokenize else text
+
+
+def _decode(ids):
+ return "".join(chr(i - 3) if i > 2 else {1: "^", 2: "$"}.get(i, "?") for i in ids)
+
+
+class MergingTokenizer(CharTokenizer):
+ """Merges ``xy`` into one token, so a prompt ending in ``x`` before an
+ answer starting with ``y`` changes its last token in ``prompt + answer``."""
+
+ MERGED = 199
+
+ def encode(self, text, add_special_tokens=True):
+ out = [BOS] if add_special_tokens else []
+ i = 0
+ while i < len(text):
+ if text[i : i + 2] == "xy":
+ out.append(self.MERGED)
+ i += 2
+ else:
+ out.append(3 + (ord(text[i]) % 190))
+ i += 1
+ return out
+
+
+def _build(row, tokenizer=None, max_length=256, max_prompt_length=128, mode="keep_end"):
+ from soup_cli.trainer.mlx_orpo import build_orpo_example
+
+ return build_orpo_example(
+ row, tokenizer or CharTokenizer(), max_length=max_length,
+ max_prompt_length=max_prompt_length, truncation_mode=mode,
+ )
+
+
+_U = {"role": "user", "content": "hi"}
+_A = {"role": "assistant", "content": "a"}
+_B = {"role": "assistant", "content": "bb"}
+
+
+class TestTokenization:
+ def test_text_row_gets_bos_and_eos(self):
+ ex = _build({"prompt": "Q:", "chosen": " yes", "rejected": " no"})
+ assert _decode(ex.chosen_ids) == "^Q: yes$"
+ assert ex.chosen_prompt_len == 3
+ assert _decode(ex.rejected_ids[ex.rejected_prompt_len:]) == " no$"
+
+ def test_bos_and_eos_are_not_doubled(self):
+ class WithSpecials(CharTokenizer):
+ def encode(self, text, add_special_tokens=True):
+ return [BOS] + super().encode(text, False) + ([EOS] if text.endswith("!") else [])
+
+ ex = _build({"prompt": "Q", "chosen": "a!", "rejected": "b!"}, WithSpecials())
+ assert ex.chosen_ids.count(BOS) == 1 and ex.chosen_ids.count(EOS) == 1
+
+ def test_conversational_row_renders_like_trl(self):
+ ex = _build({"prompt": [_U], "chosen": [_A], "rejected": [_B]})
+ assert _decode(ex.chosen_ids) == "^<user>hi|<assistant>a|$"
+ assert _decode(ex.chosen_ids[: ex.chosen_prompt_len]) == "^<user>hi|<assistant>"
+ assert _decode(ex.rejected_ids[ex.rejected_prompt_len:]) == "bb|$"
+
+ def test_prompt_ending_in_assistant_continues_the_message(self):
+ ex = _build({"prompt": [_U, {"role": "assistant", "content": "Sure,"}],
+ "chosen": [_A], "rejected": [_B]})
+ assert _decode(ex.chosen_ids[: ex.chosen_prompt_len]) == "^<user>hi|<assistant>Sure,"
+
+ def test_a_generation_prompt_the_full_render_lacks_is_narrowed_away(self):
+ """TRL's common-prefix rule (the DeepSeek-R1 ``<think>`` case): text the
+ generation prompt adds but ``prompt + answer`` does not render is not
+ prompt, and the answer starts where the two renderings part."""
+
+ class Thinking(CharTokenizer):
+ def apply_chat_template(self, messages, tokenize=True, add_generation_prompt=False,
+ **kw):
+ text = super().apply_chat_template(messages, tokenize=False, **kw)
+ return text + ("<assistant><think>" if add_generation_prompt else "")
+
+ ex = _build({"prompt": [_U], "chosen": [_A], "rejected": [_B]}, Thinking())
+ assert _decode(ex.chosen_ids[: ex.chosen_prompt_len]) == "^<user>hi|<assistant>"
+ assert _decode(ex.chosen_ids[ex.chosen_prompt_len:]) == "a|$"
+
+ def test_a_merged_last_prompt_token_moves_the_answer_start(self):
+ """TRL's build_tokenized_answer: the answer starts one token earlier."""
+ ex = _build({"prompt": "zx", "chosen": "y1", "rejected": "q2"}, MergingTokenizer())
+ assert ex.chosen_ids[ex.chosen_prompt_len] == MergingTokenizer.MERGED
+ assert ex.chosen_prompt_len == ex.rejected_prompt_len - 1
+
+ def test_prompts_differing_beyond_one_token_are_unstable(self):
+ from soup_cli.trainer.mlx_dpo import PrefixUnstableError
+
+ class Shifty(CharTokenizer):
+ def encode(self, text, add_special_tokens=True):
+ ids = super().encode(text, add_special_tokens)
+ return [7, 7, 7] + ids if text.endswith("BAD") else ids
+
+ with pytest.raises(PrefixUnstableError):
+ _build({"prompt": "QQQ", "chosen": "ok", "rejected": "BAD"}, Shifty())
+
+ def test_a_tie_is_kept(self):
+ """ORPO trains a tie: log-odds 0, finite, and the NLL still learns."""
+ ex = _build({"prompt": "Q", "chosen": "same", "rejected": "same"})
+ assert ex.chosen_ids == ex.rejected_ids
+
+ def test_long_prompt_keeps_its_end_and_never_enters_the_answer(self):
+ ex = _build({"prompt": "P" * 100 + "END", "chosen": "a", "rejected": "b"},
+ max_length=40, max_prompt_length=20)
+ assert ex.chosen_prompt_len == 20
+ assert _decode(ex.chosen_ids[: ex.chosen_prompt_len]).endswith("END")
+ assert _decode(ex.chosen_ids[ex.chosen_prompt_len:]) == "a$"
+
+ def test_answer_cut_to_the_remaining_room(self):
+ ex = _build({"prompt": "Q", "chosen": "x" * 50, "rejected": "y"},
+ max_length=12, max_prompt_length=6)
+ assert len(ex.chosen_ids) == 12
+ assert len(ex.rejected_ids) == ex.rejected_prompt_len + 2
+
+ def test_no_room_for_an_answer_is_refused(self):
+ from soup_cli.trainer.mlx_dpo import PreferenceRowError
+
+ with pytest.raises(PreferenceRowError, match="no answer token fits"):
+ _build({"prompt": "Q" * 30, "chosen": "a", "rejected": "b"},
+ max_length=10, max_prompt_length=10)
+
+ def test_rows_go_through_the_loader_converter(self):
+ """The bundled layout: string prompt, conversations repeating the user turn."""
+ ex = _build({"prompt": "hi", "chosen": [_U, _A], "rejected": [_U, _B]})
+ assert _decode(ex.chosen_ids[: ex.chosen_prompt_len]) == "^<user>hi|<assistant>"
+
+
+class TestTheTrainerCapsLikeOrpoConfig:
+ def test_default_truncation_keeps_the_end_of_a_long_prompt(self):
+ """ORPOConfig's default is ``keep_end``; the trainer must use it."""
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.mlx_orpo import MLXORPOTrainerWrapper
+
+ wrapper = MLXORPOTrainerWrapper(load_config_from_string(_ORPO_YAML))
+ wrapper.config.data.max_length = 40
+ wrapper.tokenizer = CharTokenizer()
+ (example,), _ = wrapper._examples(
+ [{"prompt": "S" * 60 + "TAIL", "chosen": "a", "rejected": "b"}]
+ )
+ assert example.chosen_prompt_len == 20
+ assert _decode(example.chosen_ids[: example.chosen_prompt_len]).endswith("TAIL")
+
+
+class TestTokensMatchTrl:
+ """The same rows through TRL 0.29.1's ORPOTrainer.tokenize_row."""
+
+ def _tokenizer(self, tmp_path):
+ pytest.importorskip("trl")
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import PreTrainedTokenizerFast
+
+ words = ["<s>", "</s>", "<pad>", "<unk>", "<", ">", "user", "assistant", "|",
+ "what", "is", "two", "plus", "four", "five", "it", "Q", ":", "yes", "no"]
+ tok = Tokenizer(models.WordLevel(vocab={w: i for i, w in enumerate(words)},
+ unk_token="<unk>"))
+ tok.pre_tokenizer = pre_tokenizers.Sequence(
+ [pre_tokenizers.Whitespace(), pre_tokenizers.Punctuation()]
+ )
+ fast = PreTrainedTokenizerFast(
+ tokenizer_object=tok, bos_token="<s>", eos_token="</s>",
+ pad_token="<pad>", unk_token="<unk>",
+ )
+ fast.chat_template = (
+ "{% for m in messages %}<{{ m['role'] }}> {{ m['content'] }} | {% endfor %}"
+ "{% if add_generation_prompt %}<assistant> {% endif %}"
+ )
+ return fast
+
+ def _trl(self, tokenizer, row, max_length):
+ import types
+
+ from trl.data_utils import maybe_apply_chat_template
+ from trl.experimental.orpo.orpo_trainer import ORPOTrainer
+
+ stub = types.SimpleNamespace(
+ processing_class=tokenizer, is_encoder_decoder=False, max_length=max_length,
+ truncation_mode="keep_end", label_pad_token_id=-100, padding_value=0,
+ )
+ stub.build_tokenized_answer = types.MethodType(ORPOTrainer.build_tokenized_answer, stub)
+ return ORPOTrainer.tokenize_row(stub, maybe_apply_chat_template(row, tokenizer))
+
+ @pytest.mark.parametrize("row", [
+ {"prompt": "Q: what is two plus two", "chosen": " four", "rejected": " five"},
+ {"prompt": [{"role": "user", "content": "what is two plus two"}],
+ "chosen": [{"role": "assistant", "content": "it is four"}],
+ "rejected": [{"role": "assistant", "content": "five"}]},
+ ])
+ def test_ids_and_prompt_spans_match(self, tmp_path, row):
+ tokenizer = self._tokenizer(tmp_path)
+ trl = self._trl(tokenizer, row, max_length=64)
+ ours = _build(row, tokenizer, max_length=64, max_prompt_length=32)
+ for side in ("chosen", "rejected"):
+ ids = getattr(ours, f"{side}_ids")
+ span = getattr(ours, f"{side}_prompt_len")
+ assert ids == list(trl[f"{side}_input_ids"])
+ assert span == sum(1 for x in trl[f"{side}_labels"] if x == -100)
+
+
+# --------------------------------------------------------------------------
+# The loss against a float64 NumPy oracle
+# --------------------------------------------------------------------------
+
+
+def _np_log1mexp(x):
+ return np.where(x < -math.log(2), np.log1p(-np.exp(x)), np.log(-np.expm1(x)))
+
+
+def _np_terms(logits, tokens, completion, sequence, *, mean=True, nll_mask="sequence"):
+ shifted = logits[:, :-1] - logits[:, :-1].max(-1, keepdims=True)
+ logsm = shifted - np.log(np.exp(shifted).sum(-1, keepdims=True))
+ tgt = tokens[:, 1:]
+ lp = np.take_along_axis(logsm, tgt[..., None], -1)[..., 0]
+ comp = completion[:, 1:].astype(np.float64)
+ seq = (sequence if nll_mask == "sequence" else completion)[:, 1:].astype(np.float64)
+ scores = (lp * comp).sum(-1) / (comp.sum(-1) if mean else 1.0)
+ half = tokens.shape[0] // 2
+ nll = -(lp[:half] * seq[:half]).sum() / seq[:half].sum()
+ return scores[:half], scores[half:], nll
+
+
+def _np_loss(a, b, nll, beta, *, log1mexp=True, use_nll=True):
+ lo = (a - b) - ((_np_log1mexp(a) - _np_log1mexp(b)) if log1mexp else 0.0)
+ ratio = -np.logaddexp(0.0, -lo)
+ return (nll if use_nll else 0.0) - beta * ratio.mean(), lo
+
+
+def _fixture(seed=0, vocab=12):
+ """Two pairs, unequal prompt and answer lengths, right padding."""
+ from soup_cli.trainer.mlx_orpo import OrpoExample, collate_orpo
+
+ examples = [
+ OrpoExample([1, 5, 6, 7, 8, 9], 3, [1, 5, 6, 4, 2], 3),
+ OrpoExample([1, 3, 8, 2], 2, [1, 3, 9, 10, 11, 2], 2),
+ ]
+ tokens, completion, sequence = (np.array(x) for x in collate_orpo(examples))
+ rng = np.random.default_rng(seed)
+ logits = rng.normal(0.0, 2.0, size=(tokens.shape[0], tokens.shape[1], vocab))
+ return logits, tokens, completion, sequence
+
+
+class _Fixed:
+ def __new__(cls, logits):
+ nn = pytest.importorskip("mlx.nn")
+ mx = pytest.importorskip("mlx.core")
+
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.logits = mx.array(logits.astype(np.float32))
+
+ def __call__(self, x):
+ return self.logits[:, : x.shape[1]]
+
+ return Model()
+
+
+def _mlx(logits, tokens, completion, sequence, beta, **kw):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer.mlx_orpo import orpo_loss, orpo_terms
+
+ model = _Fixed(logits)
+ a, b, nll = orpo_terms(model, mx.array(tokens), mx.array(completion), mx.array(sequence), **kw)
+ loss, metrics = orpo_loss(a, b, nll, beta)
+ return np.array(a), np.array(b), float(nll.item()), float(loss.item()), metrics
+
+
+class TestTheLossMatchesTheOracle:
+ @pytest.mark.parametrize("beta", [0.1, 0.7])
+ def test_terms_and_total(self, beta):
+ logits, tokens, comp, seq = _fixture()
+ a, b, nll, loss, metrics = _mlx(logits, tokens, comp, seq, beta)
+ ra, rb, rnll = _np_terms(logits, tokens, comp, seq)
+ rloss, rlo = _np_loss(ra, rb, rnll, beta)
+ np.testing.assert_allclose(a, ra, rtol=1e-5)
+ np.testing.assert_allclose(b, rb, rtol=1e-5)
+ assert nll == pytest.approx(rnll, rel=1e-5)
+ assert loss == pytest.approx(rloss, rel=1e-5)
+ assert metrics["log_odds_chosen"].item() == pytest.approx(rlo.mean(), rel=1e-4)
+
+ def test_the_chunked_head_gives_the_same_scores(self):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer.mlx_orpo import token_logps
+
+ logits, tokens, _, _ = _fixture()
+ model = _Fixed(logits)
+ split = (lambda x: model.logits[:, : x.shape[1]], lambda h: h)
+ full = token_logps(model, mx.array(tokens))
+ chunked = token_logps(model, mx.array(tokens), head_split=split, chunk_size=2)
+ assert mx.allclose(full, chunked, atol=1e-6).item()
+
+ @pytest.mark.parametrize("mutation", [
+ "no_log1mexp", "summed_scores", "reversed_pair", "no_nll", "completion_mask_for_nll",
+ ])
+ def test_each_listed_mutation_moves_the_loss(self, mutation):
+ """The fixture is sensitive to every wrong objective the issue names, so
+ an implementation making any of them fails `test_terms_and_total`."""
+ logits, tokens, comp, seq = _fixture()
+ right, _ = _np_loss(*_np_terms(logits, tokens, comp, seq), 0.1)
+ a, b, nll = _np_terms(
+ logits, tokens, comp, seq, mean=mutation != "summed_scores",
+ nll_mask="completion" if mutation == "completion_mask_for_nll" else "sequence",
+ )
+ if mutation == "reversed_pair":
+ a, b = b, a
+ wrong, _ = _np_loss(a, b, nll, 0.1, log1mexp=mutation != "no_log1mexp",
+ use_nll=mutation != "no_nll")
+ assert abs(wrong - right) > 1e-3
+
+ def test_prompt_logits_move_the_nll_but_not_the_scores(self):
+ logits, tokens, comp, seq = _fixture()
+ a0, b0, nll0, _, _ = _mlx(logits, tokens, comp, seq, 0.1)
+ bumped = logits.copy()
+ # Positions t whose target t+1 is a real prompt token.
+ prompt_target = (seq[:, 1:] == 1) & (comp[:, 1:] == 0)
+ bumped[:, :-1][prompt_target] += np.random.default_rng(3).normal(
+ 0.0, 3.0, size=(int(prompt_target.sum()), logits.shape[-1])
+ )
+ a1, b1, nll1, _, _ = _mlx(bumped, tokens, comp, seq, 0.1)
+ np.testing.assert_allclose(a1, a0, rtol=1e-6)
+ np.testing.assert_allclose(b1, b0, rtol=1e-6)
+ assert abs(nll1 - nll0) > 1e-3
+
+ def test_padding_does_not_score(self):
+ logits, tokens, comp, seq = _fixture()
+ a0, b0, nll0, _, _ = _mlx(logits, tokens, comp, seq, 0.1)
+ bumped = logits.copy()
+ pad_target = seq[:, 1:] == 0
+ bumped[:, :-1][pad_target] = 50.0
+ a1, b1, nll1, _, _ = _mlx(bumped, tokens, comp, seq, 0.1)
+ np.testing.assert_allclose(a1, a0, rtol=1e-6)
+ assert nll1 == pytest.approx(nll0, rel=1e-6)
+
+ def test_gradients_match_finite_differences(self):
+ mx = pytest.importorskip("mlx.core")
+ nn = pytest.importorskip("mlx.nn")
+ from soup_cli.trainer.mlx_orpo import orpo_loss, orpo_terms
+
+ logits, tokens, comp, seq = _fixture(seed=1)
+ model = _Fixed(logits)
+ t, c, s = mx.array(tokens), mx.array(comp), mx.array(seq)
+
+ def f(m):
+ return orpo_loss(*orpo_terms(m, t, c, s), 0.1)[0]
+
+ _, grads = nn.value_and_grad(model, f)(model)
+ g = np.array(grads["logits"])
+ rng = np.random.default_rng(5)
+ eps = 1e-4
+ for _ in range(12):
+ idx = (rng.integers(0, logits.shape[0]), rng.integers(0, logits.shape[1] - 1),
+ rng.integers(0, logits.shape[2]))
+ hi, lo = logits.copy(), logits.copy()
+ hi[idx] += eps
+ lo[idx] -= eps
+ fd = (_np_loss(*_np_terms(hi, tokens, comp, seq), 0.1)[0]
+ - _np_loss(*_np_terms(lo, tokens, comp, seq), 0.1)[0]) / (2 * eps)
+ assert g[idx] == pytest.approx(fd, abs=2e-4, rel=2e-2), idx
+
+
+class TestEdgeValues:
+ def _loss(self, a, b, nll=0.5, beta=0.1):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer.mlx_orpo import orpo_loss
+
+ loss, metrics = orpo_loss(mx.array(a), mx.array(b), mx.array(nll), beta)
+ return loss, metrics
+
+ def test_identical_pair_is_finite_log2(self):
+ loss, metrics = self._loss([-1.3, -0.2], [-1.3, -0.2])
+ assert loss.item() == pytest.approx(0.5 + 0.1 * math.log(2), rel=1e-6)
+ assert metrics["log_odds_chosen"].item() == pytest.approx(0.0, abs=1e-6)
+
+ @pytest.mark.parametrize("a, b", [([-50.0], [-60.0]), ([-1e-6], [-2.0]), ([-0.69], [-0.7])])
+ def test_extreme_and_near_zero_scores_are_finite_with_finite_gradients(self, a, b):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer.mlx_orpo import orpo_loss
+
+ ra, rb = np.array(a), np.array(b)
+ expected, _ = _np_loss(ra, rb, 0.5, 0.1)
+ loss, _ = self._loss(a, b)
+ assert loss.item() == pytest.approx(expected, rel=1e-4)
+ grad = mx.grad(lambda x, y: orpo_loss(x, y, mx.array(0.5), 0.1)[0], argnums=(0, 1))
+ ga, gb = grad(mx.array(a), mx.array(b))
+ assert np.isfinite(np.array(ga)).all() and np.isfinite(np.array(gb)).all()
+
+ def test_beta_scales_only_the_preference_term(self):
+ l1, _ = self._loss([-1.0], [-2.0], beta=0.1)
+ l2, _ = self._loss([-1.0], [-2.0], beta=0.3)
+ assert (l2.item() - 0.5) == pytest.approx(3 * (l1.item() - 0.5), rel=1e-5)
+
+ def test_nan_input_is_not_a_quiet_zero(self):
+ loss, _ = self._loss([float("nan")], [-1.0])
+ assert math.isnan(loss.item())
+
+
+# --------------------------------------------------------------------------
+# Training on a tiny random Llama
+# --------------------------------------------------------------------------
+
+_ORPO_YAML = """
+base: tiny-base
+task: orpo
+backend: mlx
+data:
+ train: ./x.jsonl
+ format: dpo
+ max_length: 128
+training:
+ epochs: 1
+ lr: 5e-3
+ orpo_beta: 0.1
+ quantization: none
+ lora: {r: 4, alpha: 8, dropout: 0.0}
+output: ./output
+"""
+
+
+def _tiny_llama_args():
+ from mlx_lm.models import llama
+
+ return 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=True,
+ )
+
+
+def _rows(n=8, prefix="q"):
+ return [{"prompt": f"{prefix}{i}:", "chosen": " good", "rejected": " bad"} for i in range(n)]
+
+
+def _wrapper(tmp_path, monkeypatch, model_seed=0, **training):
+ mx = pytest.importorskip("mlx.core")
+ pytest.importorskip("mlx_lm")
+ from mlx_lm.models import llama
+
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.mlx_orpo import MLXORPOTrainerWrapper
+
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ monkeypatch.chdir(tmp_path)
+ extra = "".join(f" {k}: {v}\n" for k, v in training.items())
+ text = _ORPO_YAML.replace(" orpo_beta: 0.1\n", " orpo_beta: 0.1\n" + extra)
+ cfg = load_config_from_string(text)
+ wrapper = MLXORPOTrainerWrapper(cfg)
+ mx.random.seed(model_seed)
+ wrapper.model = llama.Model(_tiny_llama_args())
+ wrapper.tokenizer = CharTokenizer()
+ wrapper._dataset = {"train": _rows(), "val": _rows(2, prefix="v")}
+ return wrapper
+
+
+def _flat(params):
+ from mlx.utils import tree_flatten
+
+ return {k: np.array(v) for k, v in tree_flatten(params)}
+
+
+class TestTraining:
+ def test_lora_trains_and_the_base_stays_frozen(self, tmp_path, monkeypatch):
+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2, gradient_accumulation_steps=1)
+ before = _flat(wrapper.model.parameters())
+ wrapper.train()
+ after = _flat(wrapper.model.parameters())
+ lora_b = [v for k, v in after.items() if k.endswith("lora_b")]
+ assert lora_b and any(np.abs(v).sum() > 0 for v in lora_b)
+ for name, value in before.items():
+ moved = name.replace(".weight", ".linear.weight")
+ key = name if name in after else moved
+ np.testing.assert_array_equal(after[key], value, err_msg=name)
+
+ def test_the_preference_is_learned_with_finite_components(self, tmp_path, monkeypatch):
+ wrapper = _wrapper(tmp_path, monkeypatch, epochs=6, batch_size=2,
+ gradient_accumulation_steps=1, warmup_ratio=0.0)
+ result = wrapper.train()
+ assert all(math.isfinite(x) for x in result["losses"])
+ assert result["val_reward_accuracy"] == pytest.approx(1.0)
+ assert result["val_log_odds_chosen"] > 0
+ assert result["skipped_identical_pairs"] == 0
+ meta = json.loads((tmp_path / "output" / "adapter_config.json").read_text())
+ assert (meta["task"], meta["orpo_beta"], meta["fine_tune_type"]) == ("orpo", 0.1, "lora")
+ assert not list((tmp_path / "output").glob("*.partial*"))
+
+ def test_training_moves_the_held_out_log_odds_against_the_untrained_model(
+ self, tmp_path, monkeypatch
+ ):
+ """The base model is its own control: same rows, before and after."""
+ from soup_cli.trainer.mlx_orpo import orpo_loss, orpo_terms
+
+ wrapper = _wrapper(tmp_path, monkeypatch, epochs=6, batch_size=2,
+ gradient_accumulation_steps=1, warmup_ratio=0.0)
+ examples, _ = wrapper._examples(_rows(2, prefix="v"), "val")
+
+ def held_out():
+ wrapper.model.eval()
+ _, metrics = orpo_loss(*orpo_terms(wrapper.model, *wrapper._batch_arrays(examples)),
+ 0.1)
+ return metrics["log_odds_chosen"].item()
+
+ before = held_out()
+ wrapper.train()
+ assert held_out() > before + 1.0
+
+ def test_ties_train_instead_of_being_skipped(self, tmp_path, monkeypatch):
+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2)
+ tie = {"prompt": "t:", "chosen": " same", "rejected": " same"}
+ wrapper._dataset["train"] = _rows(6) + [tie, dict(tie)]
+ result = wrapper.train()
+ assert result["skipped_identical_pairs"] == 0
+ assert all(math.isfinite(x) for x in result["losses"])
+
+ def test_two_micro_batches_equal_one_batch_after_an_sgd_update(self, tmp_path, monkeypatch):
+ 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 = _wrapper(path, monkeypatch, batch_size=batch_size,
+ gradient_accumulation_steps=accum, optimizer="sgd",
+ scheduler="constant", warmup_ratio=0.0, seed=4)
+ result = wrapper.train()
+ return result, _flat(wrapper.model.trainable_parameters())
+
+ one, w1 = run(tmp_path / "a", 2, 1, [[0, 1]])
+ two, w2 = run(tmp_path / "b", 1, 2, [[0], [1]])
+ assert len(one["losses"]) == len(two["losses"]) == 1
+ # The NLL is a token mean over the batch: two micro-batches of one pair
+ # average two per-pair means, one batch of two takes one mean over both
+ # pairs' tokens. With equal-length chosen sequences they coincide.
+ for name in w1:
+ np.testing.assert_allclose(w1[name], w2[name], atol=1e-6, err_msg=name)
+
+ def test_val_loss_is_the_row_weighted_mean_over_chunks(self, tmp_path, monkeypatch):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer import mlx_orpo
+
+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2, epochs=2)
+ wrapper._dataset["val"] = _rows(2, prefix="v") + [
+ {"prompt": "w:", "chosen": " bad", "rejected": " good"}
+ ]
+ result = wrapper.train()
+ examples, _ = wrapper._examples(wrapper._dataset["val"], "val")
+ wrapper.model.eval()
+ per_row = []
+ for example in examples:
+ arrays = wrapper._batch_arrays([example])
+ loss, _ = wrapper._loss(wrapper.model, arrays, "val", mx.arange(1))
+ per_row.append(loss.item())
+ assert result["val_loss"] == pytest.approx(sum(per_row) / 3, rel=1e-4)
+ assert mlx_orpo.MLXORPOTrainerWrapper.fail_on_nonfinite
+
+ def test_a_nonfinite_loss_stops_the_run(self, tmp_path, monkeypatch):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer import mlx_orpo
+
+ real = mlx_orpo.orpo_terms
+
+ def poisoned(*args, **kwargs):
+ a, b, nll = real(*args, **kwargs)
+ return a * mx.array(float("nan")), b, nll
+
+ monkeypatch.setattr(mlx_orpo, "orpo_terms", poisoned)
+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2)
+ with pytest.raises(FloatingPointError, match="nonfinite loss"):
+ wrapper.train()
+
+
+class TestResume:
+ def _first_run(self, tmp_path, monkeypatch):
+ wrapper = _wrapper(tmp_path / "a", monkeypatch, batch_size=2, epochs=3, seed=1)
+ fresh = wrapper.train()
+ return tmp_path / "a" / "output" / "adapters.safetensors", fresh
+
+ def test_resume_from_its_own_adapter(self, tmp_path, monkeypatch):
+ checkpoint, fresh = self._first_run(tmp_path, monkeypatch)
+ resumed = _wrapper(tmp_path / "b", monkeypatch, batch_size=2, seed=1)
+ result = resumed.train(resume_from_checkpoint=str(checkpoint))
+ assert result["losses"][0] < fresh["losses"][0]
+
+ @pytest.mark.parametrize("change, match", [
+ ({"task": "dpo"}, "task='dpo'"),
+ ({"model": "other-base"}, "belongs to base"),
+ (None, "no adapter_config.json"),
+ ])
+ def test_mismatched_or_missing_metadata_is_refused(self, tmp_path, monkeypatch, change, match):
+ checkpoint, _ = self._first_run(tmp_path, monkeypatch)
+ meta = checkpoint.parent / "adapter_config.json"
+ if change is None:
+ meta.unlink()
+ else:
+ meta.write_text(json.dumps({**json.loads(meta.read_text()), **change}))
+ resumed = _wrapper(tmp_path / "b", monkeypatch, batch_size=2, seed=1)
+ with pytest.raises(ValueError, match=match):
+ resumed.train(resume_from_checkpoint=str(checkpoint))
+
+
+class TestFreshProcessReload:
+ def test_scores_reproduce_and_the_adapter_has_an_effect(self, tmp_path, monkeypatch):
+ mx = pytest.importorskip("mlx.core")
+ from soup_cli.trainer.mlx_orpo import orpo_terms
+
+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2, epochs=3)
+ base_path = tmp_path / "base.safetensors"
+ wrapper.model.save_weights(str(base_path))
+ wrapper.train()
+ examples, _ = wrapper._examples(_rows(2, prefix="v"), "val")
+ tokens, completion, sequence = (np.array(x) for x in wrapper._batch_arrays(examples))
+ wrapper.model.eval()
+ a, b, nll = orpo_terms(wrapper.model, *wrapper._batch_arrays(examples))
+ mx.eval(a, b, nll)
+ np.save(tmp_path / "batch.npy", np.stack([tokens, completion, sequence]))
+
+ script = textwrap.dedent(f"""
+ import json, sys
+ import numpy as np
+ import mlx.core as mx
+ from mlx_lm.models import llama
+ from mlx_lm.tuner.utils import load_adapters
+ sys.path.insert(0, {str(tmp_path)!r})
+ from soup_cli.trainer.mlx_orpo import orpo_terms
+ 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=True)
+ model = llama.Model(args)
+ model.load_weights({str(base_path)!r})
+ if sys.argv[1] == "adapter":
+ load_adapters(model, {str(tmp_path / "output")!r})
+ model.eval()
+ t, c, s = (mx.array(x) for x in np.load({str(tmp_path / "batch.npy")!r}))
+ a, b, nll = orpo_terms(model, t, c, s)
+ print(json.dumps({{"a": a.tolist(), "b": b.tolist(), "nll": nll.item()}}))
+ """)
+ def run(mode):
+ out = subprocess.run([sys.executable, "-c", script, mode], capture_output=True,
+ text=True, check=True, timeout=300)
+ return json.loads(out.stdout.strip().splitlines()[-1])
+
+ reloaded, base = run("adapter"), run("base")
+ np.testing.assert_allclose(reloaded["a"], np.array(a), rtol=1e-5, atol=1e-6)
+ np.testing.assert_allclose(reloaded["b"], np.array(b), rtol=1e-5, atol=1e-6)
+ assert reloaded["nll"] == pytest.approx(nll.item(), rel=1e-5)
+ assert abs(np.array(base["a"]) - np.array(reloaded["a"])).max() > 1e-3
+
+
+# --------------------------------------------------------------------------
+# Config and dispatch
+# --------------------------------------------------------------------------
+
+
+class TestConfig:
+ def _load(self, top="", training=""):
+ """`training` lines replace the fixture's own line for the same key."""
+ from soup_cli.config.loader import load_config_from_string
+
+ text = _ORPO_YAML.replace("backend: mlx\n", "backend: mlx\n" + top)
+ for line in training.splitlines(keepends=True):
+ key = line.split(":", 1)[0]
+ own = [x for x in text.splitlines(keepends=True) if x.split(":", 1)[0] == key]
+ text = text.replace(own[0], line) if own else text.replace(
+ " orpo_beta: 0.1\n", " orpo_beta: 0.1\n" + line
+ )
+ return load_config_from_string(text)
+
+ def test_orpo_on_mlx_loads_and_dispatches(self):
+ from soup_cli.trainer.mlx_orpo import MLXORPOTrainerWrapper
+ from soup_cli.trainer.mlx_routing import get_mlx_trainer
+
+ cfg = self._load()
+ assert (cfg.task, cfg.backend, cfg.training.orpo_beta) == ("orpo", "mlx", 0.1)
+ assert get_mlx_trainer("orpo") is MLXORPOTrainerWrapper
+
+ @pytest.mark.parametrize("top, training, match", [
+ ("", " quantization: 8bit\n", "quantization='8bit'"),
+ ("modality: vision\n", "", "modality='vision'"),
+ ("", " lora: {r: 0}\n", "lora.r must be at least 1"),
+ ("", " loraplus_lr_ratio: 16\n", "loraplus_lr_ratio"),
+ ])
+ def test_unsupported_combinations_are_refused_at_load(self, top, training, match):
+ with pytest.raises(Exception, match=match):
+ self._load(top, training)
+
+ def test_the_preference_alias_is_refused_explicitly(self):
+ from soup_cli.config.loader import load_config_from_string
+
+ alias = (_ORPO_YAML.replace("task: orpo", "task: preference")
+ .replace(" orpo_beta: 0.1\n", " preference_loss: orpo\n"))
+ with pytest.raises(Exception, match="task='preference' has no trainer"):
+ load_config_from_string(alias)
+
+ def test_the_transformers_route_is_unchanged(self):
+ from soup_cli.config.loader import load_config_from_string
+
+ text = _ORPO_YAML.replace("backend: mlx", "backend: transformers")
+ cfg = load_config_from_string(text.replace(" orpo_beta: 0.1\n", " orpo_beta: 0.25\n"))
+ assert (cfg.backend, cfg.training.orpo_beta) == ("transformers", 0.25)
+
+ def test_doctor_reports_ignored_settings(self):
+ from soup_cli.config.backend_support import check_config
+
+ cfg = self._load(training=" use_galore: true\n")
+ assert {e.field for e in check_config(cfg)} == {"training.use_galore"}
+
+ 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
+ from soup_cli.trainer.mlx_orpo import MLXORPOTrainerWrapper
+
+ buffer = StringIO()
+ monkeypatch.setattr(mlx_dpo, "console", Console(file=buffer, width=400))
+ MLXORPOTrainerWrapper(self._load(training=" use_galore: true\n"))._check_unsupported()
+ assert "MLX backend ignores: GaLore" in _strip_ansi(buffer.getvalue())
diff --git a/tests/test_trl_preference_config_contract.py b/tests/test_trl_preference_config_contract.py
index 7881574d..d77c3fef 100644
--- a/tests/test_trl_preference_config_contract.py
+++ b/tests/test_trl_preference_config_contract.py
@@ -264,9 +264,10 @@ 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"
+ # The native MLX loops build no trl config: their `max_prompt_length=`
+ # goes to their own tokenizer (tests/test_mlx_dpo.py and
+ # tests/test_mlx_orpo.py pin the cap).
+ and path.stem not in ("mlx_dpo", "mlx_orpo")
}
assert users, "found no trainer passing a prompt-length cap — did the path move?"
uncovered = sorted(users - set(_ALL_SIX))