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(preference): blend reference-free losses on the log-probs trl computes (#1425) (#1556)

UmranPros37f0b267bbc7
diff --git a/changelog.d/0.75.1/1556.changed.md b/changelog.d/0.75.1/1556.changed.md
new file mode 100644
index 00000000..f6da5917
--- /dev/null
+++ b/changelog.d/0.75.1/1556.changed.md
@@ -0,0 +1,7 @@
+- **A `simpo` + `orpo` blend now trains instead of refusing (#1425 by @umran666 in #1556).** #1513 made every blend refuse, because no trl 0.29 trainer puts per-sequence log-probs on the batch. The CPO (SimPO) and ORPO trainers both return theirs from `concatenated_forward`, so the wrapper now captures them there: a blend naming only `simpo` and `orpo` runs. Blends naming `dpo` or `ipo` still stop and name the terms — those trainers compute log-probs inline, publish only means, and need a frozen reference model this path does not build.
+
+ **Behaviour changes:**
+ - `{simpo: 0.7, orpo: 0.3}` is live on trl 0.29 where it previously stopped at step 0. `bco` mixed with anything is still rejected at config load.
+ - Each blended loss now reads its hyperparameters from the config rather than off the primary trainer, which is whichever loss has the larger weight. `training.simpo_gamma` and `training.orpo_beta` now reach their own term either way; before, `orpo_beta` could feed SimPO's beta and ORPO's odds-ratio weight was always `1.0`, so the same weights written in a different YAML order trained a different objective.
+ - In a blend, `simpo` and `orpo` are their preference terms only — without the likelihood term the standalone `preference_loss: simpo` / `orpo` runs carry. A `{simpo: 1.0}` blend is not the standalone SimPO loss, and `training.cpo_alpha` does not affect it. Use `training.preference_loss` for a full standalone loss.
+ - With `val_split` set, trl's `prediction_step` calls `get_batch_loss_metrics` directly, so eval reports the primary loss's own trl loss rather than the blend's value.
\ No newline at end of file
diff --git a/docs/training.md b/docs/training.md
index de15950d..069f8aaa 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -954,19 +954,36 @@ Mix DPO / SimPO / ORPO / IPO terms in one training run by setting
task: preference
training:
preference_loss_weights:
- dpo: 0.6
- simpo: 0.4
+ simpo: 0.6
+ orpo: 0.4
```
The combine wrapper computes a weighted sum via the in-tree
`compute_dpo_term` / `compute_simpo_term` / `compute_orpo_term` /
-`compute_ipo_term` kernels. **On trl 0.29 no preference trainer puts the
-per-sequence log-probs those kernels need on the batch**, so a blend currently
-stops at the first step and names the terms it could not compute. Until the
-wrapper reads the logits from the trainer's own forward pass, do not configure
-`preference_loss_weights`: remove it and set `training.preference_loss` to the
-single loss you want. BCO cannot be mixed with paired losses (data
-format incompatible — rejected at config load).
+`compute_ipo_term` kernels. On trl 0.29 it reads the per-sequence log-probs
+those kernels need out of the primary trainer's own forward pass
+(`concatenated_forward`), so which blends train depends on which trainer is
+built:
+
+| Blend | Result on trl 0.29 |
+| --- | --- |
+| `simpo` + `orpo` | Trains. The CPO (SimPO) and ORPO trainers both return their per-sequence log-probs. |
+| anything naming `dpo` or `ipo` | Stops at the first step and names the terms. They need a frozen reference model this path does not build, so there are no reference log-probs to read — and their own trainers compute log-probs inline, publishing only means. |
+| `bco` mixed with anything | Rejected at config load (data format incompatible). |
+
+**What a term is.** In a blend, `simpo` and `orpo` are their *preference terms
+only* — the margin / odds-ratio objective — without the likelihood (NLL) term
+the standalone `preference_loss: simpo` / `preference_loss: orpo` runs carry. A
+`{simpo: 1.0}` blend is therefore not the same number as a `preference_loss:
+simpo` run, and `training.cpo_alpha` does not affect it. Use
+`training.preference_loss` when you want the full standalone loss. Each term
+does honour its own config field: `training.simpo_gamma` for SimPO,
+`training.orpo_beta` for ORPO, whichever loss has the larger weight or not.
+
+**Evaluation.** With `val_split` set, trl's `prediction_step` calls
+`get_batch_loss_metrics` directly, so the eval loss is the primary loss's own
+trl loss — not the blend's value. Training and evaluation therefore report
+different numbers for the same batch.
## MoE Model Support
@@ -1270,18 +1287,19 @@ training:
Gated to DPO-family tasks (`dpo`, `ipo`, or `preference` with `preference_loss in {dpo, ipo}`); transformers backend only. `dpo_ref_regen_epochs` is refused at config load: it never regenerated the reference. With LoRA there is no separate reference model to copy into, and the DPO-family trainers cannot run with `lora.r: 0`. The wiring is tracked in [#1345](https://github.com/MakazhanAlpamys/Soup/issues/1345).
-### Multi-objective preference loss (schema-only in v0.40.0)
+### Multi-objective preference loss
```yaml
task: preference
training:
- preference_loss_weights: {dpo: 0.7, bco: 0.3}
+ preference_loss_weights: {simpo: 0.7, orpo: 0.3}
```
Schema validates 2–5 entries summing to 1, and rejects `bco` mixed with a
-paired loss at config load. The runtime blend is **not** live on trl 0.29: the
-config loads, then training stops at the first step naming the terms it could
-not compute (see [Weighted Multi-Objective Preference Loss](#weighted-multi-objective-preference-loss)).
+paired loss at config load. On trl 0.29 a `simpo` + `orpo` blend trains; any
+blend naming `dpo` or `ipo` stops at the first step naming the terms it could
+not compute, because those trainers publish no per-sequence log-probs to read
+(see [Weighted Multi-Objective Preference Loss](#weighted-multi-objective-preference-loss)).
Set `training.preference_loss` for a single loss.
diff --git a/src/soup_cli/trainer/preference.py b/src/soup_cli/trainer/preference.py
index 774982ab..a5486d5e 100644
--- a/src/soup_cli/trainer/preference.py
+++ b/src/soup_cli/trainer/preference.py
@@ -149,6 +149,7 @@ class PreferenceTrainerWrapper:
from rich.console import Console as _Console
from soup_cli.utils.preference_combine import (
+ REF_FREE_LOSSES,
describe_blend,
validate_weight_compat,
)
@@ -179,7 +180,13 @@ class PreferenceTrainerWrapper:
raise ValueError(f"unknown primary preference loss: {primary!r}")
_Console().print(
f"[cyan]Multi-objective preference loss:[/] {describe_blend(weights)} "
- f"(primary: {primary})"
+ f"(primary: {primary}"
+ + (
+ "; simpo/orpo are preference terms only, without the NLL term"
+ if set(weights) <= REF_FREE_LOSSES
+ else ""
+ )
+ + ")"
)
self._active_weights = dict(weights)
return PrimaryWrapper(inner_cfg, **kwargs)
@@ -213,7 +220,19 @@ class PreferenceTrainerWrapper:
inner_trainer = getattr(self._inner, "trainer", None)
if inner_trainer is not None:
try:
- attach_weighted_preference_combine(inner_trainer, weights)
+ # #1425: capture the policy log-probs the primary
+ # trainer already computes (CPO / ORPO), then wrap
+ # compute_loss over them. A dpo/ipo primary has no
+ # such hook, and its blend still refuses.
+ from soup_cli.utils.preference_combine import (
+ attach_policy_logp_capture,
+ blend_loss_params,
+ )
+
+ attach_policy_logp_capture(inner_trainer)
+ attach_weighted_preference_combine(
+ inner_trainer, weights, blend_loss_params(self.config)
+ )
except (TypeError, ValueError) as exc:
# Schema validates weights at config load; runtime
# rejection should be loud — but fall through to the
diff --git a/src/soup_cli/utils/preference_combine.py b/src/soup_cli/utils/preference_combine.py
index e3ff5147..9a350256 100644
--- a/src/soup_cli/utils/preference_combine.py
+++ b/src/soup_cli/utils/preference_combine.py
@@ -25,7 +25,7 @@ from __future__ import annotations
import logging
import math
-from typing import TYPE_CHECKING, Dict, Mapping, Optional
+from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional
logger = logging.getLogger(__name__)
@@ -37,6 +37,23 @@ REF_MODEL_LOSSES: frozenset = frozenset({"dpo", "ipo"})
REF_FREE_LOSSES: frozenset = frozenset({"simpo", "orpo"})
UNPAIRED_LOSSES: frozenset = frozenset({"bco"})
+#: The beta the Soup SimPO wrapper builds with. Soup has no `beta` schema field
+#: for SimPO — `simpo.py` leaves `CPOConfig`'s own default in place — so this is
+#: the value trl's `CPOConfig` carries. DPO and IPO have their own fields
+#: (`dpo_beta`, `ipo_tau`), so `blend_loss_params` reads those instead; this
+#: constant is only SimPO's fallback. Reading beta off the primary trainer made
+#: the blend's objective depend on which loss happened to be named first
+#: (#1425 review); `tests/test_v05311.py` pins it against trl so a default change
+#: cannot drift silently.
+DEFAULT_BETA: float = 0.1
+
+#: Fallbacks for the two knobs `params` may omit. These mirror the schema
+#: defaults (`schema.py`: `simpo_gamma=0.5`, `orpo_beta=0.1`) so a blend
+#: attached without a config — an existing test harness, say — lands on the
+#: same objective the standalone loss would use.
+DEFAULT_SIMPO_GAMMA: float = 0.5
+DEFAULT_ORPO_ALPHA: float = 0.1
+
def validate_weight_compat(weights: Mapping[str, float]) -> None:
"""Enforce the BCO-incompatible-with-paired rule at runtime.
@@ -138,9 +155,14 @@ def compute_orpo_term(
"""Reference-free odds-ratio preference loss (ORPO).
Uses the response-log-prob formulation ``-log σ(log(p_w) - log(p_l) +
- log(1-p_l) - log(1-p_w))`` scaled by ``alpha``. Approximates the full
- ORPO loss without the SFT term — caller is expected to mix in SFT via
- its own weight if desired.
+ log(1-p_l) - log(1-p_w))`` scaled by ``alpha``.
+
+ This is the odds-ratio term only: it leaves out the NLL term that a
+ standalone ``preference_loss: orpo`` run adds (trl computes that NLL over
+ prompt plus response, ``orpo_trainer.py``). A blend of ``simpo`` and
+ ``orpo`` therefore trains neither loss's likelihood term — see the
+ "Weighted Multi-Objective Preference Loss" section in ``docs/training.md``
+ and #1425.
``pol_chosen`` / ``pol_rejected`` are *summed* sequence log-probs. On a real
sequence the summed log-prob is ≈ −45, so ``exp()`` underflows to 0 and the
@@ -201,7 +223,42 @@ def combine_losses(
return out
-def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, float]) -> bool:
+def blend_loss_params(cfg) -> dict:
+ """Each blended loss's own hyperparameters, read from the config (#1425).
+
+ The blend used to take ``beta`` / ``simpo_gamma`` / ``orpo_alpha`` off the
+ primary trainer, which is whichever loss has the larger weight — so
+ ``orpo_beta`` fed SimPO's beta on an ORPO-primary blend, ORPO's alpha was
+ always ``1.0`` because no trainer has an ``orpo_alpha`` attribute, and the
+ same weights written in a different YAML order trained a different
+ objective. Config is the only place these are unambiguous.
+
+ ``training.orpo_beta`` is ORPO's odds-ratio weight, so it becomes ORPO's
+ ``alpha`` here; ``training.simpo_gamma`` is SimPO's margin. DPO and IPO
+ have real beta fields (``dpo_beta``, ``ipo_tau``) that ``dpo.py`` and
+ ``ipo.py`` already pass to trl — read those too, or their terms would carry
+ a beta no config can reach (#1425 review). Only SimPO has no field of its
+ own, so it falls back to :data:`DEFAULT_BETA`.
+ """
+ tcfg = getattr(cfg, "training", None)
+ if tcfg is None: # defensive — a config always has `training`
+ return {}
+ return {
+ "dpo": {"beta": float(getattr(tcfg, "dpo_beta", DEFAULT_BETA))},
+ "ipo": {"beta": float(getattr(tcfg, "ipo_tau", DEFAULT_BETA))},
+ "simpo": {
+ "beta": DEFAULT_BETA,
+ "gamma": float(getattr(tcfg, "simpo_gamma", DEFAULT_SIMPO_GAMMA)),
+ },
+ "orpo": {"alpha": float(getattr(tcfg, "orpo_beta", DEFAULT_ORPO_ALPHA))},
+ }
+
+
+def attach_weighted_preference_combine(
+ trainer: object,
+ weights: Mapping[str, float],
+ params: Optional[Mapping[str, Mapping[str, float]]] = None,
+) -> bool:
"""v0.53.11 #68 — wrap inner trainer's ``compute_loss`` for TRUE weighted blend.
Replaces the v0.40.1 primary-loss approximation with a per-batch
@@ -220,6 +277,14 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
compute. It used to fall back to the v0.40.1 primary-loss scaling, which
trained only the highest-weighted loss while reporting a blended number.
+ ``params`` supplies each loss's own hyperparameters, keyed by loss name
+ (``{"simpo": {"beta": ..., "gamma": ...}, "orpo": {"alpha": ...}}``). It
+ must come from the config, not from the trainer: the trainer is whichever
+ loss has the larger weight, so reading ``beta`` / ``simpo_gamma`` off it
+ made the same weights in a different YAML order train a different
+ objective (#1425 review). Anything not supplied falls back to
+ :data:`DEFAULT_BETA`.
+
Idempotent: re-attaching detects the ``_soup_weighted_combine`` marker.
"""
validate_weight_compat(weights)
@@ -229,6 +294,7 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
if getattr(original, "_soup_weighted_combine", False):
return True
snapshot = dict(weights)
+ loss_params: Dict[str, Mapping[str, float]] = {k: dict(v) for k, v in (params or {}).items()}
def wrapped(model, inputs, return_outputs=False, **kwargs):
result = original(model, inputs, return_outputs=return_outputs, **kwargs)
@@ -237,12 +303,17 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
# to pass `outputs` through when the caller asked for it.
outputs = result[1] if return_outputs else None
- # True weighted-sum path: read per-batch logps from inputs OR the
- # trainer's last-batch state.
- pol_chosen = _read_logps(inputs, "policy_chosen_logps")
+ # True weighted-sum path: the per-batch logps, else the ones captured
+ # from the primary trainer's own forward pass (#1425).
+ captured = getattr(trainer, "_soup_policy_logps", None) or {}
+ pol_chosen = captured.get("policy_chosen_logps")
+ if pol_chosen is None:
+ pol_chosen = _read_logps(inputs, "policy_chosen_logps")
if pol_chosen is None:
pol_chosen = _read_logps(inputs, "chosen_logps")
- pol_rejected = _read_logps(inputs, "policy_rejected_logps")
+ pol_rejected = captured.get("policy_rejected_logps")
+ if pol_rejected is None:
+ pol_rejected = _read_logps(inputs, "policy_rejected_logps")
if pol_rejected is None:
pol_rejected = _read_logps(inputs, "rejected_logps")
ref_chosen = _read_logps(inputs, "reference_chosen_logps")
@@ -251,16 +322,22 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
ref_rejected = _read_logps(inputs, "reference_rejected_logps")
if ref_rejected is None:
ref_rejected = _read_logps(inputs, "ref_rejected_logps")
+ # Lengths come from the capture when it ran, else from the batch.
+ chosen_lens = captured.get("chosen_lens")
+ if chosen_lens is None:
+ chosen_lens = _read_lens(inputs, "chosen")
+ rejected_lens = captured.get("rejected_lens")
+ if rejected_lens is None:
+ rejected_lens = _read_lens(inputs, "rejected")
terms: dict = {}
if pol_chosen is not None and pol_rejected is not None:
- # v0.53.11 review fix (security HIGH) — explicit None check
- # before float(). The previous `or 0.1` idiom triggered tensor
- # truth-value evaluation when TRL stored these as zero-element
- # tensors instead of Python floats.
- beta_attr = getattr(trainer, "beta", None)
- beta = float(beta_attr) if beta_attr is not None else 0.1
+ # #1425 review: every hyperparameter comes from `params` (the
+ # config), never from the primary trainer. The trainer is whichever
+ # loss has the larger weight, so `getattr` here made {simpo: 0.5,
+ # orpo: 0.5} and {orpo: 0.5, simpo: 0.5} train different objectives.
for name in snapshot:
+ cfg_for_loss = loss_params.get(name, {})
try:
if name == "dpo":
if ref_chosen is None or ref_rejected is None:
@@ -269,7 +346,11 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
)
continue
terms["dpo"] = compute_dpo_term(
- pol_chosen, pol_rejected, ref_chosen, ref_rejected, beta
+ pol_chosen,
+ pol_rejected,
+ ref_chosen,
+ ref_rejected,
+ float(cfg_for_loss.get("beta", DEFAULT_BETA)),
)
elif name == "ipo":
if ref_chosen is None or ref_rejected is None:
@@ -278,28 +359,31 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
)
continue
terms["ipo"] = compute_ipo_term(
- pol_chosen, pol_rejected, ref_chosen, ref_rejected, beta
+ pol_chosen,
+ pol_rejected,
+ ref_chosen,
+ ref_rejected,
+ float(cfg_for_loss.get("beta", DEFAULT_BETA)),
)
elif name == "simpo":
- gamma_attr = getattr(trainer, "simpo_gamma", None)
- gamma = (
- float(gamma_attr) if gamma_attr is not None else 1.0
- )
terms["simpo"] = compute_simpo_term(
- pol_chosen, pol_rejected, beta, gamma
+ pol_chosen,
+ pol_rejected,
+ float(cfg_for_loss.get("beta", DEFAULT_BETA)),
+ float(cfg_for_loss.get("gamma", DEFAULT_SIMPO_GAMMA)),
+ chosen_lens=chosen_lens,
+ rejected_lens=rejected_lens,
)
elif name == "orpo":
- alpha_attr = getattr(trainer, "orpo_alpha", None)
- alpha = (
- float(alpha_attr) if alpha_attr is not None else 1.0
- )
- # Length-normalise when the batch carries response
- # lengths/labels — otherwise summed log-probs underflow
- # exp() and the odds-ratio correction degenerates.
+ # `orpo_beta` is ORPO's odds-ratio weight; `orpo_alpha`
+ # never existed on any trainer, so the term used 1.0
+ # regardless of the config.
terms["orpo"] = compute_orpo_term(
- pol_chosen, pol_rejected, alpha,
- chosen_lens=_read_lens(inputs, "chosen"),
- rejected_lens=_read_lens(inputs, "rejected"),
+ pol_chosen,
+ pol_rejected,
+ float(cfg_for_loss.get("alpha", DEFAULT_ORPO_ALPHA)),
+ chosen_lens=chosen_lens,
+ rejected_lens=rejected_lens,
)
elif name == "bco":
# BCO is data-format-incompatible — already rejected
@@ -341,6 +425,88 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
return True
+def attach_policy_logp_capture(trainer: object) -> bool:
+ """Record the policy log-probs trl already computes (#1425).
+
+ trl 0.29's CPO (the SimPO path) and ORPO trainers compute per-sequence
+ chosen/rejected log-probs inside ``concatenated_forward`` and hand them
+ straight back to ``get_batch_loss_metrics``; nothing puts them where a
+ weighted blend can read them, which is why every blend on trl 0.29 fell
+ through to the primary loss alone. trl's DPO/IPO trainers compute theirs
+ inline in ``compute_loss`` and publish only means, so they have no such
+ hook and return ``False`` here — their blends keep refusing.
+
+ The captured values are converted to **summed** log-probs using the batch's
+ own per-side ``chosen_labels`` / ``rejected_labels``, because the kernels in
+ this module take sums plus lengths. Whether trl handed over sums or averages
+ is not inspected: deriving the lengths and multiplying back gives the sum
+ either way. That multiply-back is only correct for the paths where trl
+ averaged — ``cpo_trainer.py`` averages for ``loss_type`` ``ipo``/``simpo``,
+ and ``orpo_trainer.py`` always averages. Soup's SimPO wrapper always builds
+ ``loss_type="simpo"``, so the averaging path is the live one today; a future
+ wrapper using ``sigmoid`` or ``hinge`` would return sums and this would
+ double-count the lengths.
+
+ Returns True when the capture is in place.
+ """
+ if not hasattr(trainer, "concatenated_forward"):
+ return False
+ original = trainer.concatenated_forward
+ if getattr(original, "_soup_logp_capture", False):
+ return True
+
+ def capturing(model, batch, *args, **kwargs):
+ out = original(model, batch, *args, **kwargs)
+ try:
+ chosen_logps, rejected_logps = out[0], out[1]
+ except (TypeError, IndexError, KeyError): # pragma: no cover — trl shape drift
+ # IndexError/TypeError: not a sequence (or too short). KeyError: a
+ # dict-shaped return, which older trl DPOTrainers used — let it fall
+ # through to the blend's refusal rather than raise out of a forward.
+ return out
+ _record_policy_logps(trainer, batch, chosen_logps, rejected_logps)
+ return out
+
+ capturing._soup_logp_capture = True
+ trainer.concatenated_forward = capturing
+ return True
+
+
+def _response_lengths(batch: Any, side: str) -> Any:
+ """Per-example response token count: everything not masked with ``-100``."""
+ labels = batch.get(f"{side}_labels") if hasattr(batch, "get") else None
+ if labels is None:
+ return None
+ try:
+ return (labels != -100).sum(dim=-1)
+ except (AttributeError, TypeError): # pragma: no cover — non-tensor labels
+ return None
+
+
+def _record_policy_logps(trainer, batch, chosen_logps, rejected_logps) -> None:
+ """Store summed policy log-probs and the lengths that produced them."""
+ chosen_lens = _response_lengths(batch, "chosen")
+ rejected_lens = _response_lengths(batch, "rejected")
+ if chosen_lens is None or rejected_lens is None:
+ # No per-side labels: keep what trl gave us and say we did not normalise.
+ trainer._soup_policy_logps = {
+ "policy_chosen_logps": chosen_logps,
+ "policy_rejected_logps": rejected_logps,
+ "chosen_lens": None,
+ "rejected_lens": None,
+ }
+ return
+ # trl averaged; the kernels take sums, so put the length back in.
+ trainer._soup_policy_logps = {
+ "policy_chosen_logps": chosen_logps * chosen_lens.to(chosen_logps.dtype),
+ "policy_rejected_logps": rejected_logps * rejected_lens.to(
+ rejected_logps.dtype,
+ ),
+ "chosen_lens": chosen_lens,
+ "rejected_lens": rejected_lens,
+ }
+
+
def _read_logps(obj, name: str):
"""Read a log-prob tensor from a mapping / object — TRL inputs vary."""
if obj is None:
diff --git a/tests/test_v05311.py b/tests/test_v05311.py
index 65a9cfff..ad430ad8 100644
--- a/tests/test_v05311.py
+++ b/tests/test_v05311.py
@@ -944,6 +944,278 @@ class TestTrueWeightedCombine:
assert "cannot compute dpo on this step (computed: simpo)" in message, message
+class TestTheCaptureReadsTrlOwnLogProbs:
+ """#1425 — the blend must run on the log-probs trl already computed.
+
+ The fake trainer below has trl 0.29 CPO's shape: `concatenated_forward`
+ returns per-sequence log-probs and the batch carries per-side `*_labels`.
+ trl averages those log-probs for simpo/ipo; the kernels here take sums
+ plus lengths, so the capture puts the length back in and the kernel
+ divides it out again. The net must equal trl's own value.
+ """
+
+ @staticmethod
+ def _cpo(chosen_avg, rejected_avg, chosen_len, rejected_len, prompt=2):
+ import torch
+
+ class _Cpo:
+ loss_type = "simpo"
+ beta = 0.1
+ simpo_gamma = 0.5
+ orpo_alpha = 1.0
+
+ def concatenated_forward(self, model, batch, *a, **k):
+ return (
+ torch.tensor(chosen_avg),
+ torch.tensor(rejected_avg),
+ None,
+ None,
+ torch.tensor(0.0),
+ )
+
+ def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
+ # The primary loss the blend replaces; its value must not
+ # survive into the result.
+ return torch.tensor(99.0)
+
+ # Tensors, like trl's real batch: the capture reads response lengths off
+ # these, and a list of ints would silently take the no-labels path.
+ batch = {
+ "chosen_labels": torch.tensor(
+ [[-100] * prompt + list(range(chosen_len)) for _ in range(2)],
+ ),
+ "rejected_labels": torch.tensor(
+ [[-100] * prompt + list(range(rejected_len)) for _ in range(2)],
+ ),
+ }
+ return _Cpo(), batch
+
+ def test_a_cpo_style_trainer_produces_the_weighted_sum(self):
+ import torch
+
+ from soup_cli.utils.preference_combine import (
+ attach_policy_logp_capture,
+ attach_weighted_preference_combine,
+ compute_orpo_term,
+ compute_simpo_term,
+ )
+
+ trainer, batch = self._cpo([-0.5, -0.5], [-1.0, -1.0], 4, 4)
+ assert attach_policy_logp_capture(trainer) is True
+ # Params as `PreferenceTrainerWrapper.setup` supplies them (#1425 review):
+ # the trainer's own attributes are no longer read, so a test that wants a
+ # specific objective has to name it here.
+ attach_weighted_preference_combine(
+ trainer,
+ {"simpo": 0.7, "orpo": 0.3},
+ {"simpo": {"beta": 0.1, "gamma": 0.5}, "orpo": {"alpha": 1.0}},
+ )
+ trainer.concatenated_forward(None, batch) # the capture runs here
+
+ out = float(trainer.compute_loss(model=None, inputs=batch))
+ assert out != pytest.approx(99.0)
+
+ # trl gave -0.5 / -1.0 averaged over 4 tokens, i.e. sums of -2 / -4.
+ lens = torch.tensor([4, 4])
+ expected = 0.7 * float(
+ compute_simpo_term(
+ torch.tensor([-2.0, -2.0]), torch.tensor([-4.0, -4.0]), 0.1, 0.5,
+ chosen_lens=lens, rejected_lens=lens,
+ ),
+ ) + 0.3 * float(
+ compute_orpo_term(
+ torch.tensor([-2.0, -2.0]), torch.tensor([-4.0, -4.0]), 1.0,
+ chosen_lens=lens, rejected_lens=lens,
+ ),
+ )
+ assert out == pytest.approx(expected, rel=1e-4), (out, expected)
+
+ def test_the_sum_reproduces_trls_own_averaged_value(self):
+ """The round trip through sums must be a no-op: trl's averages and ours
+ must give the same SimPO term."""
+ import torch
+
+ from soup_cli.utils.preference_combine import (
+ _record_policy_logps,
+ compute_simpo_term,
+ )
+
+ trainer = object.__new__(type("T", (), {}))
+ chosen_avg = torch.tensor([-0.4, -0.6])
+ rejected_avg = torch.tensor([-0.9, -1.1])
+ # Padded to one width, as a collator emits; the per-row count of
+ # non -100 entries is still 5 and 3.
+ batch = {
+ "chosen_labels": torch.tensor([
+ [-100, -100] + list(range(5)),
+ [-100, -100] + list(range(3)) + [-100, -100],
+ ]),
+ "rejected_labels": torch.tensor([
+ [-100, -100] + list(range(7)),
+ [-100, -100] + list(range(2)) + [-100] * 5,
+ ]),
+ }
+ _record_policy_logps(trainer, batch, chosen_avg, rejected_avg)
+ stored = trainer._soup_policy_logps
+ ours = compute_simpo_term(
+ stored["policy_chosen_logps"], stored["policy_rejected_logps"], 0.1, 0.5,
+ chosen_lens=stored["chosen_lens"], rejected_lens=stored["rejected_lens"],
+ )
+ # trl's own SimPO loss works directly on the averages it produced, with
+ # no lengths: it already normalised. Dividing them again here (as an
+ # earlier version of this control did) is not trl's formula.
+ theirs = compute_simpo_term(chosen_avg, rejected_avg, 0.1, 0.5)
+ assert float(ours) == pytest.approx(float(theirs), rel=1e-6)
+
+ def test_changing_only_the_secondary_loss_changes_the_loss(self):
+ """The second open box on #1425: same primary, different secondary."""
+ from soup_cli.utils.preference_combine import (
+ attach_policy_logp_capture,
+ attach_weighted_preference_combine,
+ )
+
+ def blended(weights):
+ trainer, batch = self._cpo([-0.5, -0.5], [-1.0, -1.0], 4, 4)
+ attach_policy_logp_capture(trainer)
+ attach_weighted_preference_combine(trainer, weights)
+ trainer.concatenated_forward(None, batch)
+ return float(trainer.compute_loss(model=None, inputs=batch))
+
+ assert blended({"simpo": 0.6, "orpo": 0.4}) != pytest.approx(
+ blended({"simpo": 0.7, "orpo": 0.3}), rel=1e-9
+ )
+
+ def test_the_blend_does_not_read_parameters_off_the_trainer(self):
+ """Config wins over the trainer's attributes (#1425 review).
+
+ The trainer is whichever loss has the larger weight, so `getattr` here
+ made the same weights in a different YAML order train a different
+ objective. Changing the trainer's attributes must change nothing now.
+ """
+ from soup_cli.utils.preference_combine import (
+ attach_policy_logp_capture,
+ attach_weighted_preference_combine,
+ )
+
+ def blended(overrides=None):
+ trainer, batch = self._cpo([-0.5, -0.5], [-1.0, -1.0], 4, 4)
+ for attr, value in (overrides or {}).items():
+ setattr(trainer, attr, value)
+ attach_policy_logp_capture(trainer)
+ attach_weighted_preference_combine(
+ trainer,
+ {"simpo": 0.5, "orpo": 0.5},
+ {"simpo": {"beta": 0.1, "gamma": 0.5}, "orpo": {"alpha": 0.1}},
+ )
+ trainer.concatenated_forward(None, batch)
+ return float(trainer.compute_loss(model=None, inputs=batch))
+
+ baseline = blended()
+ # Every attribute the old code read off the trainer, made hostile.
+ for overrides in (
+ {"beta": 7.0},
+ {"simpo_gamma": 9.0},
+ {"orpo_alpha": 4.0},
+ {"beta": 7.0, "simpo_gamma": 9.0, "orpo_alpha": 4.0},
+ ):
+ assert blended(overrides) == pytest.approx(baseline, rel=1e-9), overrides
+
+ def test_the_blend_reads_each_loss_parameters_from_the_config(self):
+ """`params` is what reaches each kernel, so the secondary loss's own
+ field moves the blend even when it is not the primary."""
+ from soup_cli.utils.preference_combine import (
+ attach_policy_logp_capture,
+ attach_weighted_preference_combine,
+ )
+
+ def blended(params):
+ trainer, batch = self._cpo([-0.5, -0.5], [-1.0, -1.0], 4, 4)
+ attach_policy_logp_capture(trainer)
+ attach_weighted_preference_combine(
+ trainer, {"simpo": 0.5, "orpo": 0.5}, params
+ )
+ trainer.concatenated_forward(None, batch)
+ return float(trainer.compute_loss(model=None, inputs=batch))
+
+ base = {"simpo": {"beta": 0.1, "gamma": 0.5}, "orpo": {"alpha": 0.1}}
+ assert blended({**base, "orpo": {"alpha": 0.9}}) != pytest.approx(
+ blended(base), rel=1e-9
+ )
+ assert blended({**base, "simpo": {"beta": 0.1, "gamma": 3.0}}) != pytest.approx(
+ blended(base), rel=1e-9
+ )
+ assert blended({**base, "simpo": {"beta": 0.5, "gamma": 0.5}}) != pytest.approx(
+ blended(base), rel=1e-9
+ )
+
+ def test_a_dpo_primary_has_no_hook_and_still_refuses(self):
+ import torch
+
+ from soup_cli.utils.preference_combine import (
+ attach_policy_logp_capture,
+ attach_weighted_preference_combine,
+ )
+
+ class _Dpo:
+ beta = 0.1
+
+ def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
+ return torch.tensor(2.0)
+
+ trainer = _Dpo()
+ assert attach_policy_logp_capture(trainer) is False
+ attach_weighted_preference_combine(trainer, {"dpo": 0.7, "simpo": 0.3})
+ with pytest.raises(ValueError, match="cannot compute"):
+ trainer.compute_loss(model=None, inputs={})
+
+ def test_attaching_twice_is_a_no_op(self):
+ from soup_cli.utils.preference_combine import attach_policy_logp_capture
+
+ trainer, _ = self._cpo([-0.5, -0.5], [-1.0, -1.0], 4, 4)
+ assert attach_policy_logp_capture(trainer) is True
+ first = trainer.concatenated_forward
+ assert attach_policy_logp_capture(trainer) is True
+ assert trainer.concatenated_forward is first
+
+ def test_a_batch_without_per_side_labels_keeps_trls_values(self):
+ """No labels means no lengths; the capture must not invent any."""
+ import torch
+
+ from soup_cli.utils.preference_combine import _record_policy_logps
+
+ trainer = object.__new__(type("T", (), {}))
+ chosen_avg = torch.tensor([-0.5, -0.5])
+ rejected_avg = torch.tensor([-1.0, -1.0])
+ _record_policy_logps(
+ trainer, {"concatenated_labels": None}, chosen_avg, rejected_avg,
+ )
+ stored = trainer._soup_policy_logps
+ assert stored["chosen_lens"] is None
+ assert stored["policy_chosen_logps"] is chosen_avg
+
+ def test_the_installed_cpo_still_returns_its_own_logps(self):
+ """Pin the hook this capture wraps (trl 0.29, read from source)."""
+ from pathlib import Path
+
+ import trl
+
+ candidates = [
+ Path(trl.__file__).parent / "experimental" / "cpo" / "cpo_trainer.py",
+ Path(trl.__file__).parent / "trainer" / "cpo_trainer.py",
+ ]
+ sources = [p.read_text(encoding="utf-8") for p in candidates if p.is_file()]
+ assert sources, "trl ships no cpo_trainer.py to pin the capture against"
+ source = "\n".join(sources)
+ assert "def concatenated_forward(" in source, (
+ "trl's CPO no longer has concatenated_forward, so #1425's capture "
+ "has no hook and a blend falls back to refusing"
+ )
+ assert "chosen_logps" in source and "rejected_logps" in source, (
+ "trl's CPO concatenated_forward no longer returns per-side log-probs; "
+ "re-derive #1425's capture against the new shape"
+ )
+
+
class TestOnARealTrlTrainer:
"""The stub trainer above is why this passed: it is the only way the wrapper
sees log-probs. On a real trl 0.29 trainer the batch carries none, so a blend
@@ -1024,6 +1296,243 @@ class TestOnARealTrlTrainer:
assert "dpo" in message and "simpo" in message, message
assert "preference_loss_weights" in message, message
+ def test_a_reference_free_blend_on_a_real_trainer_is_the_weighted_sum(
+ self, tmp_path, monkeypatch,
+ ):
+ """Pin the `attach_policy_logp_capture` call in `setup()` (#1425 review).
+
+ Every other blend test attaches the capture itself on a fake trainer, so
+ deleting the one line in `PreferenceTrainerWrapper.setup` that installs
+ it left them all green while no real blend would compute anything.
+ """
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.preference import PreferenceTrainerWrapper
+ from soup_cli.utils.preference_combine import compute_orpo_term
+
+ monkeypatch.chdir(tmp_path)
+ base = self._tiny_model_dir(tmp_path)
+ cfg = load_config_from_string(
+ f"base: {base.as_posix()}\ntask: preference\n"
+ "data: {train: ./unused.jsonl, format: dpo, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 2\n quantization: none\n"
+ " preference_loss_weights: {simpo: 0.7, orpo: 0.3}\n"
+ " orpo_beta: 0.4\n simpo_gamma: 1.5\n"
+ " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"
+ )
+ rows = [
+ {"prompt": "what is one plus one ?", "chosen": "two",
+ "rejected": "one plus one is three"},
+ {"prompt": "hello there", "chosen": "hi there hello", "rejected": "no"},
+ ]
+ wrapper = PreferenceTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": rows})
+ trainer = wrapper.trainer
+ batch = trainer._prepare_inputs(next(iter(trainer.get_train_dataloader())))
+
+ blended = trainer.compute_loss(trainer.model, batch)
+ # trl's own, unwrapped forward on the same batch.
+ chosen, rejected = type(trainer).concatenated_forward(
+ trainer, trainer.model, batch,
+ )[:2]
+ # The config's own fields, not their defaults: ORPO's alpha is
+ # `training.orpo_beta`, and reading a hardcoded 1.0 here is the bug
+ # this test existed to catch (#1425 review).
+ assert float(trainer.simpo_gamma) == 1.5 # the SimPO wrapper's own
+ simpo = trainer.cpo_loss(chosen, rejected)[0].mean()
+ orpo = compute_orpo_term(chosen, rejected, 0.4) # training.orpo_beta
+ assert float(blended) == pytest.approx(float(0.7 * simpo + 0.3 * orpo), rel=1e-6)
+ blended.backward()
+ assert any(
+ p.grad is not None and float(p.grad.abs().sum()) > 0
+ for p in trainer.model.parameters() if p.requires_grad
+ )
+ wrapper.train() # completes instead of stopping at step 0
+
+ @pytest.mark.parametrize(
+ ("weights", "field", "low", "high"),
+ [
+ ("{simpo: 0.7, orpo: 0.3}", "orpo_beta", 0.1, 0.9),
+ ("{orpo: 0.7, simpo: 0.3}", "simpo_gamma", 0.5, 3.0),
+ ],
+ )
+ def test_the_secondary_loss_reads_its_own_config_field(
+ self, tmp_path, monkeypatch, weights, field, low, high,
+ ):
+ """A blend's secondary term must honour its own field, not the
+ primary trainer's attributes (#1425 review)."""
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.preference import PreferenceTrainerWrapper
+
+ losses = []
+ for i, value in enumerate((low, high)):
+ sub = tmp_path / f"r{i}"
+ sub.mkdir()
+ monkeypatch.chdir(sub)
+ base = self._tiny_model_dir(sub)
+ cfg = load_config_from_string(
+ f"base: {base.as_posix()}\ntask: preference\n"
+ "data: {train: ./unused.jsonl, format: dpo, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 2\n quantization: none\n"
+ f" preference_loss_weights: {weights}\n {field}: {value}\n"
+ " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"
+ )
+ wrapper = PreferenceTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": [
+ {"prompt": "what is one plus one ?", "chosen": "two",
+ "rejected": "one plus one is three"},
+ {"prompt": "hello there", "chosen": "hi there hello", "rejected": "no"},
+ ]})
+ trainer = wrapper.trainer
+ batch = trainer._prepare_inputs(next(iter(trainer.get_train_dataloader())))
+ losses.append(float(trainer.compute_loss(trainer.model, batch)))
+ assert losses[0] != pytest.approx(losses[1], rel=1e-9), (field, losses)
+
+ def test_the_same_weights_in_either_order_train_the_same_objective(
+ self, tmp_path, monkeypatch,
+ ):
+ """SimPO's beta must come from the config, not the primary trainer.
+
+ Under an ORPO primary, `trainer.beta` is `orpo_beta` (0.7 here), so a
+ beta read off the trainer would silently scale SimPO's term by it. Only
+ a real trainer exposes that attribute, which is why the fake-trainer
+ test cannot catch this one (#1425 review).
+ """
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.preference import PreferenceTrainerWrapper
+
+ losses = []
+ for i, weights in enumerate(("{simpo: 0.5, orpo: 0.5}", "{orpo: 0.5, simpo: 0.5}")):
+ sub = tmp_path / f"r{i}"
+ sub.mkdir()
+ monkeypatch.chdir(sub)
+ base = self._tiny_model_dir(sub)
+ cfg = load_config_from_string(
+ f"base: {base.as_posix()}\ntask: preference\n"
+ "data: {train: ./unused.jsonl, format: dpo, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 2\n quantization: none\n"
+ f" preference_loss_weights: {weights}\n"
+ " orpo_beta: 0.7\n simpo_gamma: 2.0\n"
+ " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"
+ )
+ wrapper = PreferenceTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": [
+ {"prompt": "what is one plus one ?", "chosen": "two",
+ "rejected": "one plus one is three"},
+ {"prompt": "hello there", "chosen": "hi there hello", "rejected": "no"},
+ ]})
+ trainer = wrapper.trainer
+ batch = trainer._prepare_inputs(next(iter(trainer.get_train_dataloader())))
+ losses.append(float(trainer.compute_loss(trainer.model, batch)))
+ assert losses[0] == pytest.approx(losses[1], rel=1e-6), losses
+
+ def test_the_setup_line_says_the_terms_are_margin_only(self, tmp_path, monkeypatch, capsys):
+ """Someone reading a training log never sees the docs (#1425 review).
+
+ Under (b) the blend's terms carry no NLL, so the `Multi-objective
+ preference loss:` line has to say so itself.
+ """
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.preference import PreferenceTrainerWrapper
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("COLUMNS", "200") # rich wraps, the phrase must not split
+
+ def build(weights):
+ cfg = load_config_from_string(
+ "base: ./unused\ntask: preference\n"
+ "data: {train: ./unused.jsonl, format: dpo, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 2\n quantization: none\n"
+ f" preference_loss_weights: {weights}\n"
+ " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"
+ )
+ PreferenceTrainerWrapper(cfg, device="cpu")._build_multi_objective()
+ return capsys.readouterr().out
+
+ out = build("{simpo: 0.6, orpo: 0.4}")
+ assert "Multi-objective preference loss" in out, out
+ assert "preference terms only, without the NLL term" in out, out
+
+ # A blend that will refuse anyway has no reason to claim anything about
+ # its terms, and must not print the note.
+ out = build("{simpo: 0.6, dpo: 0.4}")
+ assert "Multi-objective preference loss" in out, out
+ assert "preference terms only" not in out, out
+
+ def test_setup_installs_the_capture_and_the_blend(self, tmp_path, monkeypatch):
+ """The two wrappers `setup()` must install, without building a trainer.
+
+ The real-trainer test above skips wherever trl's config cannot import,
+ and every other blend test attaches the capture itself — so deleting
+ `attach_policy_logp_capture(inner_trainer)` from `setup()` left the
+ whole file green while no real blend could compute anything (#1425
+ review). Injecting a fake inner trainer exercises the call site itself.
+ """
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.preference import PreferenceTrainerWrapper
+
+ class _FakeInner:
+ class trainer: # noqa: N801 — stands in for the trl trainer
+ beta = 7.0
+ simpo_gamma = 9.0
+
+ def concatenated_forward(self, model, batch, *a, **k):
+ raise AssertionError("not called here")
+
+ def compute_loss(self, model, inputs, return_outputs=False, **kw):
+ raise AssertionError("not called here")
+
+ def setup(self, dataset):
+ self.dataset = dataset
+
+ monkeypatch.chdir(tmp_path)
+ cfg = load_config_from_string(
+ "base: ./unused\ntask: preference\n"
+ "data: {train: ./unused.jsonl, format: dpo, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 2\n quantization: none\n"
+ " preference_loss_weights: {simpo: 0.7, orpo: 0.3}\n"
+ " orpo_beta: 0.9\n"
+ " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"
+ )
+ wrapper = PreferenceTrainerWrapper(cfg, device="cpu")
+ inner = _FakeInner()
+ wrapper._inner = inner
+ wrapper.setup({"train": []})
+
+ trainer = inner.trainer
+ assert getattr(trainer.concatenated_forward, "_soup_logp_capture", False), (
+ "setup() no longer installs the log-prob capture, so a real blend "
+ "computes nothing and falls through to refusing"
+ )
+ assert getattr(trainer.compute_loss, "_soup_weighted_combine", False), (
+ "setup() no longer installs the weighted blend"
+ )
+
+ # And the params it hands the blend come from the config, not the
+ # trainer's hostile `beta = 7.0` / `simpo_gamma = 9.0` above.
+ from soup_cli.utils.preference_combine import blend_loss_params
+
+ params = blend_loss_params(cfg)
+ assert params["orpo"]["alpha"] == 0.9, params
+ assert params["simpo"]["gamma"] == cfg.training.simpo_gamma, params
+ assert params["simpo"]["beta"] != 7.0, params
+
+ def test_the_default_beta_matches_the_one_the_wrappers_build(self):
+ """`DEFAULT_BETA` stands in for trl's CPOConfig default (the SimPO wrapper
+ sets no beta). Read the dataclass default itself: constructing a config
+ resolves bf16 and raises on a CPU-only runner."""
+ from soup_cli.trainer._trl_compat import resolve_trl_symbol
+ from soup_cli.utils.preference_combine import DEFAULT_BETA
+
+ try:
+ cpo_config_cls = resolve_trl_symbol("CPOConfig", "trl.experimental.cpo")
+ except Exception as exc: # noqa: BLE001 — a broken trl is not a failure
+ pytest.skip(f"this environment cannot import a trl CPO config: {exc}")
+
+ field = cpo_config_cls.__dataclass_fields__.get("beta")
+ if field is None:
+ pytest.skip("trl's CPOConfig no longer names a beta")
+ assert field.default == DEFAULT_BETA, (field.default, DEFAULT_BETA)
+
# ---------------------------------------------------------------------------
# v0.53.11 #127 — live EMA hook in callback