Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(train): refuse the RL-signal flags PPO cannot feed (#1441) (#1514)
UmranPros92e6a1fd0040
diff --git a/changelog.d/0.75.1/1514.fixed.md b/changelog.d/0.75.1/1514.fixed.mdnew file mode 100644index 00000000..236b1807--- /dev/null+++ b/changelog.d/0.75.1/1514.fixed.md@@ -0,0 +1 @@+- **`task: ppo` refuses the reward-hacking and echo-trap flags it cannot feed, instead of loading them inert (#1441 by @umran666 in #1514).** The `trl` PPO trainer this build supports takes no reward functions — its reward comes from the reward model it calls internally — so the wrappers Soup built for the shared signal buffer were dropped, the buffer was never written, and because the buffer object existed the detector's log-reading fallback returned early as well. A run with `reward_hack_detector`, `reward_hack_mitigation` or `echo_trap_enabled` was announced and then never halted, mitigated or trapped. Those three flags are now refused before the model loads, naming every flag set and pointing at `task: grpo`, where the buffer is fed. The on-GPU buffer feed for PPO rollouts is still open.diff --git a/docs/commands.md b/docs/commands.mdindex b4cf0ac0..0f0a2a7f 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -359,7 +359,7 @@ soup data persona-mix --prompts <jsonl> --n N --output <jsonl> Persona-Hub divesoup data brain-rot <data.jsonl> [--strict] Brain-rot detector — arXiv 2510.13928 (v0.69.0)soup iterative-dpo --base-model <m> --reward-model <rm> --prompts <p.jsonl> --output-dir <out> --rounds N --pairs-per-round N [--plan-only] Iterative DPO loop driver — LIVE sample→score→pair→train (v0.70.0; live v0.71.11)soup train --reward-hack-detector info_rm|rm_ensemble [--reward-hack-halt] Reward-hacking detector for GRPO — LIVE callback (v0.70.0; live v0.71.11)-soup train --reward-hack-mitigation off|log_only|kl_control|pid_lagrangian Closed-loop reward-hacking auto-mitigation (detect → raise KL/β → rollback → early-stop); GRPO/PPO, requires --reward-hack-detector; PPO BETA (v0.71.26)+soup train --reward-hack-mitigation off|log_only|kl_control|pid_lagrangian Closed-loop reward-hacking auto-mitigation (detect → raise KL/β → rollback → early-stop); GRPO only, requires --reward-hack-detector; refused on task: ppo (v0.71.26)soup train --config soup.yaml # training.uld_strategy: wasserstein_aligned Cross-tokenizer ULD on task='distill' (different tokenizers) — LIVE (v0.71.18)soup train --config soup.yaml # training.minillm_enabled: true [minillm_teacher_mix_ratio 0.3] MiniLLM reverse-KL distillation, config-only — LIVE; offline mix 0 rejected (v0.70.0; live v0.71.11; #692, #979)soup train --config grpo.yaml # training.rl_checkpoint_save_every_steps: N [rl_checkpoint_keep_last: N; rl_checkpoint_include_optimizer: true] Mid-epoch checkpoint for GRPO/PPO — LIVE (v0.70.0; live v0.71.11)diff --git a/docs/training.md b/docs/training.mdindex 4410178c..73525684 100644--- a/docs/training.md+++ b/docs/training.md@@ -502,14 +502,14 @@ tokenizer-specific rather than vocabulary-agnostic.### Closed-loop reward-hacking auto-mitigation (v0.71.26)-The detectors above *halt*; `training.reward_hack_mitigation` (or the `--reward-hack-mitigation` flag) makes the trainer *self-correct* mid-run. It requires `reward_hack_detector` on a `grpo`/`ppo` transformers run, and has four modes:+The detectors above *halt*; `training.reward_hack_mitigation` (or the `--reward-hack-mitigation` flag) makes the trainer *self-correct* mid-run. It requires `reward_hack_detector` on a `grpo` transformers run, and has four modes:- **`log_only`** — observe only. Appends a per-step `mitigation_log.jsonl` under the run's output dir (the InfoRM/ensemble drop, the OK/WARN/HACK verdict, reward mean/std, completion-length trend, repetition) and provably never mutates β. Run this first to *see* hacking before you let a controller act on it.- **`kl_control`** — a reversible **bang-bang + hysteresis** controller. When a multi-signal vote (`reward_hack_signals`: the detector drop + `length_trend` + `repetition`) stays above `reward_hack_trip_band` for `reward_hack_dwell_steps`, it multiplies β by `reward_hack_kl_gain` (clamped to `[reward_hack_beta_floor > 0, reward_hack_beta_ceil]`, never crossing 0); after `reward_hack_release_patience` below-band steps it relaxes β back toward the floor. Dwell + release-patience stop it flapping. β is written to **both** `trainer.beta` and `trainer.args.beta` so it takes effect on stock GRPO *and* Soup's GRPO variants (and `trainer.args.kl_coef` on PPO).- **`pid_lagrangian`** — a **PID-Lagrangian** controller (Stooke et al. 2020) that holds the hacking signal at `reward_hack_signal_target` (Kp/Ki/Kd with integral anti-windup via `reward_hack_integral_clamp`), plus an **escalation ladder**: raise β → after `reward_hack_rollback_patience` persistent-HACK steps roll back to the last-good RL checkpoint (needs `rl_checkpoint_save_every_steps`) → after `reward_hack_max_recovery_attempts` rollbacks, early-stop with a plain-English give-up explanation.- **Anti-gaming hardening** (any control mode): `reward_hack_signal_smoothing` (`ema`/`median` over `reward_hack_smoothing_window`), `reward_hack_conservative_on_disagreement` (when detectors disagree, keep KL high + guard against a bimodal reward-distribution collapse), and `reward_hack_reward_shaping` (subtract a bounded `reward_hack_shaping_strength` penalty on the gamed proxy — `length`/`repetition`/`sentinel` — over the reward-fn seam).-**Scope:** proof-of-mechanism only. Validated on SmolLM2-135M + a synthetic length-hacking task on a single RTX 3050 (all four modes live, including a real mid-run rollback). PPO ships **BETA** — the buffer + `kl_coef` mutation are wired and unit-tested, but the on-GPU proof is GRPO-only. Whether the loop suppresses hacking without collapsing true reward on 7B+ with a real reward model is an open, community-validatable question. `reward_hack_mitigation ∈ {kl_control, pid_lagrangian}` is mutually exclusive with `ref_model_ema_alpha` (both drive the KL/ref dynamics).+**Scope:** proof-of-mechanism only. Validated on SmolLM2-135M + a synthetic length-hacking task on a single RTX 3050 (all four modes live, including a real mid-run rollback). The on-GPU proof is GRPO-only. **On `task: ppo` the reward-hacking and echo-trap flags are refused** (`reward_hack_detector`, `reward_hack_mitigation`, `echo_trap_enabled`): the trl PPO trainer this build supports takes no reward functions, so the reward/completion signal those callbacks read is never captured, and a run carrying them would be announced and then inert. Whether the loop suppresses hacking without collapsing true reward on 7B+ with a real reward model is an open, community-validatable question. `reward_hack_mitigation ∈ {kl_control, pid_lagrangian}` is mutually exclusive with `ref_model_ema_alpha` (both drive the KL/ref dynamics).Every detector composes with v0.34 `soup why` (anomaly explainer), v0.32 spike recovery, and the v0.53.11 #127 `GRPOStabilityCallback` so a single GRPO run can have InfoRM + echo-trap + spike-recovery + in-place ref-model EMA all active simultaneously without duplicating trajectory / state collection. The reward-hack and echo-trap callbacks read the per-step rewards through a shared, thread-safe capture buffer (Soup wraps your reward functions so it never has to monkeypatch TRL); `rm_ensemble` needs ≥2 reward functions to compute a divergence. The MiniLLM teacher-mix is an offline distribution-blend analog of the paper's on-policy teacher-mixed *sampling*, and ULD compares the distributions after clamping teacher ids to the teacher vocab (correct for same-family / extended-vocab pairs; a genuinely different tokenization needs a sequence-alignment step). The reference-model EMA (`--ref-model-ema-alpha`) updates in place — no full `state_dict` round-trip — so it is cheap at 70B+ scale.diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.pyindex 5f096089..dc2dd6c9 100644--- a/src/soup_cli/trainer/ppo.py+++ b/src/soup_cli/trainer/ppo.py@@ -71,6 +71,45 @@ def _effective_ppo_setting(return getattr(config, field, kwargs[field])+def _unsupported_rl_flags(tcfg) -> list[str]:+ """The RL-signal flags PPO cannot feed on the experimental trl API (#1441)."""+ flags = []+ if getattr(tcfg, "reward_hack_detector", None) is not None:+ flags.append("reward_hack_detector")+ if getattr(tcfg, "echo_trap_enabled", False):+ flags.append("echo_trap_enabled")+ if getattr(tcfg, "reward_hack_mitigation", "off") != "off":+ flags.append("reward_hack_mitigation")+ return flags+++def refuse_unfed_rl_flags(tcfg, *, is_experimental: bool) -> None:+ """Refuse RL-signal flags PPO cannot feed, before anything is loaded.++ #1441: the experimental ``PPOTrainer`` takes no ``reward_funcs`` — its+ reward comes from the reward model it calls internally — so the wrappers+ built at :282-299 were dropped on the floor. The buffer was still created,+ and because the buffer object existed, the detector's ``on_log`` fallback+ returned early, so nothing was ever written *and* nothing was ever read from+ trl's logs. A run with a detector, a mitigation mode or the echo trap was+ announced, loaded and inert.++ Refusing beats a dead callback: the run stops before the model load, and the+ message names every flag that was set.+ """+ if not is_experimental:+ return+ flags = _unsupported_rl_flags(tcfg)+ if not flags:+ return+ raise ValueError(+ f"task: ppo cannot use {', '.join(flags)}: this trl's experimental "+ "PPOTrainer takes no reward functions, so the reward/completion signal "+ "these callbacks read is never captured. They are wired on GRPO only. "+ "Remove the flag(s), or run task: grpo where the signal buffer is fed."+ )++class PPOTrainerWrapper:"""High-level wrapper for PPO training from SoupConfig.@@ -120,8 +159,6 @@ class PPOTrainerWrapper:def setup(self, dataset: dict):"""Load model, tokenizer, reward model/fn, apply LoRA, create PPO trainer."""- from datasets import Dataset-# Import PPOTrainer/PPOConfig — trl >=0.28 moved to trl.experimentalppo_trainer_cls, ppo_config_cls, is_experimental = _import_ppo_classes()@@ -133,6 +170,15 @@ class PPOTrainerWrapper:cfg = self.configtcfg = cfg.training+ # #1441 — refuse before anything is loaded, including `datasets` and the+ # model. These callbacks read a signal buffer the experimental+ # PPOTrainer leaves empty, so a run with them is announced and inert.+ refuse_unfed_rl_flags(tcfg, is_experimental=is_experimental)++ # Deferred below the refusal: a config that cannot run at all should say+ # which flag stopped it, not fail on an unrelated import first.+ from datasets import Dataset+# #353: seed before the model and any adapter are built.apply_training_seed(tcfg)diff --git a/tests/test_issue1441_ppo_refuses_unfed_rl_flags.py b/tests/test_issue1441_ppo_refuses_unfed_rl_flags.pynew file mode 100644index 00000000..facc5a33--- /dev/null+++ b/tests/test_issue1441_ppo_refuses_unfed_rl_flags.py@@ -0,0 +1,244 @@+"""#1441 — `task: ppo` must refuse the RL-signal flags it cannot feed.++The trl PPO trainer this build supports (`trl.experimental.ppo.PPOTrainer`)+takes no `reward_funcs`: its reward comes from the reward model it calls+internally. So the callable wrappers built for the shared signal buffer were+dropped, the buffer was never written, and — because the buffer object existed —+the detector's `on_log` fallback returned early too. A run carrying+`reward_hack_detector`, `reward_hack_mitigation` or `echo_trap_enabled` was+loaded, announced, and inert: never halted, never mitigated, never trapped.++These drive the refusal the trainer calls before loading anything, so they need+no model, no trl import and no GPU.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from soup_cli.trainer.ppo import refuse_unfed_rl_flags+++def _tcfg(**overrides):+ """A `training` shape with the three flags off, as a real config has them."""+ base = {+ "reward_hack_detector": None,+ "reward_hack_halt": False,+ "reward_hack_mitigation": "off",+ "echo_trap_enabled": False,+ }+ base.update(overrides)+ return SimpleNamespace(**base)+++class TestTheRefusal:+ def test_no_flags_means_no_refusal(self):+ # The control: a plain PPO run must not be refused.+ refuse_unfed_rl_flags(_tcfg(), is_experimental=True)++ def test_the_detector_is_refused_and_named(self):+ with pytest.raises(ValueError) as excinfo:+ refuse_unfed_rl_flags(+ _tcfg(reward_hack_detector="info_rm"), is_experimental=True,+ )+ message = str(excinfo.value)+ assert "reward_hack_detector" in message, message+ assert "task: ppo" in message, message++ def test_the_mitigation_mode_is_refused_and_named(self):+ with pytest.raises(ValueError) as excinfo:+ refuse_unfed_rl_flags(+ _tcfg(reward_hack_mitigation="kl_control"), is_experimental=True,+ )+ assert "reward_hack_mitigation" in str(excinfo.value)++ def test_the_echo_trap_is_refused_and_named(self):+ with pytest.raises(ValueError) as excinfo:+ refuse_unfed_rl_flags(+ _tcfg(echo_trap_enabled=True), is_experimental=True,+ )+ assert "echo_trap_enabled" in str(excinfo.value)++ def test_every_set_flag_is_named_not_just_the_first(self):+ with pytest.raises(ValueError) as excinfo:+ refuse_unfed_rl_flags(+ _tcfg(+ reward_hack_detector="info_rm",+ reward_hack_mitigation="kl_control",+ echo_trap_enabled=True,+ ),+ is_experimental=True,+ )+ message = str(excinfo.value)+ for flag in ("reward_hack_detector", "reward_hack_mitigation", "echo_trap_enabled"):+ assert flag in message, message++ def test_the_halt_switch_alone_is_not_a_refusal(self):+ """`reward_hack_halt` only modifies the detector; with no detector+ there is nothing to feed, so it must not refuse on its own."""+ refuse_unfed_rl_flags(_tcfg(reward_hack_halt=True), is_experimental=True)++ def test_the_message_says_the_flags_are_grpo_only(self):+ """A user who wants this feature needs to be told where it works."""+ with pytest.raises(ValueError) as excinfo:+ refuse_unfed_rl_flags(+ _tcfg(reward_hack_detector="info_rm"), is_experimental=True,+ )+ assert "grpo" in str(excinfo.value).lower()++ def test_a_non_experimental_trl_is_not_refused(self):+ """The transitional API does accept `reward_funcs`, so the refusal is+ scoped to the experimental class rather than to `task: ppo` itself."""+ refuse_unfed_rl_flags(+ _tcfg(reward_hack_detector="info_rm"), is_experimental=False,+ )+++class TestTheFlagScan:+ def test_a_default_config_scans_empty(self):+ from soup_cli.trainer.ppo import _unsupported_rl_flags++ assert _unsupported_rl_flags(_tcfg()) == []++ def test_a_missing_attribute_is_treated_as_off(self):+ """A config object without the fields at all must not raise."""+ from soup_cli.trainer.ppo import _unsupported_rl_flags++ assert _unsupported_rl_flags(SimpleNamespace()) == []++ def test_a_real_config_with_the_flags_off_scans_empty(self):+ """Against the real schema, not a stand-in."""+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.ppo import _unsupported_rl_flags++ cfg = load_config_from_string(+ "base: ./tiny\ntask: ppo\ndata: {train: ./d.jsonl, format: plaintext}\n"+ "training: {epochs: 1, batch_size: 1, gradient_accumulation_steps: 1}\n"+ "output: ./out\n"+ )+ assert _unsupported_rl_flags(cfg.training) == []+ refuse_unfed_rl_flags(cfg.training, is_experimental=True)++ def test_a_real_config_that_sets_the_detector_is_refused(self):+ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(+ "base: ./tiny\ntask: ppo\ndata: {train: ./d.jsonl, format: plaintext}\n"+ "training:\n epochs: 1\n batch_size: 1\n gradient_accumulation_steps: 1\n"+ " reward_hack_detector: info_rm\n"+ "output: ./out\n"+ )+ with pytest.raises(ValueError, match="reward_hack_detector"):+ refuse_unfed_rl_flags(cfg.training, is_experimental=True)+++class TestSetupRefusesBeforeLoadingAnything:+ """The call site, not just the helper (#1441 review).++ Every other test here calls `refuse_unfed_rl_flags` directly, so replacing+ the one line in `setup()` with `pass` left the file green. This drives+ `PPOTrainerWrapper.setup` with the loaders stubbed, and asserts nothing was+ loaded: the refusal has to land before the model, the reward model or the+ tokenizer.+ """++ _FLAGS = {+ "reward_hack_detector": " reward_hack_detector: info_rm\n",+ "reward_hack_mitigation": (+ " reward_hack_detector: info_rm\n reward_hack_mitigation: kl_control\n"+ ),+ "echo_trap_enabled": " echo_trap_enabled: true\n",+ }++ @pytest.mark.parametrize("flag", sorted(_FLAGS))+ def test_setup_refuses_before_loading_anything(self, flag, tmp_path, monkeypatch):+ import os++ # `peft` and `trl` are in this list on purpose: this environment's+ # transformers/torchvision mismatch breaks `trl.PPOConfig` and+ # `peft`, so without them the test ERRORS instead of skipping. On a+ # working stack all five import and the test runs (~23 s).+ for module in ("torch", "transformers", "peft", "trl", "datasets"):+ pytest.importorskip(module)+ os.environ.setdefault("TRL_EXPERIMENTAL_SILENCE", "1")++ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer import ppo++ loaded: list[str] = []+ monkeypatch.setattr(+ ppo.PPOTrainerWrapper, "_setup_reward",+ lambda self, *a: loaded.append("reward"),+ )+ monkeypatch.setattr(+ ppo.PPOTrainerWrapper, "_setup_transformers",+ lambda self, *a: loaded.append("policy"),+ )+ monkeypatch.chdir(tmp_path)+ cfg = load_config_from_string(+ "base: ./tiny\ntask: ppo\nbackend: transformers\n"+ "data:\n train: train.jsonl\n max_length: 64\n"+ "training:\n epochs: 1\n batch_size: 2\n gradient_accumulation_steps: 1\n"+ " quantization: none\n reward_model: ./rm\n"+ " lora:\n r: 4\n alpha: 8\n"+ + self._FLAGS[flag]+ + "output: ./out\n"+ )+ wrapper = ppo.PPOTrainerWrapper(cfg, device="cpu")+ rows = [{"messages": [{"role": "user", "content": "hi"}]}] * 4+ with pytest.raises(ValueError, match=flag):+ wrapper.setup({"train": rows})+ assert loaded == [], loaded++ def test_a_plain_ppo_setup_is_not_refused_by_the_call_site(+ self, tmp_path, monkeypatch,+ ):+ """The control: the same path with no flags must get past the refusal.++ It still fails later in this environment (no model on disk), so this+ asserts only that the refusal is not what stops it.+ """+ for module in ("torch", "transformers", "peft", "trl", "datasets"):+ pytest.importorskip(module)++ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer import ppo++ monkeypatch.chdir(tmp_path)+ cfg = load_config_from_string(+ "base: ./tiny\ntask: ppo\nbackend: transformers\n"+ "data:\n train: train.jsonl\n max_length: 64\n"+ "training:\n epochs: 1\n batch_size: 2\n gradient_accumulation_steps: 1\n"+ " quantization: none\n reward_model: ./rm\n"+ "output: ./out\n"+ )+ wrapper = ppo.PPOTrainerWrapper(cfg, device="cpu")+ rows = [{"messages": [{"role": "user", "content": "hi"}]}] * 4+ try:+ wrapper.setup({"train": rows})+ except Exception as exc: # noqa: BLE001 — anything but the refusal+ assert "cannot use" not in str(exc), exc+++class TestTheRefusalCoversExactlyTheFlagsThatMakeABuffer:+ """`_unsupported_rl_flags` re-states `rl_callbacks_need_buffer`; if a fourth+ flag ever starts a buffer, the refusal must not silently miss it (#1441)."""++ @pytest.mark.parametrize(+ "overrides",+ [+ {},+ {"reward_hack_detector": "info_rm"},+ {"reward_hack_mitigation": "log_only"},+ {"echo_trap_enabled": True},+ {"reward_hack_halt": True},+ ],+ )+ def test_the_refusal_and_the_buffer_predicate_agree(self, overrides):+ from soup_cli.trainer.ppo import _unsupported_rl_flags+ from soup_cli.utils.peft_wiring import rl_callbacks_need_buffer++ tcfg = _tcfg(**overrides)+ assert bool(_unsupported_rl_flags(tcfg)) == rl_callbacks_need_buffer(tcfg)