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.

fix(train): a blend that cannot be computed refuses instead of scaling one loss (#1425) (#1513)

UmranPros4142fdd89889
diff --git a/changelog.d/0.75.1/1513.fixed.md b/changelog.d/0.75.1/1513.fixed.md
new file mode 100644
index 00000000..96c3cad1
--- /dev/null
+++ b/changelog.d/0.75.1/1513.fixed.md
@@ -0,0 +1 @@
+- **`training.preference_loss_weights` refuses a blend it cannot compute, instead of training one loss and reporting several (#1425 by @umran666 in #1513).** No trl 0.29 trainer puts per-sequence log-probs on the batch, so every requested term went uncomputed and the wrapper fell back to `primary_loss * primary_weight`: `{dpo: 0.7, simpo: 0.3}` printed `Multi-objective preference loss: 0.70·dpo + 0.30·simpo` at setup and then trained DPO alone scaled by 0.7, with nothing in the output saying so. A blend that cannot be evaluated now stops the run, naming the terms it could not compute, the ones it could, and what was requested; the weighted-sum path itself is unchanged, so a trl that does carry log-probs still blends. Every `preference_loss_weights` config therefore stops at the first step until the real blend lands: to train one loss, remove the weights and set `training.preference_loss`.
diff --git a/docs/training.md b/docs/training.md
index 73525684..132fcd69 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -936,10 +936,14 @@ training:
simpo: 0.4
```
-The combine wrapper reads policy + reference summed log-probs from the inner
-TRL trainer's per-batch inputs and computes a true weighted sum via the
-in-tree `compute_dpo_term` / `compute_simpo_term` / `compute_orpo_term` /
-`compute_ipo_term` kernels. BCO cannot be mixed with paired losses (data
+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).
@@ -1247,11 +1251,11 @@ training:
preference_loss_weights: {dpo: 0.7, bco: 0.3}
```
-Schema validates 2–5 entries summing to 1. Live runtime weighted-loss
-combination is wired in v0.40.1; v0.40.0 fails fast with an actionable
-`NotImplementedError` if you actually try to train (same stub-then-live
-pattern as v0.27.0 MII / v0.37.0 multipack / v0.38.0 quant menu /
-v0.39.0 ReLoRA).
+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)).
+Set `training.preference_loss` for a single loss.
## GRPO Training (Reasoning)
diff --git a/src/soup_cli/utils/preference_combine.py b/src/soup_cli/utils/preference_combine.py
index b1f6d2a5..e3ff5147 100644
--- a/src/soup_cli/utils/preference_combine.py
+++ b/src/soup_cli/utils/preference_combine.py
@@ -215,9 +215,10 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
matching ``compute_*_term`` helper.
3. Combine via :func:`combine_losses` and return the blended scalar.
- When the TRL trainer does not expose the per-batch log-probs (older
- TRL versions, custom forks), we fall back to the v0.40.1 primary-loss
- scaling — defence-in-depth so a TRL upgrade does not crash training.
+ When the TRL trainer does not expose the per-batch log-probs (which is every
+ trl 0.29 trainer — #1425), this raises, naming the terms it could not
+ 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.
Idempotent: re-attaching detects the ``_soup_weighted_combine`` marker.
"""
@@ -231,11 +232,10 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
def wrapped(model, inputs, return_outputs=False, **kwargs):
result = original(model, inputs, return_outputs=return_outputs, **kwargs)
- if return_outputs:
- primary_loss, outputs = result
- else:
- primary_loss = result
- outputs = None
+ # #1425: the primary loss is no longer a fallback (it is what made a
+ # blend train one loss while reporting several). It is only unpacked
+ # 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.
@@ -315,9 +315,23 @@ def attach_weighted_preference_combine(trainer: object, weights: Mapping[str, fl
# All requested terms computed — return true weighted sum.
blended = combine_losses(terms, snapshot)
else:
- # Fallback: primary-loss scaling.
- primary_weight = snapshot.get(_pick_primary(snapshot), 1.0)
- blended = primary_loss * float(primary_weight)
+ # #1425: trl 0.29 puts no per-sequence log-probs on the batch, so
+ # `terms` is empty on every step. Scaling the primary loss by its
+ # weight trained only the highest-weighted loss and said nothing
+ # about it, while setup had already printed
+ # "0.70·dpo + 0.30·simpo". Refuse instead, naming the terms.
+ missing = sorted(set(snapshot) - set(terms))
+ computed = sorted(terms)
+ raise ValueError(
+ "preference_loss_weights: cannot compute "
+ f"{', '.join(missing)} on this step"
+ + (f" (computed: {', '.join(computed)})" if computed else "")
+ + f". Weights requested: {', '.join(sorted(snapshot))}. The "
+ "underlying trl exposes no per-sequence log-probs on the batch, "
+ "so the blend cannot be evaluated; training would silently use "
+ "the primary loss alone. Remove training.preference_loss_weights "
+ "and set training.preference_loss to the single loss you want."
+ )
if return_outputs:
return blended, outputs
return blended
@@ -362,11 +376,6 @@ def _read_lens(obj, prefix: str):
return None
-def _pick_primary(weights: Mapping[str, float]) -> str:
- """Return the loss with the highest weight (deterministic on ties)."""
- return max(sorted(weights), key=lambda k: weights[k])
-
-
def describe_blend(weights: Optional[Mapping[str, float]]) -> str:
"""Human-readable summary for advisory output."""
if not weights:
diff --git a/tests/test_v05311.py b/tests/test_v05311.py
index d0b0ae89..47f7e31a 100644
--- a/tests/test_v05311.py
+++ b/tests/test_v05311.py
@@ -525,6 +525,8 @@ class TestWeightedCombineHook:
)
def test_blended_loss_scales_with_weight(self):
+ """#1425: this asserted `2.0 * 0.7`, i.e. the silent primary-only
+ fallback. It now refuses; `inputs=None` is the shape it exercised."""
from soup_cli.utils.preference_combine import (
attach_weighted_preference_combine,
)
@@ -537,9 +539,9 @@ class TestWeightedCombineHook:
attach_weighted_preference_combine(
trainer, {"dpo": 0.7, "simpo": 0.3}
)
- # Primary is dpo (highest weight). Loss = 2.0 * 0.7 = 1.4
- out = trainer.compute_loss(None, None)
- assert float(out) == pytest.approx(1.4)
+ with pytest.raises(ValueError) as excinfo:
+ trainer.compute_loss(None, None)
+ assert "cannot compute" in str(excinfo.value)
# ---------------------------------------------------------------------------
@@ -882,7 +884,34 @@ class TestTrueWeightedCombine:
assert float(out) != 99.0
assert math.isfinite(float(out))
- def test_falls_back_when_logps_missing(self):
+ def test_refuses_when_logps_missing(self):
+ """#1425: no trl 0.29 trainer puts log-probs on the batch.
+
+ This used to return `primary * primary_weight` — training only the
+ highest-weighted loss while reporting a blended number, silently.
+ """
+ from soup_cli.utils.preference_combine import (
+ attach_weighted_preference_combine,
+ )
+
+ class _Trainer:
+ def compute_loss(self, model, inputs, return_outputs=False):
+ return torch.tensor(2.0)
+
+ trainer = _Trainer()
+ attach_weighted_preference_combine(
+ trainer, {"dpo": 0.7, "simpo": 0.3}
+ )
+ # No logps -> refuse, naming the terms, instead of scaling silently.
+ with pytest.raises(ValueError) as excinfo:
+ trainer.compute_loss(model=None, inputs={})
+ message = str(excinfo.value)
+ assert "dpo" in message and "simpo" in message, message
+ assert "preference_loss_weights" in message, message
+
+ def test_refusal_names_only_the_terms_it_could_not_compute(self):
+ """Policy logps present, reference ones absent: `simpo` computes and
+ only `dpo` is named as missing."""
from soup_cli.utils.preference_combine import (
attach_weighted_preference_combine,
)
@@ -895,9 +924,98 @@ class TestTrueWeightedCombine:
attach_weighted_preference_combine(
trainer, {"dpo": 0.7, "simpo": 0.3}
)
- # No logps → fallback to primary scaling.
- out = trainer.compute_loss(model=None, inputs={})
- assert float(out) == pytest.approx(2.0 * 0.7)
+ inputs = {
+ "policy_chosen_logps": torch.tensor([0.0, 0.1]),
+ "policy_rejected_logps": torch.tensor([-0.5, -0.6]),
+ }
+ with pytest.raises(ValueError) as excinfo:
+ trainer.compute_loss(model=None, inputs=inputs)
+ message = str(excinfo.value)
+ # Pinned whole, not "cannot compute dpo": that substring also occurs in
+ # "cannot compute dpo, simpo", so a mutation that named every requested
+ # term as missing would survive a looser assertion (#1425 review).
+ assert "cannot compute dpo on this step (computed: simpo)" in message, message
+
+
+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
+ must stop instead of training the primary loss alone (#1425 review).
+
+ On `main` these fail, because training completes: the loss is
+ `0.7 * DPO` and the run reports success.
+ """
+
+ _WORDS = [
+ "<pad>", "<s>", "</s>", "<unk>", "what", "is", "one", "plus", "?",
+ "two", "three", "hello", "there", "hi", "no",
+ ]
+
+ def _tiny_model_dir(self, tmp_path):
+ """A random-init 2-layer Llama plus a WordLevel tokenizer (#1425 repro)."""
+ try:
+ from soup_cli.trainer._trl_compat import resolve_trl_symbol
+
+ resolve_trl_symbol("DPOConfig")
+ except Exception as exc: # noqa: BLE001 — a broken trl is not a failure
+ pytest.skip(f"this environment cannot import a trl DPO config: {exc}")
+
+ import torch
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import (
+ LlamaConfig,
+ LlamaForCausalLM,
+ PreTrainedTokenizerFast,
+ )
+
+ base = tmp_path / "tiny"
+ words = list(self._WORDS)
+ raw = Tokenizer(
+ models.WordLevel(vocab={w: i for i, w in enumerate(words)}, unk_token="<unk>"),
+ )
+ raw.pre_tokenizer = pre_tokenizers.Whitespace()
+ tok = PreTrainedTokenizerFast(
+ tokenizer_object=raw, bos_token="<s>", eos_token="</s>",
+ pad_token="<pad>", unk_token="<unk>",
+ )
+ torch.manual_seed(0)
+ LlamaForCausalLM(LlamaConfig(
+ vocab_size=len(words), hidden_size=32, intermediate_size=64,
+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,
+ pad_token_id=0, bos_token_id=1, eos_token_id=2,
+ )).save_pretrained(base)
+ tok.save_pretrained(base)
+ return base
+
+ @pytest.mark.parametrize(
+ "weights", ["{dpo: 0.7, simpo: 0.3}", "{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
# ---------------------------------------------------------------------------