Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(preference): a dpo or ipo term under a simpo or orpo primary trains (#1425) (#1828)
Yang Baid09b95cd4572
diff --git a/changelog.d/0.76.0/1828.added.md b/changelog.d/0.76.0/1828.added.mdnew file mode 100644index 00000000..0eb23fba--- /dev/null+++ b/changelog.d/0.76.0/1828.added.md@@ -0,0 +1,13 @@+- **A `dpo` or `ipo` term in a `preference_loss_weights` blend now also trains when the largest+ weight is `simpo` or `orpo` (#1425 by @ybai08 in #1828).** Those primaries build trl's CPO and+ ORPO trainers, which run no frozen reference, so a blend such as `{simpo: 0.6, dpo: 0.4}`+ stopped at the first step. The blend now makes the reference itself: the trainer's own forward+ once more per step, without gradients and with the LoRA adapter switched off, which is the base+ model the adapter started from. A blend that names neither `dpo` nor `ipo` runs no extra+ forward. With `init_strategy: pissa` / `olora` / `loftq` or `relora_steps` the adapter-off model+ is not the starting model, so that combination is refused before the model is loaded, with+ the reason. The terms are computed on the primary trainer's batch, and the CPO / ORPO batches start+ with the BOS token where the `DPOTrainer`'s need not, so the same `dpo` term differs a little+ between a `simpo` and a `dpo` primary; `docs/training.md` says which reference and which tokens+ each primary uses. Try: `soup train --config soup.yaml` with `task: preference` and+ `training.preference_loss_weights: {simpo: 0.6, dpo: 0.4}`.diff --git a/docs/training.md b/docs/training.mdindex d4af41cc..b9db87b0 100644--- a/docs/training.md+++ b/docs/training.md@@ -991,14 +991,14 @@ The combine wrapper computes a weighted sum via the in-tree`compute_dpo_term` / `compute_simpo_term` / `compute_orpo_term` /`compute_ipo_term` kernels. The loss with the largest weight is the *primary*:its trl trainer is the one that is built, and on trl 0.29 the per-sequence-log-probs the kernels need are read out of that trainer's own forward pass. So-which blends train depends on which trainer is built:+log-probs the kernels need are read out of that trainer's own forward pass.+Where they come from 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 (`concatenated_forward`). || `dpo` or `ipo` has the largest weight, with any of `dpo`, `ipo`, `simpo`, `orpo` beside it | Trains. Both build trl's `DPOTrainer`: the policy log-probs are taken from the logits of its own forward pass, the reference log-probs from its `compute_ref_log_probs`. |-| `simpo` or `orpo` has the largest weight, and the blend names `dpo` or `ipo` | Stops at the first step and names the terms. `dpo` and `ipo` compare the policy with a frozen reference, and the CPO / ORPO trainers run none. Give `dpo` or `ipo` the largest weight instead. |+| `simpo` or `orpo` has the largest weight, and the blend names `dpo` or `ipo` | Trains. The CPO / ORPO trainers run no reference, so the blend runs one: the same forward once more, without gradients and with the LoRA adapter switched off. Refused with `init_strategy: pissa` / `olora` / `loftq` or `relora_steps`, where that is not the starting model ("Which reference" below). || `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@@ -1018,15 +1018,41 @@ whichever of them is the primary, so `{dpo: 0.5, ipo: 0.5}` and`{ipo: 0.5, dpo: 0.5}` are the same loss. `dpo_beta_schedule` is not availablewith a blend.-**Cost of a `dpo` / `ipo` primary.** The policy is run once, as in a-single-loss run. The reference is run twice per step: trl computes its own-reference log-probs inline and keeps only their means, so the blend asks the-trainer for them again (`compute_ref_log_probs`, without gradients). With-16-bit logits (bf16 or fp16 autocast) the blend also keeps one more tensor the-size of the logits for the backward pass, next to the one trl's own loss-keeps: 2 bytes × rows × tokens × vocabulary, where a batch of 4 pairs is 8-rows. That is about 250 MiB for 4 pairs of 512 tokens and a 32,000-token-vocabulary. With float32 logits it keeps none.+**Which reference.** Under a `dpo` / `ipo` primary it is trl's: the frozen+`ref` adapter, a copy of the adapter as it started. Under a `simpo` / `orpo`+primary it is the base model with the adapter switched off. For a new LoRA+adapter, whose update starts at zero, the two compute the same thing.++That holds while the base weights are the ones that were loaded, which covers+the default init (`init_strategy: random`), DoRA and rsLoRA.+`init_strategy: pissa`, `olora` and `loftq` (and `use_olora`) move part of+every targeted weight into the adapter and leave a residual in the base, and+`relora_steps` merges the adapter into the base at every restart; with the+adapter off the model is then no longer the one the policy started from. A+`dpo` / `ipo` term under a `simpo` / `orpo` primary is refused with either of+them, before the model is loaded. With such an init, give `dpo` or `ipo` the+largest weight: trl's copy of the adapter carries the residual's other half,+so its reference is still the starting model.++**Which tokens.** The terms are computed on the primary trainer's batch, and+the two trainer families do not render a row the same way: the CPO / ORPO+batches start with the tokenizer's BOS token, and the `DPOTrainer`'s need not+(with a plain tokenizer and no chat template they do not). An even split+between a reference loss and a reference-free one therefore depends on which+key comes first, because the first key is the primary.++**Cost.** The policy is run once per step, as in a single-loss run. A `dpo` /+`ipo` primary runs the reference twice: trl computes its own reference+log-probs inline and keeps only their means, so the blend asks the trainer for+them again (`compute_ref_log_probs`, without gradients). A `simpo` / `orpo`+primary runs the reference once, and only when the blend names `dpo` or `ipo`;+with `val_split` it runs on evaluation batches too.++With 16-bit logits (bf16 or fp16 autocast) a `dpo` / `ipo` primary also keeps+one more tensor the size of the logits for the backward pass, next to the one+trl's own loss keeps: 2 bytes × rows × tokens × vocabulary, where a batch of 4+pairs is 8 rows. That is about 250 MiB for 4 pairs of 512 tokens and a+32,000-token vocabulary. With float32 logits it keeps none.**Evaluation.** With `val_split` set and a `simpo` / `orpo` primary, trl's`prediction_step` calls `get_batch_loss_metrics` directly, so the eval loss is@@ -1367,10 +1393,9 @@ training:```Schema validates 2–5 entries summing to 1, and rejects `bco` mixed with a-paired loss at config load. On trl 0.29 a `simpo` + `orpo` blend trains, and-so does a blend whose largest weight is `dpo` or `ipo`. A `dpo` or `ipo` term-under a `simpo` / `orpo` primary stops at the first step naming the terms it-could not compute, because those trainers run no frozen reference+paired loss at config load. On trl 0.29 every blend of `dpo`, `ipo`, `simpo`+and `orpo` trains; which reference and which tokens the terms use depends on+the loss with the largest weight(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.pyindex 3932267e..2c997b77 100644--- a/src/soup_cli/trainer/preference.py+++ b/src/soup_cli/trainer/preference.py@@ -151,12 +151,13 @@ class PreferenceTrainerWrapper:from soup_cli.utils.preference_combine import (REF_FREE_LOSSES,describe_blend,+ primary_loss,validate_weight_compat,)weights = get_loss_weights(self.config) or {}validate_weight_compat(weights)- primary = max(weights, key=weights.get)+ primary = primary_loss(weights)# Build the primary inner wrapper using the same dispatch table.inner_cfg = _make_inner_cfg(self.config, primary)kwargs = {@@ -202,10 +203,16 @@ class PreferenceTrainerWrapper:# Advisory print + build are owned by ``_build_multi_objective``# so successive setup() calls (e.g. resume) emit one consistent# advisory line, not two.- from soup_cli.utils.preference_combine import validate_weight_compat+ from soup_cli.utils.preference_combine import (+ validate_adapter_off_reference,+ validate_weight_compat,+ )weights = get_loss_weights(self.config) or {}validate_weight_compat(weights)+ # #1425: also before anything is loaded -- a dpo / ipo term whose+ # adapter-off reference would not be the starting model.+ validate_adapter_off_reference(weights, self.config.training)if self._inner is None:self._inner = self._build_multi_objective()if self._inner is not None:@@ -230,9 +237,12 @@ class PreferenceTrainerWrapper:attach_policy_logp_capture,attach_reference_logp_capture,blend_loss_params,+ needs_reference_model,)- attach_policy_logp_capture(inner_trainer)+ attach_policy_logp_capture(+ inner_trainer, reference=needs_reference_model(weights)+ )attach_reference_logp_capture(inner_trainer)attach_weighted_preference_combine(inner_trainer, weights, blend_loss_params(self.config)diff --git a/src/soup_cli/utils/preference_combine.py b/src/soup_cli/utils/preference_combine.pyindex de4fddd9..a5cceedf 100644--- a/src/soup_cli/utils/preference_combine.py+++ b/src/soup_cli/utils/preference_combine.py@@ -77,6 +77,71 @@ def needs_reference_model(weights: Mapping[str, float]) -> bool:return bool(set(weights) & REF_MODEL_LOSSES)+def primary_loss(weights: Mapping[str, float]) -> str:+ """The loss whose trl trainer is built: the largest weight, and on a tie the+ first key."""+ return max(weights, key=weights.get)+++def validate_adapter_off_reference(weights: Mapping[str, float], training: Any) -> None:+ """Refuse a ``dpo`` / ``ipo`` term whose reference would not be the model+ the policy started from (#1425).++ Under a ``simpo`` / ``orpo`` primary the reference is the model with the+ LoRA adapter switched off. That is the starting model only while the base+ weights stay as they were loaded. PiSSA, OLoRA and LoftQ move part of every+ targeted weight into the adapter when it is created and leave a residual in+ the base, and a ReLoRA restart merges the adapter into the base; adapter-off+ is then another model, and the term would train against it without an+ error. A ``dpo`` / ``ipo`` primary is not affected by the init: trl's+ ``DPOTrainer`` keeps a frozen copy of the adapter as its reference.+ """+ primary = primary_loss(weights)+ if primary not in REF_FREE_LOSSES or not needs_reference_model(weights):+ return+ lora = getattr(training, "lora", None)+ init = getattr(lora, "init_strategy", "random")+ relora_steps = getattr(training, "relora_steps", None)+ other_primary = (+ "Give dpo or ipo the largest weight (trl's DPOTrainer keeps a frozen "+ "copy of the adapter as its reference)"+ )+ if getattr(lora, "use_olora", False):+ # The schema sets init_strategy='olora' beside it and refuses any+ # other value, so the way out is the flag, not the init.+ why = (+ "training.lora.use_olora=True (the same as init_strategy='olora') "+ "rewrites the base weights when the adapter is created"+ )+ fix = (+ f"{other_primary}, or set training.lora.use_olora to false and leave "+ "training.lora.init_strategy unset."+ )+ elif init != "random":+ why = (+ f"training.lora.init_strategy={init!r} rewrites the base weights when "+ "the adapter is created"+ )+ fix = f"{other_primary}, or set training.lora.init_strategy to 'random'."+ elif relora_steps is not None:+ why = (+ f"training.relora_steps={relora_steps} merges the adapter into the base "+ "weights at every restart"+ )+ fix = "Remove training.relora_steps, or remove the dpo / ipo term from the blend."+ else:+ return+ terms = ", ".join(sorted(set(weights) & REF_MODEL_LOSSES))+ article = "an" if primary[0] in "aeiou" else "a"+ raise ValueError(+ f"preference_loss_weights: cannot compute {terms} under {article} {primary} primary "+ f"with this adapter. dpo and ipo compare the policy with the model it "+ f"started from. The {primary} trainer keeps no copy of that model, so the "+ f"blend reads it by switching the LoRA adapter off, and {why}: with the "+ f"adapter off the model is no longer the one that was loaded. {fix}"+ )++def _sigmoid(x):import torch@@ -439,10 +504,11 @@ def attach_weighted_preference_combine():# The policy log-probs are there; only the reference is not.reason = (- "dpo and ipo compare the policy with a frozen reference, and "- "the primary trainer of this blend (the loss with the largest "- "weight) runs none. Give dpo or ipo the largest weight, or "- "remove"+ "dpo and ipo compare the policy with a frozen reference. The "+ "primary trainer of this blend (the loss with the largest "+ "weight) runs none, and the model has no LoRA adapter to "+ "switch off to make one. Give dpo or ipo the largest weight, "+ "or remove")else:reason = (@@ -467,7 +533,7 @@ def attach_weighted_preference_combine(return True-def attach_policy_logp_capture(trainer: object) -> bool:+def attach_policy_logp_capture(trainer: object, reference: bool = False) -> bool:"""Record the policy log-probs trl already computes (#1425).trl 0.29's CPO (the SimPO path) and ORPO trainers compute per-sequence@@ -490,6 +556,13 @@ def attach_policy_logp_capture(trainer: object) -> bool:wrapper using ``sigmoid`` or ``hinge`` would return sums and this woulddouble-count the lengths.+ ``reference=True`` is for a blend that also names ``dpo`` or ``ipo``. The+ CPO and ORPO trainers have no frozen reference, so the capture makes one:+ the same ``concatenated_forward`` once more, without gradients and with+ the LoRA adapter switched off, which is the base model the adapter started+ from. With full fine-tuning there is no adapter to switch off, nothing is+ recorded, and the blend refuses.+Returns True when the capture is in place."""if not hasattr(trainer, "concatenated_forward"):@@ -508,6 +581,8 @@ def attach_policy_logp_capture(trainer: object) -> bool:# through to the blend's refusal rather than raise out of a forward.return out_record_policy_logps(trainer, batch, chosen_logps, rejected_logps)+ if reference:+ _record_adapter_free_reference(trainer, original, model, batch, args, kwargs)return outcapturing._soup_logp_capture = True@@ -515,6 +590,37 @@ def attach_policy_logp_capture(trainer: object) -> bool:return True+def _record_adapter_free_reference(trainer, forward, model, batch, args, kwargs) -> None:+ """Add reference log-probs to the capture: ``forward`` with the adapter off.++ PEFT's ``disable_adapter()`` turns ``requires_grad`` off on every adapter+ weight and, on the way out, on for all of the active adapter's, whatever+ they were. The flags are put back as they were found, so a weight the run+ froze on purpose stays frozen.+ """+ import torch++ accelerator = getattr(trainer, "accelerator", None)+ peft_model = accelerator.unwrap_model(model) if accelerator is not None else model+ if not hasattr(peft_model, "disable_adapter"):+ return+ flags = [(param, param.requires_grad) for param in peft_model.parameters()]+ try:+ with torch.no_grad(), peft_model.disable_adapter():+ out = forward(model, batch, *args, **kwargs)+ finally:+ for param, flag in flags:+ param.requires_grad_(flag)+ stored = trainer._soup_policy_logps+ ref_chosen, ref_rejected = out[0], out[1]+ if stored["chosen_lens"] is not None:+ # trl averaged these too; back to sums, like the policy's.+ ref_chosen = ref_chosen * stored["chosen_lens"].to(ref_chosen.dtype)+ ref_rejected = ref_rejected * stored["rejected_lens"].to(ref_rejected.dtype)+ stored["ref_chosen_logps"] = ref_chosen+ stored["ref_rejected_logps"] = ref_rejected++def attach_reference_logp_capture(trainer: object) -> bool:"""Record policy and reference log-probs on a trl ``DPOTrainer`` (#1425).diff --git a/tests/test_issue1425_dpo_ipo_blend.py b/tests/test_issue1425_dpo_ipo_blend.pyindex e39d7e35..218fa096 100644--- a/tests/test_issue1425_dpo_ipo_blend.py+++ b/tests/test_issue1425_dpo_ipo_blend.py@@ -13,8 +13,10 @@ against ``type(trainer).compute_loss``, the method under Soup's wrappers, oragainst log-probs rebuilt here from a separate forward pass, so none of themreads the capture to check the capture.-Still refused, and pinned in ``tests/test_v05311.py``: a ``dpo`` / ``ipo`` term-under a ``simpo`` / ``orpo`` primary, whose trainer runs no reference.+A ``dpo`` / ``ipo`` term under a ``simpo`` / ``orpo`` primary needs a reference+the CPO and ORPO trainers do not run. Their capture runs one: the same forward+with the LoRA adapter switched off. The tests for it rebuild that reference a+different way, by setting every ``lora_B`` to zero."""from __future__ import annotations@@ -75,7 +77,10 @@ def _tiny_model_dir(tmp_path):return base-def _build(tmp_path, monkeypatch, weights, fields=FIELDS, name="run"):+_LORA = "{r: 4, alpha: 8, dropout: 0.0}"+++def _build(tmp_path, monkeypatch, weights, fields=FIELDS, name="run", lora=_LORA):"""A real ``PreferenceTrainerWrapper`` for ``weights``, set up on ROWS.A fresh LoRA adapter starts with ``B = 0``, which makes the policy equal to@@ -94,7 +99,7 @@ def _build(tmp_path, monkeypatch, weights, fields=FIELDS, name="run"):"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{fields}"- " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"+ f" lora: {lora}\noutput: ./out\n")wrapper = PreferenceTrainerWrapper(cfg, device="cpu")wrapper.setup({"train": ROWS})@@ -455,32 +460,519 @@ class TestABlendWithADpoOrIpoPrimary:assert trainer.state.global_step == 1-class TestWhatStillRefuses:+def _cpo_sums(model, batch):+ """Response log-prob sums and lengths for a CPO / ORPO batch, per side,+ from separate forwards and a plain log-softmax."""+ out = []+ for side in ("chosen", "rejected"):+ ids = batch[f"{side}_input_ids"]+ labels = batch[f"{side}_labels"]+ logits = model(input_ids=ids, attention_mask=batch[f"{side}_attention_mask"]).logits+ logp = torch.log_softmax(logits[:, :-1, :], dim=-1)+ picked = logp.gather(-1, ids[:, 1:].unsqueeze(-1)).squeeze(-1)+ mask = (labels[:, 1:] != -100).to(picked.dtype)+ out += [(picked * mask).sum(dim=1), mask.sum(dim=1)]+ chosen, chosen_len, rejected, rejected_len = out+ return chosen, rejected, chosen_len, rejected_len+++def _cpo_reference_sums(model, batch):+ """The base model's sums: every ``lora_B`` set to zero, then put back.+ Not the route the capture takes (it switches the adapter off)."""+ saved = {+ name: param.detach().clone()+ for name, param in model.named_parameters()+ if "lora_B" in name+ }+ assert saved+ try:+ with torch.no_grad():+ for name, param in model.named_parameters():+ if name in saved:+ param.zero_()+ chosen, rejected, _, _ = _cpo_sums(model, batch)+ finally:+ with torch.no_grad():+ for name, param in model.named_parameters():+ if name in saved:+ param.copy_(saved[name])+ return chosen, rejected+++def _cpo_terms(trainer, batch):+ from soup_cli.utils.preference_combine import (+ DEFAULT_BETA,+ compute_orpo_term,+ compute_simpo_term,+ )++ chosen, rejected, chosen_len, rejected_len = _cpo_sums(trainer.model, batch)+ ref_chosen, ref_rejected = _cpo_reference_sums(trainer.model, batch)+ chosen_ratio = chosen - ref_chosen+ rejected_ratio = rejected - ref_rejected+ return {+ "dpo": -torch.nn.functional.logsigmoid(+ DPO_BETA * (chosen_ratio - rejected_ratio)+ ).mean(),+ "ipo": (+ (chosen_ratio / chosen_len - rejected_ratio / rejected_len - 1 / (2 * IPO_TAU)) ** 2+ ).mean(),+ "simpo": compute_simpo_term(+ chosen, rejected, DEFAULT_BETA, SIMPO_GAMMA, chosen_len, rejected_len+ ),+ "orpo": compute_orpo_term(chosen, rejected, ORPO_BETA, chosen_len, rejected_len),+ }+++class TestABlendWithASimpoOrOrpoPrimary:+ """The other half of #1425: the primary's trainer has no reference."""++ def test_the_fixture_has_a_reference_that_differs(self, tmp_path, monkeypatch):+ _, trainer = _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}")+ batch = _batch(trainer)++ assert type(trainer).__name__ == "CPOTrainer"+ assert not hasattr(trainer, "compute_ref_log_probs")+ chosen, rejected, chosen_len, rejected_len = _cpo_sums(trainer.model, batch)+ ref_chosen, ref_rejected = _cpo_reference_sums(trainer.model, batch)+ assert not torch.allclose(chosen, ref_chosen)+ assert not torch.allclose(rejected, ref_rejected)+ assert len(set(chosen_len.tolist() + rejected_len.tolist())) == 4+ # zeroing lora_B was undone+ again, _, _, _ = _cpo_sums(trainer.model, batch)+ assert torch.equal(again, chosen)++ @pytest.mark.parametrize(+ "weights",+ [+ {"simpo": 0.6, "dpo": 0.4},+ {"simpo": 0.6, "ipo": 0.4},+ {"orpo": 0.6, "dpo": 0.4},+ {"orpo": 0.6, "ipo": 0.4},+ {"simpo": 0.4, "dpo": 0.3, "ipo": 0.2, "orpo": 0.1},+ ],+ )+ def test_the_loss_is_the_weighted_sum_of_the_terms(self, tmp_path, monkeypatch, weights):+ yaml = "{" + ", ".join(f"{k}: {v}" for k, v in weights.items()) + "}"+ _, trainer = _build(tmp_path, monkeypatch, yaml)+ batch = _batch(trainer)++ blended = float(trainer.compute_loss(trainer.model, batch))++ terms = _cpo_terms(trainer, batch)+ assert blended == pytest.approx(_weighted(terms, weights), rel=1e-5)+ without_reference = {k: v for k, v in weights.items() if k in ("simpo", "orpo")}+ assert blended != pytest.approx(_weighted(terms, without_reference), rel=1e-3)++ @pytest.mark.parametrize(+ ("weights", "field", "low", "high"),+ [+ ("{simpo: 0.7, dpo: 0.3}", "dpo_beta", 0.1, 0.9),+ ("{orpo: 0.7, ipo: 0.3}", "ipo_tau", 0.1, 0.9),+ ],+ )+ def test_changing_only_the_reference_terms_field_changes_the_loss(+ self, tmp_path, monkeypatch, weights, field, low, high+ ):+ losses = []+ for value in (low, high):+ fields = "".join(+ line + "\n" for line in FIELDS.splitlines() if not line.strip().startswith(field)+ ) + f" {field}: {value}\n"+ _, trainer = _build(tmp_path, monkeypatch, weights, fields=fields, name=f"v{value}")+ losses.append(float(trainer.compute_loss(trainer.model, _batch(trainer))))++ assert losses[0] != pytest.approx(losses[1], rel=1e-4)++ def test_the_adapter_is_back_on_and_no_weight_changed_its_frozen_state(+ self, tmp_path, monkeypatch+ ):+ """PEFT's ``disable_adapter()`` turns ``requires_grad`` off on every+ adapter weight and back on for all of the active adapter's when it+ exits. A weight the run froze on purpose must still be frozen."""+ _, trainer = _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}")+ batch = _batch(trainer)+ frozen = next(+ param for name, param in trainer.model.named_parameters() if "lora_A" in name+ )+ frozen.requires_grad_(False)+ before = {name: param.requires_grad for name, param in trainer.model.named_parameters()}+ chosen_before, _, _, _ = _cpo_sums(trainer.model, batch)++ trainer.compute_loss(trainer.model, batch).backward()++ after = {name: param.requires_grad for name, param in trainer.model.named_parameters()}+ assert after == before+ assert frozen.grad is None+ chosen_after, _, _, _ = _cpo_sums(trainer.model, batch)+ assert torch.equal(chosen_after, chosen_before) # the adapter is in the forward again+ trained = [+ param for name, param in trainer.model.named_parameters()+ if "lora_" in name and param.requires_grad+ ]+ assert trained and all(param.grad is not None for param in trained)+ assert sum(float(param.grad.abs().sum()) for param in trained) > 0++ def test_the_flags_are_restored_when_the_reference_forward_fails(self, tmp_path, monkeypatch):+ from soup_cli.utils.preference_combine import _record_adapter_free_reference++ _, trainer = _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}")+ # One weight frozen on purpose: PEFT alone would hand it back trainable.+ next(+ param for name, param in trainer.model.named_parameters() if "lora_A" in name+ ).requires_grad_(False)+ before = {name: param.requires_grad for name, param in trainer.model.named_parameters()}++ def failing(model, batch):+ raise RuntimeError("out of memory")++ with pytest.raises(RuntimeError, match="out of memory"):+ _record_adapter_free_reference(trainer, failing, trainer.model, {}, (), {})++ after = {name: param.requires_grad for name, param in trainer.model.named_parameters()}+ assert after == before++ def test_the_reference_carries_no_gradient(self, tmp_path, monkeypatch):+ _, trainer = _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}")++ trainer.compute_loss(trainer.model, _batch(trainer))++ captured = trainer._soup_policy_logps+ assert captured["policy_chosen_logps"].requires_grad+ assert not captured["ref_chosen_logps"].requires_grad+ assert not captured["ref_rejected_logps"].requires_grad++ @pytest.mark.parametrize(+ ("weights", "with_grad", "without_grad"),+ [+ ("{simpo: 0.6, dpo: 0.4}", 1, 1), # the policy, then the reference+ ("{simpo: 0.6, orpo: 0.4}", 1, 0), # no reference term: no extra forward+ ],+ )+ def test_the_reference_forward_runs_only_when_a_term_needs_it(+ self, tmp_path, monkeypatch, weights, with_grad, without_grad+ ):+ _, trainer = _build(tmp_path, monkeypatch, weights)+ batch = _batch(trainer)+ calls = []+ handle = trainer.model.register_forward_pre_hook(+ lambda *_: calls.append(torch.is_grad_enabled())+ )+ try:+ trainer.compute_loss(trainer.model, batch)+ finally:+ handle.remove()++ assert calls.count(True) == with_grad+ assert calls.count(False) == without_grad+ assert ("ref_chosen_logps" in trainer._soup_policy_logps) is bool(without_grad)++ def test_the_two_trainer_families_render_a_row_differently(self, tmp_path, monkeypatch):+ """Why the docs say the terms follow the primary's batch: with this+ tokenizer the CPO batch starts with BOS and the DPOTrainer's does not,+ so the same response has a different reference log-prob."""+ _, cpo = _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}", name="cpo")+ _, dpo = _build(tmp_path, monkeypatch, "{dpo: 0.6, simpo: 0.4}", name="dpo")+ bos = WORDS.index("<s>")++ cpo_batch, dpo_batch = _batch(cpo), _batch(dpo)++ assert bool((cpo_batch["chosen_input_ids"][:, 0] == bos).all())+ assert not bool((dpo_batch["input_ids"][:, 0] == bos).any())++ def test_an_evaluation_batch_runs_the_reference_too(self, tmp_path, monkeypatch):+ """trl's CPO ``prediction_step`` goes through ``concatenated_forward``,+ not ``compute_loss``: the eval loss is trl's own, and the capture still+ pays for a reference forward there. The docs say both."""+ _, trainer = _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}")+ raw = next(iter(trainer.get_train_dataloader()))+ calls = []+ handle = trainer.model.register_forward_pre_hook(lambda *_: calls.append(1))+ try:+ trainer.prediction_step(trainer.model, raw, prediction_loss_only=True)+ finally:+ handle.remove()++ assert len(calls) == 2++ @pytest.mark.parametrize("weights", ["{simpo: 0.6, dpo: 0.4}", "{orpo: 0.6, ipo: 0.4}"])+ def test_a_run_completes_and_logs_the_blend(self, tmp_path, monkeypatch, weights):+ """Before this, the run stopped at step 0: "cannot compute dpo"."""+ wrapper, trainer = _build(tmp_path, monkeypatch, weights)+ parsed = {+ key.strip(): float(value)+ for key, value in (item.split(":") for item in weights.strip("{}").split(","))+ }+ expected = _weighted(_cpo_terms(trainer, _batch(trainer)), parsed)++ result = wrapper.train()++ assert result["initial_loss"] == pytest.approx(expected, rel=1e-4)+ assert trainer.state.global_step == 1+++def _training(init="random", use_olora=False, relora_steps=None):+ from types import SimpleNamespace++ return SimpleNamespace(+ lora=SimpleNamespace(init_strategy=init, use_olora=use_olora),+ relora_steps=relora_steps,+ )+++class TestAnAdapterOffReferenceMustBeTheStartingModel:+ """Under a ``simpo`` / ``orpo`` primary the reference is the model with the+ adapter switched off. That is the model the policy started from only while+ the base weights are the ones that were loaded."""+@pytest.mark.parametrize(- ("weights", "missing", "computed"),+ ("init", "moves"), [(True, False), ("pissa", True), ("olora", True)]+ )+ def test_the_premise_some_inits_rewrite_the_base(self, tmp_path, init, moves):+ """PEFT itself, without Soup: PiSSA and OLoRA put part of each weight+ into the adapter and leave a residual in the base, so adapter-off is no+ longer the model that was loaded. The default init leaves it alone."""+ from peft import LoraConfig, get_peft_model+ from transformers import AutoModelForCausalLM++ base = AutoModelForCausalLM.from_pretrained(_tiny_model_dir(tmp_path))+ ids = torch.arange(8).unsqueeze(0)+ with torch.no_grad():+ loaded = base(input_ids=ids).logits.clone()+ model = get_peft_model(+ base,+ LoraConfig(r=4, target_modules=["q_proj", "v_proj"], init_lora_weights=init),+ )+ with model.disable_adapter():+ adapter_off = model(input_ids=ids).logits++ assert (float((adapter_off - loaded).abs().max()) > 1e-3) is moves++ @pytest.mark.parametrize("primary", ["simpo", "orpo"])+ @pytest.mark.parametrize("term", ["dpo", "ipo"])+ @pytest.mark.parametrize("init", ["pissa", "olora", "loftq"])+ def test_such_an_init_is_refused_with_the_reason(self, primary, term, init):+ from soup_cli.utils.preference_combine import validate_adapter_off_reference++ with pytest.raises(ValueError) as excinfo:+ validate_adapter_off_reference({primary: 0.6, term: 0.4}, _training(init))++ message = str(excinfo.value)+ article = "an" if primary == "orpo" else "a"+ assert f"cannot compute {term} under {article} {primary} primary" in message+ assert f"training.lora.init_strategy='{init}' rewrites the base weights" in message+ assert "Give dpo or ipo the largest weight" in message+ assert "set training.lora.init_strategy to 'random'" in message+ assert "use_olora" not in message++ @pytest.mark.parametrize("init", ["olora", "random"])+ def test_use_olora_is_named_and_is_what_the_message_says_to_unset(self, init):+ """The schema sets ``init_strategy='olora'`` beside ``use_olora`` and+ refuses any other value, so "set init_strategy to 'random'" would send+ the user into that error. ``random`` here is a config object that did+ not go through the schema."""+ from soup_cli.utils.preference_combine import validate_adapter_off_reference++ with pytest.raises(ValueError) as excinfo:+ validate_adapter_off_reference(+ {"simpo": 0.6, "dpo": 0.4}, _training(init, use_olora=True)+ )++ message = str(excinfo.value)+ assert "training.lora.use_olora=True (the same as init_strategy='olora')" in message+ assert "rewrites the base weights" in message+ assert "Give dpo or ipo the largest weight" in message+ assert "set training.lora.use_olora to false" in message+ assert "init_strategy to 'random'" not in message++ def test_the_way_out_of_use_olora_loads(self):+ """What the message says to do is a config the schema accepts, and+ what it no longer says to do is one the schema refuses."""+ from soup_cli.config.schema import LoraConfig++ assert LoraConfig(use_olora=False).init_strategy == "random"+ with pytest.raises(ValueError, match="use_olora=True conflicts"):+ LoraConfig(use_olora=True, init_strategy="random")++ def test_a_relora_restart_is_refused_with_the_reason(self):+ """A restart merges the adapter into the base: measured on the tiny+ Llama, a LoRA-targeted base weight moved by 2.9e-02 in two steps of a+ ``{simpo: 0.6, dpo: 0.4}`` run with ``relora_steps: 1``."""+ from soup_cli.utils.preference_combine import validate_adapter_off_reference++ with pytest.raises(ValueError) as excinfo:+ validate_adapter_off_reference(+ {"orpo": 0.5, "dpo": 0.3, "ipo": 0.2}, _training(relora_steps=200)+ )++ message = str(excinfo.value)+ assert "cannot compute dpo, ipo under an orpo primary" in message+ assert "training.relora_steps=200 merges the adapter into the base weights" in message+ assert "Remove training.relora_steps" in message+ assert "init_strategy" not in message++ @pytest.mark.parametrize(+ ("weights", "training"),[- ("{simpo: 0.6, dpo: 0.4}", "dpo", "simpo"),- ("{orpo: 0.6, ipo: 0.4}", "ipo", "orpo"),- ("{simpo: 0.5, dpo: 0.3, ipo: 0.2}", "dpo, ipo", "simpo"),+ ({"simpo": 0.6, "dpo": 0.4}, {}), # the default init+ ({"dpo": 0.6, "simpo": 0.4}, {"init": "pissa"}), # trl keeps its own reference+ ({"ipo": 0.6, "orpo": 0.4}, {"init": "olora", "relora_steps": 100}),+ ({"simpo": 0.7, "orpo": 0.3}, {"init": "pissa", "relora_steps": 100}), # no reference+ ({"dpo": 0.5, "simpo": 0.5}, {"init": "loftq"}), # a tie: the first key is the primary],)- def test_a_reference_term_under_a_reference_free_primary_says_why(- self, tmp_path, monkeypatch, weights, missing, computed+ def test_what_has_a_valid_reference_is_not_refused(self, weights, training):+ from soup_cli.utils.preference_combine import validate_adapter_off_reference++ assert validate_adapter_off_reference(weights, _training(**training)) is None++ def test_on_a_tie_the_first_key_is_the_primary(self):+ from soup_cli.utils.preference_combine import primary_loss++ assert primary_loss({"simpo": 0.5, "dpo": 0.5}) == "simpo"+ assert primary_loss({"dpo": 0.5, "simpo": 0.5}) == "dpo"+ assert primary_loss({"orpo": 0.2, "ipo": 0.5, "dpo": 0.3}) == "ipo"++ @pytest.mark.parametrize(+ ("lora", "fields", "reason"),+ [+ (_LORA[:-1] + ", init_strategy: pissa}", FIELDS, "init_strategy='pissa'"),+ (_LORA[:-1] + ", use_olora: true}", FIELDS, "training.lora.use_olora=True"),+ (_LORA, FIELDS + " relora_steps: 1\n", "training.relora_steps=1"),+ ],+ )+ def test_a_real_setup_refuses_before_the_model_is_loaded(+ self, tmp_path, monkeypatch, lora, fields, reason+ ):+ from soup_cli.trainer.preference import PreferenceTrainerWrapper++ built = []+ build = PreferenceTrainerWrapper._build_multi_objective+ monkeypatch.setattr(+ PreferenceTrainerWrapper,+ "_build_multi_objective",+ lambda self: built.append(1) or build(self),+ )++ with pytest.raises(ValueError, match="cannot compute dpo under a simpo primary") as excinfo:+ _build(tmp_path, monkeypatch, "{simpo: 0.6, dpo: 0.4}", fields=fields, lora=lora)++ assert reason in str(excinfo.value) and built == []++ @pytest.mark.parametrize("init", ["pissa", "olora"])+ def test_with_a_dpo_primary_the_same_init_trains_against_the_starting_model(+ self, tmp_path, monkeypatch, init):- """The simpo / orpo trainers run no reference, so a dpo / ipo term has- nothing to compare with. The message used to blame missing log-probs,- which is not what is missing here, and gave no way forward."""- wrapper, _ = _build(tmp_path, monkeypatch, weights)+ """What the message tells the user to do instead. trl's ``DPOTrainer``+ keeps a frozen copy of the adapter, residual and all, so at the first+ step the policy and the reference are still the same model."""+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.preference import PreferenceTrainerWrapper++ monkeypatch.chdir(tmp_path)+ base = _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: {dpo: 0.6, simpo: 0.4}\n"+ f" lora: {{r: 4, alpha: 8, dropout: 0.0, init_strategy: {init}}}\noutput: ./out\n"+ )+ wrapper = PreferenceTrainerWrapper(cfg, device="cpu")+ wrapper.setup({"train": ROWS})+ trainer = wrapper.trainer++ trainer.compute_loss(trainer.model, _batch(trainer))++ got = trainer._soup_policy_logps+ for side in ("chosen", "rejected"):+ gap = got[f"policy_{side}_logps"] - got[f"ref_{side}_logps"]+ assert float(gap.abs().max()) < 1e-5, side+++class TestWhatStillRefuses:+ def test_a_model_without_an_adapter_has_no_reference_and_says_so(self):+ """Soup's preference wrappers always apply LoRA, so this is a stand-in:+ a CPO-shaped trainer over a model that has no adapter to switch off."""+ from soup_cli.utils.preference_combine import (+ attach_policy_logp_capture,+ attach_weighted_preference_combine,+ )++ class _Cpo:+ def concatenated_forward(self, model, batch):+ return torch.tensor([-0.5, -0.5]), torch.tensor([-1.0, -1.0])++ def compute_loss(self, model, inputs, return_outputs=False, **kwargs):+ self.concatenated_forward(model, inputs)+ return torch.tensor(2.0)++ trainer = _Cpo()+ labels = torch.tensor([[-100, 1, 1], [-100, 1, 1]])+ batch = {"chosen_labels": labels, "rejected_labels": labels}+ attach_policy_logp_capture(trainer, reference=True)+ attach_weighted_preference_combine(trainer, {"simpo": 0.6, "dpo": 0.4})with pytest.raises(ValueError, match="cannot compute") as excinfo:- wrapper.train()+ trainer.compute_loss(object(), batch)message = str(excinfo.value)- assert f"cannot compute {missing} on this step (computed: {computed})" in message+ assert "cannot compute dpo on this step (computed: simpo)" in messageassert "frozen reference" in message+ assert "no LoRA adapter to switch off" in messageassert "Give dpo or ipo the largest weight" in messageassert "no per-sequence log-probs" not in message+ def test_the_adapter_is_switched_off_on_the_unwrapped_model(self):+ """The trainer hands ``concatenated_forward`` the model as accelerate+ wrapped it; ``disable_adapter`` lives on the PEFT model inside."""+ from contextlib import contextmanager++ from soup_cli.utils.preference_combine import _record_adapter_free_reference++ class _Peft(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.weight = torch.nn.Parameter(torch.zeros(1))+ self.off = False++ @contextmanager+ def disable_adapter(self):+ self.off = True+ try:+ yield+ finally:+ self.off = False++ peft = _Peft()+ wrapped = object() # what accelerate returns; it has no disable_adapter+ seen = {}++ class _Accelerator:+ def unwrap_model(self, model):+ assert model is wrapped+ return peft++ class _Trainer:+ accelerator = _Accelerator()+ _soup_policy_logps = {+ "chosen_lens": torch.tensor([2, 4]),+ "rejected_lens": torch.tensor([1, 3]),+ }++ def forward(model, batch):+ seen.update(model=model, off=peft.off, grad=torch.is_grad_enabled())+ return torch.tensor([-0.5, -1.0]), torch.tensor([-2.0, -3.0])++ trainer = _Trainer()+ _record_adapter_free_reference(trainer, forward, wrapped, {}, (), {})++ assert seen == {"model": wrapped, "off": True, "grad": False}+ assert peft.off is False+ # averages back to sums with each side's own lengths+ assert trainer._soup_policy_logps["ref_chosen_logps"].tolist() == [-1.0, -4.0]+ assert trainer._soup_policy_logps["ref_rejected_logps"].tolist() == [-2.0, -9.0]+@pytest.mark.parametrize("fields",[" dpo_beta_schedule: linear\n dpo_beta_end: 0.5\n", " dpo_ref_regen_epochs: 1\n"],@@ -861,3 +1353,41 @@ class TestTheIpoKernel:compute_ipo_term(pol_chosen, pol_rejected, None, ref_rejected, 0.25)with pytest.raises(ValueError, match="beta"):compute_ipo_term(pol_chosen, pol_rejected, ref_chosen, ref_rejected, 0.0)+++# --- The primary is the largest weight, wherever its key sits ----------------+#+# From the second review of #1828: both call sites survived having+# ``primary_loss(weights)`` swapped for ``next(iter(weights))``.+++def test_the_guard_follows_the_largest_weight_not_the_first_key():+ from soup_cli.utils.preference_combine import validate_adapter_off_reference++ with pytest.raises(ValueError, match="cannot compute dpo under a simpo primary"):+ validate_adapter_off_reference({"dpo": 0.4, "simpo": 0.6}, _training("pissa"))+ assert validate_adapter_off_reference({"simpo": 0.4, "dpo": 0.6}, _training("pissa")) is None+++ ("weights", "wrapper_name"),+ [+ ("{dpo: 0.4, simpo: 0.6}", "SimPOTrainerWrapper"),+ ("{simpo: 0.4, dpo: 0.6}", "DPOTrainerWrapper"),+ ("{ipo: 0.1, dpo: 0.3, orpo: 0.6}", "ORPOTrainerWrapper"),+ ],+)+def test_the_built_trainer_follows_the_largest_weight(weights, wrapper_name):+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.preference import PreferenceTrainerWrapper++ cfg = load_config_from_string(+ "base: ./nowhere\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"+ )+ wrapper = PreferenceTrainerWrapper(cfg, device="cpu")++ assert type(wrapper._build_multi_objective()).__name__ == wrapper_namediff --git a/tests/test_v05311.py b/tests/test_v05311.pyindex 6bb606fe..ea3b9e7e 100644--- a/tests/test_v05311.py+++ b/tests/test_v05311.py@@ -1266,36 +1266,11 @@ class TestOnARealTrlTrainer:tok.save_pretrained(base)return base- # A dpo / ipo primary trains since #1425's DPOTrainer capture- # (tests/test_issue1425_dpo_ipo_blend.py); under a simpo / orpo primary the- # dpo term still has no reference to read.- @pytest.mark.parametrize("weights", ["{simpo: 0.6, dpo: 0.4}"])- def test_a_blend_on_a_real_trainer_refuses_instead_of_training_one_loss(- self, tmp_path, monkeypatch, weights,- ):- from soup_cli.config.loader import load_config_from_string- from soup_cli.trainer.preference import PreferenceTrainerWrapper-- 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"- f" preference_loss_weights: {weights}\n"- " lora: {r: 4, alpha: 8, dropout: 0.0}\noutput: ./out\n"- )- rows = [- {"prompt": "what is one plus one ?", "chosen": "two", "rejected": "three"},- {"prompt": "hello there", "chosen": "hi", "rejected": "no"},- ] * 2- wrapper = PreferenceTrainerWrapper(cfg, device="cpu")- wrapper.setup({"train": rows})- with pytest.raises(ValueError, match="cannot compute") as excinfo:- wrapper.train()- message = str(excinfo.value)- assert "dpo" in message and "simpo" in message, message- assert "preference_loss_weights" in message, message+ # The refusal test that stood here (`{dpo: 0.7, simpo: 0.3}` and+ # `{simpo: 0.6, dpo: 0.4}` stopping at step 0) is gone with #1425: both+ # blends train now. tests/test_issue1425_dpo_ipo_blend.py has them as+ # positive cases, and the refusal that is left (no log-probs, or a model+ # with no adapter to switch off) on stand-in trainers.def test_a_reference_free_blend_on_a_real_trainer_is_the_weighted_sum(self, tmp_path, monkeypatch,