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(reward-hacking): keep info_rm silent on rewards too discrete for a median split (#1438) (#1630)
Momoyeyu1f9f8d513d41
diff --git a/changelog.d/0.75.1/1630.fixed.md b/changelog.d/0.75.1/1630.fixed.mdnew file mode 100644index 00000000..dcd6f103--- /dev/null+++ b/changelog.d/0.75.1/1630.fixed.md@@ -0,0 +1 @@+- `info_rm` reward-hacking detection no longer votes on a step whose median split leaves either half constant — a two-valued reward (e.g. `reward_fn: accuracy`'s 0/1), or a continuous reward where half the batch lands on the same value. Previously the pooled-variance floor collapsed to `1e-9` and a first step near a 50% success rate recorded a phantom separation of ~31,623 as the baseline, so later, healthier steps read as a collapse and could halt the run or mutate β. Those steps now cast no vote and log one warning naming the cause. A step where every reward is identical still votes once a baseline exists, so a genuinely collapsed continuous reward reads HACK as before. The pooled-variance floor is also tied to the observed reward range instead of a bare `1e-9`. Detector logs and `mitigation_log.jsonl` from runs before this version are not comparable — use `reward_hack_detector: rm_ensemble` or the length/repetition signals on two-valued rewards (#1438 by @Momoyeyu in #1630).diff --git a/docs/training.md b/docs/training.mdindex 8371d83c..c1259c04 100644--- a/docs/training.md+++ b/docs/training.md@@ -508,6 +508,22 @@ whitespace tokens to the active tokenizer's integer ids. This catches subwordrepetition that punctuation-heavy decoded text can hide, but the score becomestokenizer-specific rather than vocabulary-agnostic.+The `info_rm` detector stays silent on any step whose median split leaves+either half constant — a two-valued reward (e.g. `reward_fn: accuracy`'s 0/1)+always does, and so does a continuous reward where half the batch lands on+the same value (e.g. rewards clipped at 0). The separation index there would+measure the success rate rather than reward-model health, so the step casts+no vote: no baseline is recorded and nothing halts or mutates β (one warning+is logged per run). The single exception: once a baseline exists, a step+where *every* reward is identical still votes 0.0 — a 0/1 run never records+a baseline and stays silent, while a genuinely collapsed continuous reward+reads HACK as before. For two-valued rewards use+`reward_hack_detector: rm_ensemble` or the length/repetition signals instead.+**Changed:** before this version a constant-half split could record an+inflated separation (~3×10⁴ at a 50% first step) as the baseline and classify+later, healthier steps as HACK — detector logs and `mitigation_log.jsonl`+files from runs before this version are not comparable.+### 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` transformers run, and has four modes:diff --git a/src/soup_cli/utils/reward_hacking.py b/src/soup_cli/utils/reward_hacking.pyindex 5845f452..bca4bed0 100644--- a/src/soup_cli/utils/reward_hacking.py+++ b/src/soup_cli/utils/reward_hacking.py@@ -32,6 +32,7 @@ Security:from __future__ import annotations+import loggingimport mathimport typesfrom dataclasses import dataclass@@ -40,9 +41,18 @@ from typing import TYPE_CHECKING, Any, Optional, Sequenceif TYPE_CHECKING:from soup_cli.utils.reward_hacking import RewardHackCallback+logger = logging.getLogger(__name__)+_MAX_DETECTOR_NAME_LEN = 32_MAX_RM_ENSEMBLE_SIZE = 32_EPS = 1e-9+#: Floor on the pooled variance in :func:`compute_cluster_separation`,+#: expressed as a fraction of the observed reward range. A constant+#: (``1e-9``) floor let a split into two constant halves return a+#: separation of ~31623 for a 0/1 reward — four orders of magnitude+#: above every later value, so it was recorded as the baseline and any+#: subsequent step read as a collapse (#1438).+_SEPARATION_VARIANCE_FLOOR_FRAC = 0.01SUPPORTED_HACK_DETECTORS: frozenset[str] = frozenset({"info_rm", "rm_ensemble"})@@ -175,7 +185,9 @@ def compute_cluster_separation(good = _check_finite_float_sequence(good_scores, "good_scores")bad = _check_finite_float_sequence(bad_scores, "bad_scores")delta = _mean(good) - _mean(bad)- pooled = _variance(good) + _variance(bad) + _EPS+ spread = max(*good, *bad) - min(*good, *bad)+ floor = max(_EPS, (_SEPARATION_VARIANCE_FLOOR_FRAC * spread) ** 2)+ pooled = _variance(good) + _variance(bad) + floorreturn delta / math.sqrt(pooled)@@ -431,6 +443,8 @@ class _RewardHackCallback_body: # type: ignore[misc, valid-type] # noqa: N801# v0.71.26 — the numeric relative drop from the last observe_signal,# consumed by the closed-loop mitigation controller.self._last_drop_pct = 0.0+ # #1438 — warn at most once per run when info_rm has no signal.+ self._warned_discrete_reward = False# --- pure signal computation (testable without transformers) ---@@ -481,8 +495,40 @@ class _RewardHackCallback_body: # type: ignore[misc, valid-type] # noqa: N801good = ordered[half:]if not bad or not good:return None+ # #1438 — a median split carries information only when each half+ # can vary. A two-valued reward (e.g. reward_fn: accuracy's 0/1)+ # always leaves at least one constant half, so its "separation" is+ # a function of the success rate alone, not of reward-model+ # health; a first step at exactly 50% would otherwise record a+ # ~31623 baseline and classify every later, healthier step as+ # HACK. Skip the step instead of voting — unless every reward in+ # the step is identical AND a baseline already exists: a 0/1 run+ # never records one (every step is silent), so reaching the check+ # means a continuous reward collapsed to a constant, which is a+ # genuine HACK signal (main reported 0.0 there too).+ if _variance(bad) == 0.0 or _variance(good) == 0.0:+ if self._baseline_health is not None and ordered[0] == ordered[-1]:+ return 0.0+ self._warn_discrete_reward()+ return Nonereturn compute_cluster_separation(good, bad)+ def _warn_discrete_reward(self) -> None:+ """Warn once per run that info_rm has nothing to vote with (#1438)."""+ if self._warned_discrete_reward:+ return+ self._warned_discrete_reward = True+ logger.warning(+ "reward_hack_detector=info_rm has no signal for this reward: a "+ "median split of the step's rewards leaves a constant half (a "+ "two-valued reward such as the 0/1 reward_fn: accuracy), so the "+ "cluster separation cannot measure reward-model health. The "+ "detector stays silent for those steps. Alternatives: "+ "reward_hack_detector=rm_ensemble (needs at least two reward "+ "functions), or the length and repetition signals via "+ "reward_hack_signals."+ )+def observe_signal(self, raw_signal: float, step: int) -> RewardHackReport:"""Fold a raw signal into the running baseline + classify.diff --git a/tests/test_issue1223_rl_signal_eval_isolation.py b/tests/test_issue1223_rl_signal_eval_isolation.pyindex f987a576..e1e400ea 100644--- a/tests/test_issue1223_rl_signal_eval_isolation.py+++ b/tests/test_issue1223_rl_signal_eval_isolation.py@@ -351,12 +351,16 @@ class TestEvaluationLeavesTheSignalUntouched:# ==========================================================================_PROMPT_LENGTH_REWARD = '''def reward_fn(prompts=None, completions=None, **kwargs):- """The prompt's word count: deterministic whatever the model samples."""+ """Prompt word count plus a per-index jitter: deterministic whatever the+ model samples (a completion-derived term would make the two runs of+ test_the_detector_state_is_bit_identical diverge), and continuous enough+ that a step's median split has two varying halves (#1438 makes info_rm+ stay silent on a two-valued reward)."""out = []- for prompt in prompts:+ for i, prompt in enumerate(prompts):if isinstance(prompt, list):prompt = " ".join(str(m.get("content", "")) for m in prompt)- out.append(float(len(str(prompt).split())))+ out.append(float(len(str(prompt).split())) + 0.001 * i)return out'''diff --git a/tests/test_issue1438_info_rm_discrete_reward.py b/tests/test_issue1438_info_rm_discrete_reward.pynew file mode 100644index 00000000..7fbf5276--- /dev/null+++ b/tests/test_issue1438_info_rm_discrete_reward.py@@ -0,0 +1,206 @@+"""#1438 — info_rm must not vote on a reward too discrete for a median split.++The default ``reward_fn: accuracy`` (and the ``verifiable`` code reward) return+only 0.0/1.0. A median split of such a step's rewards always leaves at least+one constant half, so the cluster "separation" is a function of the success+rate alone — about 31623 at exactly 50% — not a reward-model health signal.+The run then records that phantom value as the baseline and every later step+reads as a collapse: a policy whose accuracy rises past 50% is halted as+HACK, and the kl_control controller raises beta. The detector now returns no+signal for those steps and warns once, instead of voting.+"""++from __future__ import annotations++import logging+import types++import pytest++from soup_cli.utils.reward_hacking import build_reward_hack_callback+++def _binary_rewards(correct: int, n: int = 8) -> list[float]:+ """A 0/1 reward such as reward_fn: accuracy returns."""+ return [0.0] * (n - correct) + [1.0] * correct+++class _SeqBuffer:+ """Fake RLSignalBuffer returning a scripted sequence of snapshots."""++ def __init__(self, snapshots):+ self._snapshots = list(snapshots)+ self._index = 0++ def snapshot(self):+ snap = self._snapshots[min(self._index, len(self._snapshots) - 1)]+ self._index += 1+ return snap+++def _snapshot(rewards, completions=()):+ return {+ "completions": list(completions) or ["a", "b", "c", "d"] * (len(rewards) // 4),+ "per_func": {"accuracy": list(rewards)},+ "rewards": list(rewards),+ }+++def _run_steps(cb, buffer, n_steps):+ control = types.SimpleNamespace(should_training_stop=False)+ state = types.SimpleNamespace(global_step=0, log_history=[])+ for step in range(1, n_steps + 1):+ state.global_step = step+ cb.on_step_end(None, state, control)+ return state, control+++class TestDiscreteRewardSilence:+ """A 0/1 reward must produce no signal, no baseline, no verdict."""++ def test_rising_accuracy_never_halts(self):+ # Issue's headline case: accuracy 3/8 -> 7/8 is a healthy run.+ cb = build_reward_hack_callback(detector="info_rm", halt_on_hack=True)+ buf = _SeqBuffer([_snapshot(_binary_rewards(k)) for k in (3, 4, 5, 6, 7)])+ cb.buffer = buf+ state, control = _run_steps(cb, buf, 5)+ assert control.should_training_stop is False+ verdicts = [e["reward_hack_verdict"] for e in state.log_history+ if "reward_hack_verdict" in e]+ assert "HACK" not in verdicts++ def test_first_step_at_fifty_percent_is_not_a_baseline(self):+ cb = build_reward_hack_callback(detector="info_rm", halt_on_hack=True)+ # 4/8 = the phantom ~31623 baseline of the bug report.+ assert cb.compute_signal(_snapshot(_binary_rewards(4))) is None+ assert cb._baseline_health is None+ assert cb._baseline_raw is None++ def test_every_two_valued_split_is_silent(self):+ cb = build_reward_hack_callback(detector="info_rm")+ for k in range(9):+ assert cb.compute_signal(_snapshot(_binary_rewards(k))) is None++ def test_constant_rewards_are_silent(self):+ cb = build_reward_hack_callback(detector="info_rm")+ assert cb.compute_signal(_snapshot([0.5] * 8)) is None++ def test_binary_run_reaching_full_accuracy_stays_silent(self):+ # 0/1 rewards never record a baseline, so a run converging to all-1.0+ # keeps producing no signal rather than a late "collapse" verdict.+ cb = build_reward_hack_callback(detector="info_rm", halt_on_hack=True)+ cb.buffer = _SeqBuffer([_snapshot(_binary_rewards(k)) for k in (3, 5, 8)])+ state, control = _run_steps(cb, cb.buffer, 3)+ assert control.should_training_stop is False+ assert not any("reward_hack_verdict" in e for e in state.log_history)++ def test_warns_once_per_run(self, caplog):+ cb = build_reward_hack_callback(detector="info_rm")+ buf = _SeqBuffer([_snapshot(_binary_rewards(k)) for k in (3, 5, 6)])+ cb.buffer = buf+ with caplog.at_level(logging.WARNING, logger="soup_cli.utils.reward_hacking"):+ _run_steps(cb, buf, 3)+ warnings = [r for r in caplog.records if "info_rm" in r.getMessage()]+ assert len(warnings) == 1+ msg = warnings[0].getMessage()+ assert "rm_ensemble" in msg # names the suggested alternatives++ def test_reward_hack_signals_mentioned_alongside_rm_ensemble(self, caplog):+ cb = build_reward_hack_callback(detector="info_rm")+ with caplog.at_level(logging.WARNING, logger="soup_cli.utils.reward_hacking"):+ cb.compute_signal(_snapshot(_binary_rewards(4)))+ assert any("reward_hack_signals" in r.getMessage() for r in caplog.records)+++class TestContinuousRewardControl:+ """Control: a genuine separation collapse on continuous rewards still+ reads HACK — the guard must not swallow real signals."""++ _WIDE = _snapshot([0.0, 0.05, 0.95, 1.0])+ _BUNCHED = _snapshot([0.45, 0.49, 0.51, 0.55])++ def test_collapse_still_halts(self):+ cb = build_reward_hack_callback(detector="info_rm", halt_on_hack=True)+ cb.buffer = _SeqBuffer([self._WIDE, self._BUNCHED])+ state, control = _run_steps(cb, cb.buffer, 2)+ assert control.should_training_stop is True+ assert any(+ e.get("reward_hack_verdict") == "HACK" for e in state.log_history+ )++ def test_total_collapse_after_a_varying_baseline_still_halts(self):+ # A fully constant step votes 0.0 once a baseline exists: a 0/1 run+ # never records one, so reaching it means a continuous reward+ # collapsed — a real HACK signal, as on main.+ cb = build_reward_hack_callback(detector="info_rm", halt_on_hack=True)+ cb.buffer = _SeqBuffer([self._WIDE, _snapshot([1.0] * 8)])+ state, control = _run_steps(cb, cb.buffer, 2)+ assert control.should_training_stop is True+ assert state.log_history[-1]["reward_hack_verdict"] == "HACK"++ def test_a_constant_half_with_a_baseline_stays_silent(self):+ # The 0.0 vote is only for a step where EVERY reward is identical.+ # A continuous reward clipped at 0 leaves one constant half but still+ # varies across the split — it carries no separation signal either.+ cb = build_reward_hack_callback(detector="info_rm", halt_on_hack=True)+ cb.buffer = _SeqBuffer(+ [self._WIDE, _snapshot([0.0, 0.0, 0.0, 0.0, 0.2, 0.5, 0.8, 1.0])]+ )+ state, control = _run_steps(cb, cb.buffer, 2)+ assert control.should_training_stop is False+ assert state.log_history[-1].get("reward_hack_verdict") != "HACK"++ def test_three_distinct_values_still_signal(self):+ cb = build_reward_hack_callback(detector="info_rm")+ assert cb.compute_signal(_snapshot([0.0, 0.1, 0.5, 0.9])) is not None+++class TestKlControlController:+ """The same sequence through the mitigation controller must leave beta+ at its starting value (acceptance: built by _attach_reward_hack)."""++ def test_beta_unchanged_on_binary_rewards(self, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.config.schema import TrainingConfig+ from soup_cli.utils.peft_wiring import _attach_reward_hack++ tcfg = TrainingConfig(+ reward_hack_detector="info_rm",+ reward_hack_mitigation="kl_control",+ )+ added = []+ trainer = types.SimpleNamespace(+ beta=0.04,+ args=types.SimpleNamespace(beta=0.04),+ add_callback=lambda cb: added.append(cb),+ )+ buf = _SeqBuffer([_snapshot(_binary_rewards(k)) for k in (3, 5, 6, 7, 7, 7)])+ n = _attach_reward_hack(+ trainer, tcfg, buffer=buf, tokenizer=None,+ output_dir=str(tmp_path), task="grpo",+ )+ assert n == 1 and added+ cb = added[0]+ cb.attach(trainer)+ for step in range(1, 7):+ cb.on_step_end(None, types.SimpleNamespace(global_step=step), None)+ assert trainer.beta == pytest.approx(0.04)+ assert trainer.args.beta == pytest.approx(0.04)+++class TestSeparationFloorIsRangeTied:+ """The pooled-variance floor scales with the reward range, so a+ degenerate split can no longer produce a ~31623 baseline."""++ def test_degenerate_split_is_bounded(self):+ from soup_cli.utils.reward_hacking import compute_cluster_separation++ value = compute_cluster_separation([1.0, 1.0], [0.0, 0.0])+ assert 0.0 < value <= 200.0 # was ~31623 under the constant 1e-9 floor++ def test_floor_scales_with_range(self):+ from soup_cli.utils.reward_hacking import compute_cluster_separation++ small = compute_cluster_separation([1.0, 1.0], [0.0, 0.0])+ big = compute_cluster_separation([100.0, 100.0], [0.0, 0.0])+ assert big == pytest.approx(small) # delta and floor scale togetherdiff --git a/tests/test_v07111.py b/tests/test_v07111.pyindex daf0c3e8..71001e4e 100644--- a/tests/test_v07111.py+++ b/tests/test_v07111.py@@ -154,7 +154,9 @@ class TestRewardHackCallback:from soup_cli.utils.reward_hacking import build_reward_hack_callbackcb = build_reward_hack_callback(detector="info_rm")- snap = {"rewards": [0.0, 0.0, 5.0, 5.0], "per_func": {}}+ # Continuous rewards with a varying median split (#1438: a two-valued+ # reward leaves a constant half and no longer yields a signal).+ snap = {"rewards": [0.0, 0.1, 4.9, 5.0], "per_func": {}}sig = cb.compute_signal(snap)assert sig is not None and sig > 0.0@@ -183,10 +185,13 @@ class TestRewardHackCallback:detector="info_rm", halt_on_hack=True, buffer=buf)state, control = _FakeState(1), _FakeControl()- # Step 1 — high separation = baseline.- buf.record(func_name="r", completions=["a"] * 4, rewards=[0, 0, 9, 9])+ # Step 1 — high separation = baseline. (Continuous rewards with both+ # median halves varying; #1438 makes a two-valued reward produce no+ # signal at all.)+ buf.record(func_name="r", completions=["a"] * 4, rewards=[0, 0.2, 8.8, 9])cb.on_step_end(None, state, control)- # Step 2 — bunched rewards = HACK.+ # Step 2 — a fully constant step with a baseline reads as a total+ # collapse = HACK (see test_issue1438_info_rm_discrete_reward.py).buf.record(func_name="r", completions=["a"] * 4, rewards=[5, 5, 5, 5])state.global_step = 2cb.on_step_end(None, state, control)diff --git a/tests/test_v07126.py b/tests/test_v07126.pyindex f902f286..81c3be69 100644--- a/tests/test_v07126.py+++ b/tests/test_v07126.py@@ -67,8 +67,12 @@ class _SeqBuffer:return snap-# Well-separated rewards (healthy) vs bunched rewards (reward model losing grip).-_HEALTHY = _grpo_snapshot([0.0, 0.0, 1.0, 1.0], ["a", "b", "c", "d"])+# Well-separated rewards (healthy) vs bunched rewards (reward model losing+# grip). _HEALTHY keeps both median-split halves varying: a two-valued reward+# leaves a constant half, and #1438 makes info_rm return no signal for it.+# _HACK stays fully constant — with a baseline recorded it reads as a total+# collapse (see test_issue1438_info_rm_discrete_reward.py).+_HEALTHY = _grpo_snapshot([0.0, 0.05, 0.95, 1.0], ["a", "b", "c", "d"])_HACK = _grpo_snapshot([0.5, 0.5, 0.5, 0.5], ["a", "b", "c", "d"])# =====================================================================