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(train): refuse silently ignored gdpo_variant (#1309) (#1515)
Tal7a3edf056ee4
diff --git a/changelog.d/0.75.1/1515.changed.md b/changelog.d/0.75.1/1515.changed.mdnew file mode 100644index 00000000..67a3f219--- /dev/null+++ b/changelog.d/0.75.1/1515.changed.md@@ -0,0 +1 @@+- **Breaking: `training.gdpo_variant` is now refused at config load.** Every non-null value is refused, including `standard`, `length_normalized` and `margin`; unset and null still load. On supported TRL versions (0.29 and later) the setting previously loaded but silently changed nothing because `DPOTrainer.dpo_loss` no longer exists. Remove `gdpo_variant` and use plain `task: dpo` for `standard`; `task: simpo` is the nearest, not identical, objective for `length_normalized`; `margin` has no equivalent. GDPO metadata no longer advertises live wiring, and the retained legacy helper raises instead of silently ignoring a missing loss hook. No new loss implementation is added; no shipped recipe, template or example sets this field. (#1309 by @taljeon in #1515)diff --git a/docs/training.md b/docs/training.mdindex 578ee6ea..08f0f281 100644--- a/docs/training.md+++ b/docs/training.md@@ -736,17 +736,20 @@ masking it out. Both are gated to the SFT-family of tasks.## EBFT / GDPO Loss Variants-Generalised DPO (`gdpo_variant: standard | length_normalized | margin`) loads for-`task: dpo` and `task: preference`, but on the trl versions Soup supports (0.29 and-later) it is not applied: the run trains exactly as it would without the field, and-nothing says so ([#1309](https://github.com/MakazhanAlpamys/Soup/issues/1309)).-The config shape:+**`training.gdpo_variant` is refused at config load**+([#1309](https://github.com/MakazhanAlpamys/Soup/issues/1309)). This breaks configs+that set `standard`, `length_normalized`, or `margin`: previously they loaded but+silently trained the default loss, because supported TRL versions (0.29 and later)+do not expose the `DPOTrainer.dpo_loss` hook. Every non-null value is refused;+unset and null still load. No shipped recipe, template or example sets the field.++Remove `gdpo_variant` to train plain `task: dpo` for `standard`. For+`length_normalized`, `task: simpo` is the nearest objective, **not an identical+replacement**. `margin` has no equivalent. Plain DPO, without a GDPO setting:```yaml-# DPO with GDPO length_normalizedtask: dpotraining:- gdpo_variant: length_normalizeddpo_beta: 0.1```@@ -1943,7 +1946,15 @@ The cross-validator rejects `task='distill'` without `teacher_model`, and reject## EBFT + GDPO (BETA, v0.52.0)-Generalized DPO lands as `training.gdpo_variant ∈ {standard, length_normalized, margin}` — gated to `task ∈ {dpo, preference}`; on trl 0.29 and later it is not applied ([#1309](https://github.com/MakazhanAlpamys/Soup/issues/1309)). Energy-Based Fine-Tuning (`training.ebft_variant ∈ {structured, strided}` + `training.ebft_temperature`) is refused at config load ([#1230](https://github.com/MakazhanAlpamys/Soup/issues/1230)): its term had no causal shift, so it rewarded copying the input, and shifted it would duplicate the cross-entropy. See [EBFT / GDPO Loss Variants](#ebft--gdpo-loss-variants).+Both fields are refused at config load. `training.gdpo_variant` silently did+nothing on supported TRL versions because the DPO loss hook no longer exists+([#1309](https://github.com/MakazhanAlpamys/Soup/issues/1309)); remove it and use+plain DPO for `standard`, or SimPO as the nearest (not identical) objective for+`length_normalized`. `margin` has no equivalent. Energy-Based Fine-Tuning+(`training.ebft_variant` + `training.ebft_temperature`) remains refused+([#1230](https://github.com/MakazhanAlpamys/Soup/issues/1230)): its term had no+causal shift, so it rewarded copying the input, and shifted it would duplicate+the cross-entropy. See [EBFT / GDPO Loss Variants](#ebft--gdpo-loss-variants).## gpt-oss `reasoning_effort` + `train_on_eot` (v0.52.0)diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 6b3b61cd..f9594144 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1964,8 +1964,9 @@ class TrainingConfig(BaseModel):]] = Field(default=None,description=(- "Generalized DPO variant. DPO-family-task-only; replaces the "- "trainer's preference loss with the selected objective."+ "Refused at config load (#1309): supported TRL versions lack the "+ "DPO loss hook. Remove this field; use plain task: dpo for standard, "+ "or task: simpo as the nearest (not identical) length-normalized objective."),)# Part F — MoE expert quantization + router-only training@@ -2785,7 +2786,7 @@ class TrainingConfig(BaseModel):that every non-null value -- not only the two the ``Literal`` accepts --gets this message instead of one pointing at a refused value. Thekernel and the hook in ``utils/ebft_gdpo.py`` stay in place,- unreachable; GDPO, which shares that module, is unaffected.+ unreachable; GDPO is separately refused by #1309."""if v is not None:raise ValueError(@@ -2802,6 +2803,20 @@ class TrainingConfig(BaseModel):)return v+ @field_validator("gdpo_variant", mode="before")+ @classmethod+ def _refuse_gdpo_variant(cls, value: Any) -> Any:+ """#1309 — refuse every non-null value before the Literal/task/backend gates."""+ if value is not None:+ raise ValueError(+ "training.gdpo_variant is refused (#1309): supported TRL versions "+ "do not expose the dpo_loss hook, so this setting was accepted but "+ "ignored. Remove gdpo_variant to use plain task: dpo for standard; "+ "task: simpo is the nearest (not identical) length-normalized "+ "objective; margin has no equivalent."+ )+ return value+@field_validator("label_names")@classmethoddef _validate_label_names(cls, v):@@ -5769,7 +5784,7 @@ class SoupConfig(BaseModel):@model_validator(mode="after")def _validate_gdpo_compat(self) -> "SoupConfig":- """v0.52.0 Part E — ``gdpo_variant`` requires DPO/preference, non-MLX."""+ """Legacy task/backend gate; #1309 refuses non-null values at the field first."""if self.training.gdpo_variant is None:return selffrom soup_cli.utils.ebft_gdpo import validate_gdpo_compatdiff --git a/src/soup_cli/utils/ebft_gdpo.py b/src/soup_cli/utils/ebft_gdpo.pyindex 74d681d9..e11a7d5b 100644--- a/src/soup_cli/utils/ebft_gdpo.py+++ b/src/soup_cli/utils/ebft_gdpo.py@@ -57,17 +57,17 @@ _GDPO_METADATA: Mapping[str, GDPOSpec] = MappingProxyType({"standard": GDPOSpec(name="standard",description="Standard GDPO (general preference objective)",- live_wired=True, # v0.53.2 #135 — kernel + DPO attach hook shipped.+ live_wired=False, # #1309 — supported TRL versions lack the dpo_loss hook.),"length_normalized": GDPOSpec(name="length_normalized",description="Length-normalized GDPO (SimPO-style normalisation)",- live_wired=True, # v0.53.2 #135+ live_wired=False, # #1309 — refused at config load.),"margin": GDPOSpec(name="margin",description="Margin-augmented GDPO (DPO + margin term)",- live_wired=True, # v0.53.2 #135+ live_wired=False, # #1309 — refused at config load.),})@@ -227,10 +227,11 @@ def attach_ebft_compute_loss(trainer: object, tcfg: object) -> bool:def attach_gdpo_compute_loss(trainer: object, tcfg: object) -> bool:- """Wrap TRL's ``DPOTrainer.dpo_loss`` so a GDPO variant is used (v0.53.2 #135).+ """Wrap a legacy ``dpo_loss`` hook (v0.53.2 #135), not supported TRL trainers.- No-op when ``tcfg.gdpo_variant`` is None. Replaces the trainer's- ``dpo_loss`` method (the stable TRL hook returning losses, chosen rewards,+ Config load refuses every non-null ``gdpo_variant`` (#1309); this legacy+ helper and kernel remain for isolated tests. No-op when the variant is None.+ Replaces a trainer's ``dpo_loss`` method (returning losses, chosen rewards,rejected rewards) with a thin wrapper that calls :func:`apply_gdpo_loss`.Returns:@@ -248,7 +249,10 @@ def attach_gdpo_compute_loss(trainer: object, tcfg: object) -> bool:margin = float(raw_margin) if raw_margin is not None else 0.0original = getattr(trainer, "dpo_loss", None)if original is None:- return False+ raise ValueError(+ "cannot attach GDPO: the trainer lacks dpo_loss (#1309); "+ "training.gdpo_variant is refused at config load"+ )def wrapped(policy_chosen_logps,diff --git a/tests/test_issue1230_refuse_ebft.py b/tests/test_issue1230_refuse_ebft.pyindex eaf218de..e4757f5f 100644--- a/tests/test_issue1230_refuse_ebft.py+++ b/tests/test_issue1230_refuse_ebft.py@@ -23,9 +23,9 @@ reference". This file pins:* ``ebft_temperature`` on its own no longer tells the user to set the refusedfield;* ``soup train`` and ``soup doctor --config`` stop at config load;-* the controls that must NOT change: null and unset still load, the EBFT hook- stays a no-op for every config that loads, and GDPO -- which shares- ``utils/ebft_gdpo.py`` -- loads, gates and computes exactly as before;+* null and unset still load, and the EBFT hook stays a no-op for every config+ that loads; GDPO is now separately refused at load by #1309, while its+ isolated legacy kernel and hook stay unchanged;* every shipped recipe, template and example still loads;* no doc still shows ``ebft_variant`` as a setting to copy."""@@ -270,11 +270,11 @@ def _loadable_configs() -> list[str]:"base: some-model\ntask: sft\ndata: {train: ./data.jsonl}\n",_yaml("null"),"base: some-model\ntask: dpo\ndata: {train: ./data.jsonl}\n"- "training: {gdpo_variant: margin}\n",+ "training: {gdpo_variant: null}\n",][email protected]("text", _loadable_configs(), ids=["sft", "sft-null", "dpo-gdpo"])[email protected]("text", _loadable_configs(), ids=["sft", "sft-null", "dpo-null"])def test_the_ebft_hook_is_a_no_op_for_every_config_that_loads(text):"""``SFTTrainerWrapper.train()`` calls this hook unconditionally; with thefield refused it can never install the term."""@@ -290,41 +290,35 @@ def test_the_ebft_hook_is_a_no_op_for_every_config_that_loads(text):assert not getattr(trainer, "_soup_ebft_wrapped", False)-class TestGdpoIsUnchanged:- """GDPO shares ``utils/ebft_gdpo.py``; this change leaves its config- surface, gates and kernel as they were. These controls do not show that- GDPO reaches the real DPO trainer: on trl 0.29 it does not (#1309), and- the fix for #1309 owns these tests if it changes what loads."""+class TestGdpoRefusedWithLegacyKernelUnchanged:+ """#1309 takes the config controls handed over by #1279. The legacy+ kernel remains, but a loaded config can no longer activate its hook."""@pytest.mark.parametrize("variant", GDPO_VARIANTS)- def test_every_gdpo_variant_still_loads_on_dpo(self, variant):- cfg = load_config_from_string(- "base: some-model\ntask: dpo\ndata: {train: ./data.jsonl}\n"- f"training: {{gdpo_variant: {variant}, dpo_beta: 0.2}}\n"- )- assert cfg.training.gdpo_variant == variant- assert cfg.training.dpo_beta == 0.2- assert cfg.training.ebft_variant is None+ def test_every_gdpo_variant_is_refused_on_dpo(self, variant):+ with pytest.raises(ValueError, match="#1309"):+ load_config_from_string(+ "base: some-model\ntask: dpo\ndata: {train: ./data.jsonl}\n"+ f"training: {{gdpo_variant: {variant}, dpo_beta: 0.2}}\n"+ )@pytest.mark.parametrize("variant", GDPO_VARIANTS)- def test_every_gdpo_variant_still_loads_on_preference(self, variant):- cfg = load_config_from_string(- "base: some-model\ntask: preference\ndata: {train: ./data.jsonl}\n"- f"training: {{preference_loss: dpo, gdpo_variant: {variant}}}\n"- )- assert cfg.training.gdpo_variant == variant+ def test_every_gdpo_variant_is_refused_on_preference(self, variant):+ with pytest.raises(ValueError, match="#1309"):+ load_config_from_string(+ "base: some-model\ntask: preference\ndata: {train: ./data.jsonl}\n"+ f"training: {{preference_loss: dpo, gdpo_variant: {variant}}}\n"+ )- def test_the_gdpo_task_gate_is_unchanged(self):- with pytest.raises(- ValueError, match=r"gdpo_variant requires task in \('dpo', 'preference'\)"- ):+ def test_refusal_precedes_the_gdpo_task_gate(self):+ with pytest.raises(ValueError, match="#1309"):load_config_from_string("base: some-model\ntask: sft\ndata: {train: ./data.jsonl}\n""training: {gdpo_variant: standard}\n")- def test_the_gdpo_backend_gate_is_unchanged(self):- with pytest.raises(ValueError, match="gdpo_variant is not supported on backend=mlx"):+ def test_refusal_precedes_the_gdpo_backend_gate(self):+ with pytest.raises(ValueError, match="#1309"):load_config_from_string("base: some-model\ntask: dpo\nbackend: mlx\ndata: {train: ./data.jsonl}\n""training: {gdpo_variant: standard}\n"@@ -368,11 +362,8 @@ class TestGdpoIsUnchanged:assert torch.allclose(loss, expected, atol=1e-7), (loss, expected)@pytest.mark.parametrize("variant", GDPO_VARIANTS)- def test_the_gdpo_hook_still_installs_from_a_loaded_config(self, variant):- """The hook's own behaviour, on a stub trainer that exposes- ``dpo_loss``. trl 0.29's ``DPOTrainer`` has no ``dpo_loss``, so on the- real trainer the hook returns False today (#1309); this change leaves- GDPO exactly as it was."""+ def test_the_legacy_gdpo_hook_still_installs_on_a_stub(self, variant):+ """Test the retained hook directly, not through a config that cannot load."""import torchfrom soup_cli.utils.ebft_gdpo import apply_gdpo_loss, attach_gdpo_compute_loss@@ -380,12 +371,9 @@ class TestGdpoIsUnchanged:def trl_dpo_loss(*args, **kwargs):raise AssertionError("the GDPO wrapper replaces TRL's dpo_loss")- cfg = load_config_from_string(- "base: some-model\ntask: dpo\ndata: {train: ./data.jsonl}\n"- f"training: {{gdpo_variant: {variant}, dpo_beta: 0.2}}\n"- )+ training = SimpleNamespace(gdpo_variant=variant, dpo_beta=0.2)trainer = SimpleNamespace(dpo_loss=trl_dpo_loss)- assert attach_gdpo_compute_loss(trainer, cfg.training) is True+ assert attach_gdpo_compute_loss(trainer, training) is Trueassert trainer._soup_gdpo_wrapped is Truepc = torch.tensor([-1.0, -2.5])diff --git a/tests/test_issue1309_refuse_gdpo.py b/tests/test_issue1309_refuse_gdpo.pynew file mode 100644index 00000000..bf8532bc--- /dev/null+++ b/tests/test_issue1309_refuse_gdpo.py@@ -0,0 +1,128 @@+"""#1309: refuse GDPO at config load instead of silently using TRL's loss."""++from types import SimpleNamespace++import pytest+import typer+from pydantic import ValidationError+from typer.testing import CliRunner++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import TrainingConfig+from soup_cli.utils.ebft_gdpo import GDPO_VARIANTS, attach_gdpo_compute_loss, get_gdpo_spec+from tests.conftest import strip_ansi+++def _yaml(value: str, *, task: str = "dpo", backend: str = "transformers") -> str:+ return (+ f"base: some-model\ntask: {task}\nbackend: {backend}\n"+ "data: {train: ./data.jsonl}\n"+ f"training: {{gdpo_variant: {value}}}\n"+ )+++ "value", ["standard", "length_normalized", "margin", "bogus", "''", "true", "1", "[]", "{}"]+)+def test_loader_refuses_every_non_null_value(value):+ with pytest.raises(ValueError, match=r"training.gdpo_variant is refused \(#1309\)"):+ load_config_from_string(_yaml(value))++[email protected]("value", [*sorted(GDPO_VARIANTS), "bogus", "", True, 1, [], {}])+def test_direct_construction_refuses_every_non_null_value(value):+ with pytest.raises(ValidationError, match="#1309") as excinfo:+ TrainingConfig(gdpo_variant=value)+ assert [error["loc"] for error in excinfo.value.errors()] == [("gdpo_variant",)]+++ "task,backend", [("sft", "transformers"), ("dpo", "mlx"), ("dpo", "unsloth")]+)+def test_refusal_precedes_task_and_backend_gates(task, backend):+ with pytest.raises(ValueError, match="#1309"):+ load_config_from_string(_yaml("standard", task=task, backend=backend))++[email protected]("loss", ["dpo", "simpo", "orpo", "ipo", "bco"])+def test_preference_loss_cannot_silently_ignore_gdpo(loss):+ text = _yaml("margin", task="preference").replace(+ "gdpo_variant: margin", f"gdpo_variant: margin, preference_loss: {loss}"+ )+ with pytest.raises(ValueError, match="#1309"):+ load_config_from_string(text)+++def test_error_explains_alternatives_without_claiming_equivalence():+ with pytest.raises(ValueError) as excinfo:+ load_config_from_string(_yaml("length_normalized"))+ message = str(excinfo.value)+ for part in [+ "dpo_loss",+ "Remove gdpo_variant",+ "task: dpo",+ "task: simpo",+ "not identical",+ "margin has no equivalent",+ ]:+ assert part in message++[email protected]("task", ["dpo", "preference", "simpo", "sft"])[email protected]("value", ["null", "Null", "NULL", "~", ""])+def test_null_keeps_plain_training_loadable(task, value):+ text = _yaml(value, task=task)+ if task == "preference":+ text = text.replace("gdpo_variant:", "preference_loss: dpo, gdpo_variant:")+ assert load_config_from_string(text).training.gdpo_variant is None+++def test_unset_keeps_plain_dpo_loadable_and_hook_inactive():+ cfg = load_config_from_string("base: x\ntask: dpo\ndata: {train: ./data.jsonl}\n")+ assert cfg.training.gdpo_variant is None+ assert attach_gdpo_compute_loss(object(), cfg.training) is False+ assert TrainingConfig().gdpo_variant is None+ assert TrainingConfig(gdpo_variant=None).gdpo_variant is None+++def test_metadata_does_not_advertise_live_wiring():+ assert all(not get_gdpo_spec(variant).live_wired for variant in GDPO_VARIANTS)+++def test_legacy_hook_cannot_silently_ignore_missing_surface():+ with pytest.raises(ValueError, match="dpo_loss.*#1309"):+ attach_gdpo_compute_loss(object(), SimpleNamespace(gdpo_variant="standard"))+++def _write_config(tmp_path):+ path = tmp_path / "soup.yaml"+ path.write_text(_yaml("standard"), encoding="utf-8")+ return path++[email protected]("extra_args", [[], ["--dry-run"]], ids=["train", "dry-run"])+def test_train_stops_before_model_setup(tmp_path, monkeypatch, extra_args):+ from soup_cli.cli import app++ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ monkeypatch.chdir(tmp_path)+ path = _write_config(tmp_path)+ result = CliRunner().invoke(app, ["train", "--config", str(path), *extra_args])+ output = " ".join(strip_ansi(result.output).split())+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "training -> gdpo_variant" in output+ assert "#1309" in output+ for later_line in ("Training Setup", "LoRA applied", "Loading model"):+ assert later_line not in output+++def test_doctor_reports_config_as_unloadable(tmp_path, capsys):+ from soup_cli.commands.doctor import doctor++ path = _write_config(tmp_path)+ with pytest.raises(typer.Exit) as excinfo:+ doctor(nccl=False, disk=False, config=str(path))+ assert excinfo.value.exit_code == 2+ output = " ".join(strip_ansi(capsys.readouterr().out).split())+ assert "training -> gdpo_variant" in output+ assert "#1309" in outputdiff --git a/tests/test_v0520.py b/tests/test_v0520.pyindex d5490bc6..c5b4c6f1 100644--- a/tests/test_v0520.py+++ b/tests/test_v0520.py@@ -679,12 +679,11 @@ class TestEbftGdpoUtils:validate_gdpo_compat(task="sft", backend="transformers")def test_get_ebft_spec(self):- # v0.53.2 #135 lifted EBFT + GDPO live_wired flags from False to True- # (kernel + attach hooks shipped).+ # #1309: the GDPO kernel exists, but the supported TRL hook does not.from soup_cli.utils.ebft_gdpo import get_ebft_spec, get_gdpo_specassert get_ebft_spec("structured").live_wired is True- assert get_gdpo_spec("margin").live_wired is True+ assert get_gdpo_spec("margin").live_wired is Falsedef test_apply_ebft_loss_lifted_in_v0532(self):"""v0.52.0 shipped both as NotImplementedError stubs; v0.53.2 #135@@ -726,19 +725,19 @@ class TestEbftGdpoSchema:with pytest.raises(Exception, match="#1230"):load_config_from_string(yaml)- def test_gdpo_dpo_happy(self):- cfg = load_config_from_string(- "base: x\ntask: dpo\ndata: {train: ./d.jsonl}\n"- "training: {gdpo_variant: length_normalized}\n"- )- assert cfg.training.gdpo_variant == "length_normalized"+ def test_gdpo_dpo_refused(self):+ with pytest.raises(ValueError, match="#1309"):+ load_config_from_string(+ "base: x\ntask: dpo\ndata: {train: ./d.jsonl}\n"+ "training: {gdpo_variant: length_normalized}\n"+ )def test_gdpo_on_sft_rejected(self):yaml = ("base: x\ntask: sft\ndata: {train: ./d.jsonl}\n""training: {gdpo_variant: standard}\n")- with pytest.raises(Exception, match="dpo"):+ with pytest.raises(Exception, match="#1309"):load_config_from_string(yaml)diff --git a/tests/test_v0532.py b/tests/test_v0532.pyindex e264fcab..a12d46f8 100644--- a/tests/test_v0532.py+++ b/tests/test_v0532.py@@ -613,12 +613,13 @@ class TestAttachGdpoComputeLoss:tcfg = type("Tcfg", (), {"gdpo_variant": None})()assert attach_gdpo_compute_loss(trainer, tcfg) is False- def test_no_op_when_trainer_lacks_dpo_loss(self) -> None:+ def test_refuses_when_trainer_lacks_dpo_loss(self) -> None:from soup_cli.utils.ebft_gdpo import attach_gdpo_compute_losstrainer = object()tcfg = type("Tcfg", (), {"gdpo_variant": "standard"})()- assert attach_gdpo_compute_loss(trainer, tcfg) is False+ with pytest.raises(ValueError, match="dpo_loss.*#1309"):+ attach_gdpo_compute_loss(trainer, tcfg)def test_wraps_and_returns_trl_shape(self) -> None:torch = _torch_or_skip()