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(grpo): log the kl metric for GRPO variants (#1263) (#1293)

Mohammad Hijjawi0c95b96ca367
diff --git a/changelog.d/0.75.1/1293.fixed.md b/changelog.d/0.75.1/1293.fixed.md
new file mode 100644
index 00000000..522f5fad
--- /dev/null
+++ b/changelog.d/0.75.1/1293.fixed.md
@@ -0,0 +1,4 @@
+- GRPO variant runs (`grpo_variant` other than `standard`) with a non-zero
+ `grpo_beta` log the `kl` metric again, as trl's stock loss does: the masked
+ batch mean of the per-token KL, averaged over the accepted tokens for `rft`
+ (#1263 by @MohammadHijjawi97 in #1293).
diff --git a/docs/training.md b/docs/training.md
index aa74a23a..0d977bf6 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -706,6 +706,10 @@ completions it trains on. The β that the reward-hack controller sets at runtime
paper uses, cannot be configured yet
([#1247](https://github.com/MakazhanAlpamys/Soup/issues/1247)).
+With a non-zero `grpo_beta`, a variant run logs the same `kl` metric as trl's stock
+loss: the batch mean of that per-token estimate over the completion tokens (over the
+accepted tokens only, for `rft`), as `kl` in training and `eval_kl` in evaluation.
+
The stability callback (EMA ref-model update, replay buffer, TIS alert counter)
attaches automatically when any of `ref_model_ema_alpha` / `replay_buffer_size`
/ `tis_threshold` / etc. is set.
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index ae806aaf..b50cc39d 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -49,7 +49,7 @@ def make_grpo_trainer_variant(base_cls: type, variant: str) -> type:
@lru_cache(maxsize=8)
def _make_grpo_trainer_variant_cached(base_cls: type, variant: str) -> type:
"""Cached factory body — keyed on already-normalised variant."""
- from soup_cli.utils.grpo_variants import apply_variant_loss
+ from soup_cli.utils.grpo_variants import apply_variant_loss, variant_kl_metric
class _GRPOTrainerVariant(base_cls): # type: ignore[misc, valid-type]
"""GRPOTrainer subclass that routes compute_loss through Soup's variants."""
@@ -163,6 +163,19 @@ def _make_grpo_trainer_variant_cached(base_cls: type, variant: str) -> type:
return None
mode = "train" if getattr(getattr(self, "model", model), "training", True) else "eval"
+ # #1263: this loss replaces trl's, which is where trl logs the ``kl``
+ # metric, so log it here the same way (same key, same gather).
+ mean_kl = variant_kl_metric(
+ self._soup_grpo_variant,
+ logp_new=logp_new,
+ advantages=advantages,
+ beta=beta,
+ completion_mask=mask,
+ reference_logp=ref_logp,
+ )
+ metrics = getattr(self, "_metrics", None)
+ if mean_kl is not None and metrics is not None:
+ metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
normalizer = (
getattr(self, "current_gradient_accumulation_steps", 1.0)
if mode == "train"
diff --git a/src/soup_cli/utils/grpo_variants.py b/src/soup_cli/utils/grpo_variants.py
index 56012e49..294d8352 100644
--- a/src/soup_cli/utils/grpo_variants.py
+++ b/src/soup_cli/utils/grpo_variants.py
@@ -438,6 +438,38 @@ def _with_kl(token_loss, per_token_kl, beta: float):
return token_loss + beta * per_token_kl
+def variant_kl_metric(
+ name: str,
+ *,
+ logp_new,
+ advantages,
+ beta: float,
+ completion_mask=None,
+ reference_logp=None,
+):
+ """Batch-mean per-token KL for the ``kl`` metric of a variant run (#1263).
+
+ trl 0.29's stock loss logs ``(kl_t * mask).sum() / mask.sum().clamp(min=1)``.
+ This is the same quantity over the tokens the variant applies its KL term
+ to: the completion tokens, or the accepted ones for ``rft``. Returns
+ ``None`` when ``beta == 0`` (no KL term, so trl logs nothing either) and
+ for ``standard``, whose loss and ``kl`` metric are trl's own.
+ """
+ normalised = validate_grpo_variant(name)
+ if normalised == "standard" or float(beta) == 0.0:
+ return None
+ per_token_kl = _per_token_kl(normalised, float(beta), logp_new, reference_logp).detach()
+ mask = completion_mask
+ if normalised == "rft":
+ advantages_2d = advantages.unsqueeze(-1) if advantages.dim() == 1 else advantages
+ mask = (advantages_2d > 0).to(per_token_kl.dtype).expand_as(per_token_kl)
+ if completion_mask is not None:
+ mask = mask * completion_mask
+ if mask is None:
+ return per_token_kl.mean()
+ return (per_token_kl * mask).sum() / mask.sum().clamp(min=1.0)
+
+
def _masked_mean(
token_loss,
completion_mask=None,
diff --git a/tests/test_issue1263_grpo_variant_kl_metric.py b/tests/test_issue1263_grpo_variant_kl_metric.py
new file mode 100644
index 00000000..26075d49
--- /dev/null
+++ b/tests/test_issue1263_grpo_variant_kl_metric.py
@@ -0,0 +1,186 @@
+"""#1263 -- GRPO variants log the ``kl`` metric trl's stock loss reports.
+
+Since #1249 every non-standard variant adds ``grpo_beta * kl_t`` inside Soup's
+variant loss. That loss replaces trl's ``GRPOTrainer._compute_loss``, which is
+where trl records the batch-mean per-token KL as the ``kl`` metric, so a variant
+run logged no ``kl``. The variant now records it under the same key, with the
+same masking and the same cross-process gather as trl 0.29's stock loss; ``rft``
+averages over the accepted tokens it applies the KL to.
+
+Helpers and the tiny offline trainer are shared with the #1232 tests.
+"""
+
+from __future__ import annotations
+
+import types
+from collections import defaultdict
+
+import pytest
+
+from tests.test_issue1232_grpo_variant_kl import (
+ VARIANTS,
+ _batch,
+ _build_real,
+ _generated_batch_off_reference,
+ _requires_train_extra,
+ _StandInGRPOBase,
+ _torch,
+ _trainer_inputs,
+ _trl_stock_loss,
+)
+
+
+def _trl_kl(torch, logp, reference, mask):
+ """trl 0.29's ``kl`` metric: masked batch mean of its per-token estimator."""
+ kl = torch.exp(reference - logp) - (reference - logp) - 1
+ return (kl * mask).sum() / mask.sum().clamp(min=1.0)
+
+
+def _metric(variant, batch, *, beta, mask="batch"):
+ from soup_cli.utils.grpo_variants import variant_kl_metric
+
+ return variant_kl_metric(
+ variant,
+ logp_new=batch["logp_new"],
+ advantages=batch["advantages"],
+ beta=beta,
+ completion_mask=batch["mask"] if mask == "batch" else mask,
+ reference_logp=batch["reference"],
+ )
+
+
+class TestTheMetric:
+ @pytest.mark.parametrize("variant", [v for v in VARIANTS if v != "rft"])
+ def test_equals_trls_masked_batch_mean(self, variant):
+ torch = _torch()
+ batch = _batch(torch)
+ expected = _trl_kl(torch, batch["logp_new"].detach(), batch["reference"], batch["mask"])
+ assert _metric(variant, batch, beta=0.1).item() == pytest.approx(expected.item(), rel=1e-12)
+
+ def test_rft_averages_over_its_accepted_tokens_only(self):
+ """Rows 0 and 2 have positive advantage; row 1's tokens are not trained on."""
+ torch = _torch()
+ batch = _batch(torch)
+ accepted = batch["mask"] * (batch["advantages"] > 0).to(batch["mask"].dtype).unsqueeze(-1)
+ expected = _trl_kl(torch, batch["logp_new"].detach(), batch["reference"], accepted)
+ everything = _trl_kl(torch, batch["logp_new"].detach(), batch["reference"], batch["mask"])
+ got = _metric("rft", batch, beta=0.1).item()
+ assert got == pytest.approx(expected.item(), rel=1e-12)
+ assert got != pytest.approx(everything.item(), rel=1e-6)
+
+ def test_rft_without_a_completion_mask_counts_tokens_not_rows(self):
+ torch = _torch()
+ batch = _batch(torch)
+ accepted = (batch["advantages"] > 0).to(batch["mask"].dtype).unsqueeze(-1).expand(3, 5)
+ expected = _trl_kl(torch, batch["logp_new"].detach(), batch["reference"], accepted)
+ assert _metric("rft", batch, beta=0.1, mask=None).item() == pytest.approx(
+ expected.item(), rel=1e-12
+ )
+
+ @pytest.mark.parametrize("variant", VARIANTS + ("standard",))
+ def test_nothing_to_log_at_beta_zero_or_for_standard(self, variant):
+ torch = _torch()
+ batch = _batch(torch)
+ assert _metric(variant, batch, beta=0.0) is None
+ if variant == "standard":
+ assert _metric(variant, batch, beta=0.1) is None
+
+
+class _StandInWithMetrics(_StandInGRPOBase):
+ """Adds trl's ``_metrics`` store and an ``accelerator`` with a single-process gather."""
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
+ self.accelerator = types.SimpleNamespace(gather=lambda tensor: tensor.reshape(-1))
+
+
+def _variant_trainer(variant, **kwargs):
+ from soup_cli.trainer.grpo import make_grpo_trainer_variant
+
+ trainer = make_grpo_trainer_variant(_StandInWithMetrics, variant)(**kwargs)
+ if variant == "two_sided":
+ trainer._soup_grpo_delta = 0.2
+ return trainer
+
+
+class TestTheVariantTrainerLogsIt:
+ @pytest.mark.parametrize("variant", VARIANTS)
+ def test_a_variant_step_records_kl(self, variant):
+ torch = _torch()
+ batch = _batch(torch)
+ trainer = _variant_trainer(variant, logps=batch["logp_new"], beta=0.1)
+ trainer._compute_loss(None, _trainer_inputs(torch, batch))
+ expected = _metric(variant, batch, beta=0.1).item()
+ assert trainer._metrics["train"]["kl"] == [pytest.approx(expected, rel=1e-12)]
+
+ @pytest.mark.parametrize("variant", VARIANTS)
+ def test_beta_zero_records_nothing(self, variant):
+ torch = _torch()
+ batch = _batch(torch)
+ trainer = _variant_trainer(variant, logps=batch["logp_new"], beta=0.0)
+ trainer._compute_loss(None, _trainer_inputs(torch, batch, with_reference=False))
+ assert "kl" not in trainer._metrics["train"]
+
+
+class TestTheRealTrainer:
+ def test_dapo_logs_the_same_kl_as_trls_stock_loss(self, tmp_path, monkeypatch):
+ """On one real generated batch, the variant's ``kl`` equals trl's stock ``kl``."""
+ _requires_train_extra()
+ import torch
+
+ wrapper = _build_real(tmp_path, monkeypatch, "dapo")
+ trainer = wrapper.trainer
+ inputs = _generated_batch_off_reference(trainer)
+ kl_log = trainer._metrics["train"]["kl"]
+
+ # Same seed before each forward: LoRA dropout is active in train mode.
+ torch.manual_seed(3)
+ trainer._compute_loss(trainer.model, inputs)
+ assert not trainer._soup_fallback_warned, "fell back to trl's stock loss"
+ assert len(kl_log) == 1, "the variant loss did not log kl"
+ torch.manual_seed(3)
+ _trl_stock_loss(trainer, "dapo", inputs)
+ assert len(kl_log) == 2
+ assert kl_log[0] == pytest.approx(kl_log[1], rel=1e-5, abs=1e-8)
+ assert kl_log[0] > 0.0, "the policy was moved off its reference, so kl is non-zero"
+
+
+class TestTheMetricFollowsTrlsPlumbing:
+ def test_an_eval_step_records_under_eval(self):
+ """trl files the metric under ``self._metrics[mode]``; ``log()`` prefixes eval keys."""
+ torch = _torch()
+ batch = _batch(torch)
+ trainer = _variant_trainer("dapo", logps=batch["logp_new"], beta=0.1)
+ trainer.model.training = False
+ trainer._compute_loss(None, _trainer_inputs(torch, batch))
+ expected = _metric("dapo", batch, beta=0.1).item()
+ assert trainer._metrics["eval"]["kl"] == [pytest.approx(expected, rel=1e-12)]
+ assert "kl" not in trainer._metrics["train"]
+
+ @pytest.mark.parametrize("variant", VARIANTS)
+ def test_the_tool_mask_is_part_of_the_mask(self, variant):
+ """trl's metric masks with ``completion_mask * tool_mask``, as the variant's loss does."""
+ torch = _torch()
+ batch = _batch(torch)
+ tool_mask = torch.tensor(
+ [[1, 1, 0, 1, 1], [1, 0, 1, 0, 0], [0, 1, 1, 0, 0]], dtype=batch["mask"].dtype
+ )
+ inputs = _trainer_inputs(torch, batch)
+ inputs["tool_mask"] = tool_mask
+ trainer = _variant_trainer(variant, logps=batch["logp_new"], beta=0.1)
+ trainer._compute_loss(None, inputs)
+ expected = _metric(variant, batch, beta=0.1, mask=batch["mask"] * tool_mask).item()
+ assert trainer._metrics["train"]["kl"] == [pytest.approx(expected, rel=1e-12)]
+ assert expected != pytest.approx(_metric(variant, batch, beta=0.1).item(), rel=1e-6)
+
+ def test_the_metric_reads_the_current_policy_not_the_rollout_one(self):
+ """With ``old_per_token_logps`` in the batch, the KL is still the current policy's."""
+ torch = _torch()
+ batch = _batch(torch)
+ inputs = _trainer_inputs(torch, batch)
+ inputs["old_per_token_logps"] = batch["logp_old"]
+ trainer = _variant_trainer("dapo", logps=batch["logp_new"], beta=0.1)
+ trainer._compute_loss(None, inputs)
+ expected = _metric("dapo", batch, beta=0.1).item()
+ assert trainer._metrics["train"]["kl"] == [pytest.approx(expected, rel=1e-12)]