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
fix(config): refuse data.chat_template with backend: mlx (#2051)
vaputa95844295aff5
diff --git a/changelog.d/0.76.0/2051.fixed.md b/changelog.d/0.76.0/2051.fixed.mdnew file mode 100644index 00000000..4f489658--- /dev/null+++ b/changelog.d/0.76.0/2051.fixed.md@@ -0,0 +1,5 @@+- `backend: mlx` no longer silently ignores `data.chat_template` on SFT, DPO or ORPO: the MLX+ trainer renders the model's shipped template only, so a prefix-stable+ override was dropped and the run failed the mask's prefix-stability check+ deep inside training. The combination is now refused at config load+ (#2075 reported by @feloau in #2051).diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 09b94f9e..8b5dfb0a 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -171,8 +171,8 @@ training:- **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.+- **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`, LoRA+ and `data.chat_template` (MLX renders the model's shipped template only; use `backend: transformers` to apply an override).+- **Not applied on MLX:** 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 MLXdiff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex a1974cf1..48171ec5 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -1153,6 +1153,8 @@ before the model loads, and the message lists the known names.Raw Jinja strings are validated: null bytes / >64KB / filesystem-touching directives (`{% include %}`, `{% import %}`, `{% from %}`, `{% macro %}`, `{% extends %}`) are rejected at config-load.+`backend: mlx` also refuses `data.chat_template` at config-load — the MLX trainer renders the model's shipped template only, so the override would be silently dropped; `backend: transformers` applies it.+### OOM-probe auto batch size```yamldiff --git a/src/soup_cli/config/backend_support.py b/src/soup_cli/config/backend_support.pyindex c5476a31..954391dc 100644--- a/src/soup_cli/config/backend_support.py+++ b/src/soup_cli/config/backend_support.py@@ -226,26 +226,10 @@ _NOT_DPO_GAPS = frozenset({_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,- ),)#: 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,- ),-)+_MLX_ORPO: tuple[SupportEntry, ...] = _MLX_DPO#: ``(task, backend, modality)`` -> the settings that combination does not honour.diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 815e0c7c..5a46507b 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -5559,7 +5559,7 @@ class SoupConfig(BaseModel):@model_validator(mode="after")def _validate_chat_template_supported_tasks(self) -> "SoupConfig":- """Reject chat-template overrides on trainers that never render chat."""+ """Reject overrides on tasks or backends that never apply them."""unsupported = {"pretrain","embedding",@@ -5582,6 +5582,13 @@ class SoupConfig(BaseModel):"data.chat_template is not used by "f"task={self.task!r}; remove it or choose a conversational training task")+ # MLX SFT and preference trainers render the model's shipped template only.+ if self.data.chat_template is not None and self.backend == "mlx":+ raise ValueError(+ "data.chat_template is not applied by backend: mlx — the MLX "+ "trainer renders the model's shipped template only. Remove "+ "data.chat_template, or use backend: transformers."+ )return self@model_validator(mode="before")diff --git a/src/soup_cli/trainer/mlx_dpo.py b/src/soup_cli/trainer/mlx_dpo.pyindex 5aa7f9bf..0061cb3d 100644--- a/src/soup_cli/trainer/mlx_dpo.py+++ b/src/soup_cli/trainer/mlx_dpo.py@@ -354,11 +354,6 @@ class MLXDPOTrainerWrapper(MLXSFTTrainerWrapper):unsupported = []if tcfg.quantization == "8bit":unsupported.append("quantization=8bit (use mlx-community 4bit models)")- if self.config.data.chat_template:- unsupported.append(- f"data.chat_template (MLX {self.objective} renders with the model's own "- "template)"- )for name, label in (("use_galore", "GaLore"),("use_lorafa", "training.use_lorafa"),diff --git a/tests/test_mlx_chat_template_refusal.py b/tests/test_mlx_chat_template_refusal.pynew file mode 100644index 00000000..50efde8a--- /dev/null+++ b/tests/test_mlx_chat_template_refusal.py@@ -0,0 +1,83 @@+"""Regression tests for #1913 Finding A: `backend: mlx` silently ignored+`data.chat_template` — the MLX trainer renders the model's shipped template,+so a prefix-stable override was dropped and the run still failed the mask's+prefix-stability check (`ResponseMaskError`) deep inside training.++After the fix the combination is refused at config load with a message that+names the escape hatches (remove the override or use the transformers+backend).+"""++from __future__ import annotations++import pytest++from soup_cli.config.schema import SoupConfig++# Registered names and raw Jinja all take the same backend validation path.+TEMPLATES = ["chatml", "llama3", "{% for m in messages %}{{ m['content'] }}{% endfor %}"]+++class TestMlxChatTemplateRefusal:+ @pytest.mark.parametrize("task", ["sft", "dpo", "orpo"])+ @pytest.mark.parametrize("template", TEMPLATES)+ def test_mlx_with_chat_template_refused_at_config_load(self, template: str, task: str) -> None:+ with pytest.raises(ValueError) as exc_info:+ SoupConfig(+ base="test/model",+ task=task,+ backend="mlx",+ data={"train": "d.jsonl", "chat_template": template},+ training={"epochs": 1},+ )+ message = str(exc_info.value)+ assert "data.chat_template is not applied by backend: mlx" in message+ assert "backend: transformers" in message+ assert "Remove data.chat_template" in message++ @pytest.mark.parametrize("task", ["sft", "dpo", "orpo"])+ def test_empty_chat_template_still_loads_on_mlx(self, task: str) -> None:+ # The field validator normalises "" to None, which is not an override.+ config = SoupConfig(+ base="test/model",+ task=task,+ backend="mlx",+ data={"train": "d.jsonl", "chat_template": ""},+ training={"epochs": 1},+ )+ assert config.data.chat_template is None++ @pytest.mark.parametrize("task", ["sft", "dpo", "orpo"])+ @pytest.mark.parametrize("template", TEMPLATES)+ def test_transformers_backend_still_accepts_chat_template(+ self, template: str, task: str,+ ) -> None:+ # The override is real on the transformers backend; only mlx drops it.+ config = SoupConfig(+ base="test/model",+ task=task,+ backend="transformers",+ data={"train": "d.jsonl", "chat_template": template},+ training={"epochs": 1},+ )+ assert config.data.chat_template == template++ @pytest.mark.parametrize("task", ["sft", "dpo", "orpo"])+ def test_mlx_without_chat_template_still_allowed(self, task: str) -> None:+ config = SoupConfig(+ base="test/model",+ task=task,+ backend="mlx",+ data={"train": "d.jsonl"},+ training={"epochs": 1},+ )+ assert config.data.chat_template is None++ def test_unsloth_backend_still_accepts_chat_template(self) -> None:+ config = SoupConfig(+ base="test/model",+ task="sft",+ backend="unsloth",+ data={"train": "d.jsonl", "chat_template": "chatml"},+ )+ assert config.data.chat_template == "chatml"