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(grpo): allow grpo_beta: 0 for KL-free recipes (#1247) (#1295)
Nurkhan Esenbek61fac7f85b28
diff --git a/changelog.d/0.75.1/1295.changed.md b/changelog.d/0.75.1/1295.changed.mdnew file mode 100644index 00000000..dd685170--- /dev/null+++ b/changelog.d/0.75.1/1295.changed.md@@ -0,0 +1 @@+- Allow `training.grpo_beta: 0` to configure KL-free GRPO recipes (DAPO, Dr. GRPO), skipping the reference-model forward pass; refuse `grpo_beta: 0` with beta-adjusting reward-hack mitigation modes (`kl_control`, `pid_lagrangian`) at config load (#1247 by @kok-o in #1295).diff --git a/docs/training.md b/docs/training.mdindex ce6a96a3..8b818082 100644--- a/docs/training.md+++ b/docs/training.md@@ -702,9 +702,9 @@ reference policy, where trl's own GRPO loss puts it: trl's per-token estimatorsame way as that variant's policy term. `rft` applies it only to the acceptedcompletions it trains on. The β that the reward-hack controller sets at runtime(`kl_control` / `pid_lagrangian`) reaches every variant the same way.-`grpo_beta` must be greater than zero, so a KL-free run, the setting the DAPO-paper uses, cannot be configured yet-([#1247](https://github.com/MakazhanAlpamys/Soup/issues/1247)).+Set `grpo_beta: 0` for a KL-free run (no KL penalty against the reference policy,+skipping the reference forward pass entirely), as used by the published DAPO and+Dr. GRPO recipes ([#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 stockloss: the batch mean of that per-token estimate over the completion tokens (over the@@ -1197,7 +1197,7 @@ data:training:epochs: 3lr: 1e-5- grpo_beta: 0.1+ grpo_beta: 0.1 # KL penalty; 0 = KL-free (DAPO / Dr. GRPO)num_generations: 4reward_fn: accuracy # or 'format', or path to custom .pylora:diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 7c05d9dd..937388a3 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1,5 +1,6 @@"""Pydantic schemas for soup.yaml config — single source of truth."""+import mathimport refrom typing import Any, Dict, List, Literal, Optional, Union@@ -1389,8 +1390,26 @@ class TrainingConfig(BaseModel):)# GRPO-specificgrpo_beta: float = Field(- default=0.1, gt=0, description="GRPO beta — KL penalty coefficient"+ default=0.1,+ ge=0.0,+ allow_inf_nan=False,+ description=(+ "GRPO beta - KL penalty coefficient (default 0.1). Set to 0 to "+ "disable the KL penalty entirely (KL-free recipes like DAPO and "+ "Dr. GRPO, #1247)."+ ),)++ @field_validator("grpo_beta", mode="before")+ @classmethod+ def _validate_grpo_beta_field(cls, v: Any) -> Any:+ if isinstance(v, bool):+ raise ValueError("grpo_beta must not be a boolean")+ if isinstance(v, (int, float)):+ fval = float(v)+ if math.isnan(fval) or math.isinf(fval):+ raise ValueError("grpo_beta must be finite")+ return vnum_generations: int = Field(default=4, ge=2, description="Number of generations per prompt for GRPO")@@ -4456,7 +4475,7 @@ def _customized_reward_hack_tunables(tcfg: Any) -> list[str]:return offenders-def _validate_reward_hack_controller(tcfg: Any) -> None:+def _validate_reward_hack_controller(tcfg: Any, task: str = "grpo") -> None:"""Validate the mitigation-controller config (only when a mode is active).Numeric consistency (β floor < ceil, release < trip band), the signal@@ -4510,6 +4529,15 @@ def _validate_reward_hack_controller(tcfg: Any) -> None:"exclusive with ref_model_ema_alpha (both drive the KL/ref ""dynamics); pick one")+ if task == "grpo":+ beta_val = getattr(tcfg, "grpo_beta", None)+ if beta_val is not None and not isinstance(beta_val, bool) and float(beta_val) == 0.0:+ raise ValueError(+ "grpo_beta: 0 is mutually exclusive with "+ f"reward_hack_mitigation={tcfg.reward_hack_mitigation!r} "+ "(the mitigation controller requires a positive beta to steer); "+ "use grpo_beta > 0 or disable mitigation"+ )# v0.71.26 Stage 2 — PID / rollback tunables require pid_lagrangian mode.if tcfg.reward_hack_mitigation != "pid_lagrangian":stage2_offenders = [@@ -7500,7 +7528,7 @@ class SoupConfig(BaseModel):# Controller config (numeric bounds, signal allowlist, β-schedule# mutual exclusion) only when a mode is active.if mitigation != "off":- _validate_reward_hack_controller(tcfg)+ _validate_reward_hack_controller(tcfg, task=self.task)return self@model_validator(mode="after")diff --git a/src/soup_cli/utils/grpo_variants.py b/src/soup_cli/utils/grpo_variants.pyindex 294d8352..01cea390 100644--- a/src/soup_cli/utils/grpo_variants.py+++ b/src/soup_cli/utils/grpo_variants.py@@ -415,7 +415,7 @@ def _per_token_kl(variant: str, beta: float, logp_new, reference_logp):if reference_logp is None:# Inside the trainer this text reaches the user through the #159- # fallback warning, where beta=0 is no remedy (grpo_beta must be > 0),+ # fallback warning (for a KL-free run, set grpo_beta: 0; #1247),# so it names the batch key trl should have filled instead.raise ValueError(f"grpo_variant={variant!r} with beta={beta} needs reference_logp, the "diff --git a/tests/test_grpo.py b/tests/test_grpo.pyindex 7910b9b2..8041bc15 100644--- a/tests/test_grpo.py+++ b/tests/test_grpo.py@@ -40,14 +40,24 @@ class TestGRPOConfig:)assert cfg.training.grpo_beta == pytest.approx(0.04)- def test_grpo_beta_must_be_positive(self):- """grpo_beta must be > 0."""+ def test_grpo_beta_zero_allowed(self):+ """grpo_beta: 0 is allowed for KL-free recipes (#1247)."""+ cfg = SoupConfig(+ base="some-model",+ task="grpo",+ data={"train": "./data.jsonl"},+ training={"grpo_beta": 0},+ )+ assert cfg.training.grpo_beta == 0.0++ def test_grpo_beta_negative_rejected(self):+ """grpo_beta must be >= 0."""with pytest.raises(Exception):SoupConfig(base="some-model",task="grpo",data={"train": "./data.jsonl"},- training={"grpo_beta": 0},+ training={"grpo_beta": -0.01},)def test_num_generations_default(self):diff --git a/tests/test_issue1247_grpo_beta_zero.py b/tests/test_issue1247_grpo_beta_zero.pynew file mode 100644index 00000000..bfee185e--- /dev/null+++ b/tests/test_issue1247_grpo_beta_zero.py@@ -0,0 +1,280 @@+"""Tests for #1247: allow grpo_beta: 0 for KL-free GRPO recipes."""++from __future__ import annotations++from pathlib import Path++import pytest+from pydantic import ValidationError++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import TrainingConfig++VARIANTS = ("standard", "gspo", "dapo", "dr_grpo", "bnpo", "two_sided", "rft")+++class TestSchemaGrpoBetaZero:+ """Schema-level validation of grpo_beta: 0."""++ @pytest.mark.parametrize("variant", VARIANTS)+ def test_grpo_beta_zero_loads_for_all_variants(self, variant):+ delta_line = " grpo_delta: 0.2\n" if variant in ("two_sided", "gspo") else ""+ cfg_str = f"""+base: test-model+task: grpo+data:+ train: dummy.jsonl+ max_length: 64+training:+ grpo_beta: 0+ grpo_variant: {variant}+{delta_line}+"""+ cfg = load_config_from_string(cfg_str)+ assert cfg.training.grpo_beta == 0.0++ def test_default_grpo_beta_unchanged(self):+ cfg_str = """+base: test-model+task: grpo+data:+ train: dummy.jsonl+ max_length: 64+"""+ cfg = load_config_from_string(cfg_str)+ assert cfg.training.grpo_beta == 0.1++ def test_grpo_beta_zero_float_loads(self):+ tcfg = TrainingConfig(grpo_beta=0.0)+ assert tcfg.grpo_beta == 0.0++ def test_grpo_beta_negative_rejected(self):+ with pytest.raises(ValidationError):+ TrainingConfig(grpo_beta=-0.01)++ def test_grpo_beta_bool_rejected(self):+ with pytest.raises(ValidationError, match="grpo_beta must not be a boolean"):+ TrainingConfig(grpo_beta=True)+ with pytest.raises(ValidationError, match="grpo_beta must not be a boolean"):+ TrainingConfig(grpo_beta=False)++ def test_grpo_beta_nan_inf_rejected(self):+ with pytest.raises(ValidationError, match="grpo_beta must be finite"):+ TrainingConfig(grpo_beta=float("nan"))+ with pytest.raises(ValidationError, match="grpo_beta must be finite"):+ TrainingConfig(grpo_beta=float("inf"))+++class TestRewardHackMitigationConflict:+ """grpo_beta: 0 is mutually exclusive with beta-adjusting mitigation."""++ @pytest.mark.parametrize("mode", ["kl_control", "pid_lagrangian"])+ def test_grpo_beta_zero_refused_with_beta_adjusting_mitigation(self, mode):+ cfg_str = f"""+base: test-model+task: grpo+data:+ train: dummy.jsonl+ max_length: 64+training:+ grpo_beta: 0+ reward_hack_detector: info_rm+ reward_hack_mitigation: {mode}+"""+ with pytest.raises(ValueError) as excinfo:+ load_config_from_string(cfg_str)+ err = str(excinfo.value)+ assert "grpo_beta" in err+ assert "reward_hack_mitigation" in err+ assert mode in err++ def test_grpo_beta_zero_accepted_with_log_only_mitigation(self):+ cfg_str = """+base: test-model+task: grpo+data:+ train: dummy.jsonl+ max_length: 64+training:+ grpo_beta: 0+ reward_hack_detector: info_rm+ reward_hack_mitigation: log_only+"""+ cfg = load_config_from_string(cfg_str)+ assert cfg.training.grpo_beta == 0.0+ assert cfg.training.reward_hack_mitigation == "log_only"+++class TestKernelLossBitForBit:+ """Variant loss with beta=0 matches KL-free loss bit-for-bit without reference."""++ @pytest.mark.parametrize("variant", ["gspo", "dapo", "dr_grpo", "bnpo", "two_sided", "rft"])+ def test_variant_loss_matches_kl_free_bit_for_bit(self, variant):+ torch = pytest.importorskip("torch")+ from soup_cli.utils.grpo_variants import apply_variant_loss++ gen = torch.Generator().manual_seed(1247)+ dtype = torch.float64+ logp_new = (-2.0 * torch.rand(3, 5, generator=gen, dtype=dtype)).requires_grad_(True)+ logp_old = logp_new.detach() + 0.2 * torch.randn(3, 5, generator=gen, dtype=dtype)+ advantages = torch.tensor([1.0, -0.5, 0.75], dtype=dtype)+ mask = torch.tensor([[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [1, 1, 0, 0, 0]], dtype=dtype)+ delta = 0.2 if variant in ("two_sided", "gspo") else None++ # Call with beta=0.0 and NO reference_logp (simulates TRL skipping ref forward)+ loss_no_ref = apply_variant_loss(+ variant,+ logp_new=logp_new,+ logp_old=logp_old,+ advantages=advantages,+ beta=0.0,+ delta=delta,+ completion_mask=mask,+ reference_logp=None,+ )++ # Call with dummy reference+ dummy_ref = logp_new.detach() + 5.0+ loss_with_ref = apply_variant_loss(+ variant,+ logp_new=logp_new,+ logp_old=logp_old,+ advantages=advantages,+ beta=0.0,+ delta=delta,+ completion_mask=mask,+ reference_logp=dummy_ref,+ )++ assert torch.equal(loss_no_ref, loss_with_ref), (+ f"{variant}: loss with beta=0 changed when reference was provided"+ )+++class TestRealTrainerBetaZero:+ """Real GRPOTrainerWrapper on tiny CPU model skips reference forward when beta=0."""++ @pytest.mark.parametrize("variant", ["standard", "dapo", "dr_grpo"])+ def test_ref_forward_skipped_when_beta_zero(self, tmp_path, monkeypatch, variant):+ for mod in ("torch", "transformers", "peft", "trl", "datasets"):+ pytest.importorskip(mod)+ import yaml++ from soup_cli.trainer.grpo import GRPOTrainerWrapper+ from tests.test_issue1232_grpo_variant_kl import (+ _tiny_llama_dir,+ _write_tiny_tokenizer,+ )++ weights = _tiny_llama_dir(tmp_path)+ _write_tiny_tokenizer(weights)+ monkeypatch.chdir(tmp_path)++ cfg_dict = {+ "base": weights,+ "task": "grpo",+ "backend": "transformers",+ "modality": "text",+ "data": {"train": "train.jsonl", "max_length": 64, "chat_template": "chatml"},+ "training": {+ "batch_size": 2,+ "gradient_accumulation_steps": 1,+ "num_generations": 2,+ "reward_fn": "format",+ "quantization": "none",+ "epochs": 1,+ "grpo_variant": variant,+ "grpo_beta": 0,+ "lora": {"r": 4, "alpha": 8, "target_modules": ["q_proj", "v_proj"]},+ },+ "output": str(tmp_path / "out"),+ }+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))+ wrapper = GRPOTrainerWrapper(cfg, device="cpu")+ wrapper.setup({"train": [{"prompt": "hi"} for _ in range(4)]})++ trainer = wrapper.trainer+ assert trainer.beta == 0.0++ batch = next(iter(trainer.get_train_dataloader()))+ inputs = trainer._prepare_inputs(batch)+ # When beta=0, trl skips computing ref_per_token_logps+ assert inputs.get("ref_per_token_logps") is None, (+ "TRL should skip reference forward when beta is 0.0"+ )++ # Ensure loss computation succeeds without error+ loss = trainer._compute_loss(trainer.model, inputs)+ assert loss is not None+ assert not loss.isnan()+++class TestTheRealTrainerComputesTheKlFreeLoss:+ """Acceptance 2 on the real trainer: at grpo_beta 0 every variant computes the+ KL-free loss itself (no #159 fallback to trl's stock loss), bit for bit."""++ @pytest.mark.parametrize("variant", ["gspo", "dapo", "dr_grpo", "bnpo", "two_sided", "rft"])+ def test_loss_and_gradient_equal_the_kl_free_loss(self, tmp_path, monkeypatch, variant):+ for mod in ("torch", "transformers", "peft", "trl", "datasets"):+ pytest.importorskip(mod)+ import torch++ from tests.test_issue1232_grpo_variant_kl import (+ _build_real,+ _loss_and_grad,+ _pre_1232_loss,+ )++ trainer = _build_real(tmp_path, monkeypatch, variant, grpo_beta=0.0).trainer+ torch.manual_seed(0)+ inputs = trainer._prepare_inputs(next(iter(trainer.get_train_dataloader())))+ assert inputs.get("ref_per_token_logps") is None+ rows = inputs["advantages"].shape[0]+ inputs["advantages"] = torch.tensor([1.0, -1.0] * (rows // 2))+ trainer.model.train()+ trainer.current_gradient_accumulation_steps = 1++ loss, grad = _loss_and_grad(trainer, lambda: trainer._compute_loss(trainer.model, inputs))+ assert not trainer._soup_fallback_warned, f"{variant}: fell back to trl's stock loss"++ def kl_free():+ input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1)+ attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1)+ logp, _ = trainer._get_per_token_logps_and_entropies(+ trainer.model,+ input_ids,+ attention_mask,+ inputs["completion_ids"].size(1),+ compute_entropy=False,+ )+ old = inputs.get("old_per_token_logps")+ return _pre_1232_loss(+ torch,+ variant,+ logp_new=logp,+ logp_old=logp.detach() if old is None else old,+ advantages=inputs["advantages"],+ delta=getattr(trainer, "_soup_grpo_delta", None),+ completion_mask=inputs["completion_mask"],+ )++ expected, expected_grad = _loss_and_grad(trainer, kl_free)+ assert torch.equal(loss, expected), (variant, loss.item(), expected.item())+ assert torch.equal(grad, expected_grad), f"{variant}: gradient is not the KL-free one"+++class TestDocumentationMentionsKlFree:+ def test_training_docs_say_how_to_run_a_kl_free_recipe(self):+ docs = Path(__file__).parents[1] / "docs" / "training.md"+ content = " ".join(docs.read_text(encoding="utf-8").split())+ assert "`grpo_beta` must be greater than zero" not in content+ assert "Set `grpo_beta: 0` for a KL-free run" in content++[email protected]("spelling", ["inf", "Infinity", "1e400", ".inf", ".nan", "'nan'"])+def test_grpo_beta_non_finite_yaml_spellings_rejected(spelling):+ with pytest.raises(ValueError, match="grpo_beta"):+ load_config_from_string(+ "base: test-model\ntask: grpo\ndata:\n train: dummy.jsonl\n"+ f"training:\n grpo_beta: {spelling}\n"+ )