A straightforward method for training your LLM, from downloading data to generating text.
feat(grpo): Dr. GRPO, DAPO and GSPO options
FareedKhan-dev41af875aa4ed
diff --git a/config/post_training_config.py b/config/post_training_config.pyindex d6cb09a..11e576b 100644--- a/config/post_training_config.py+++ b/config/post_training_config.py@@ -31,6 +31,9 @@ OptimizerName = Literal["adamw", "muon"]Schedule = Literal["cosine", "wsd", "linear"]PreferenceLoss = Literal["dpo", "ipo", "simpo", "orpo", "kto"]RewardSource = Literal["verifier", "rm"]+AdvantageNorm = Literal["std", "none"]+LossAggregation = Literal["token-mean", "seq-mean-token-mean", "seq-mean-token-sum-norm"]+RatioLevel = Literal["token", "sequence"]class ConfigError(ValueError):@@ -226,8 +229,13 @@ class GRPOConfig(BaseModelConfig):temperature: float = 1.0top_p: float = 1.0grpo_epochs: int = 1- clip: float = 0.2+ clip: float = 0.2 # lower clip range (and upper, unless clip_high is set)+ clip_high: float | None = None # DAPO "clip-higher": a larger upper range, e.g. 0.28kl_coef: float = 0.04 # KL(policy || ref) penalty term in the loss+ adv_norm: AdvantageNorm = "std" # "none" = Dr. GRPO (no division by the group std)+ loss_agg: LossAggregation = "token-mean" # how token losses are averaged, see grpo.py+ ratio_level: RatioLevel = "token" # "sequence" = GSPO (one importance ratio per answer)+ filter_groups: bool = False # DAPO dynamic sampling: skip groups with no reward spreadlr: float = 1e-6grad_clip: float = 1.0eval_every: int = 50@@ -236,7 +244,7 @@ class GRPOConfig(BaseModelConfig):def __post_init__(self) -> None:super().__post_init__()_check(self.group_size >= 2, "group_size must be at least 2 (the group is the baseline)")- _check(self.clip > 0, "clip must be positive")+ _check(self.clip > 0 and (self.clip_high is None or self.clip_high > 0), "clip ranges must be positive")# Tiny config for fast smoke tests (CPU or a single GPU, seconds not hours).diff --git a/configs/grpo.json b/configs/grpo.jsonindex b3691c9..f253cea 100644--- a/configs/grpo.json+++ b/configs/grpo.json@@ -13,7 +13,12 @@"top_p": 1.0,"grpo_epochs": 1,"clip": 0.2,+ "clip_high": null,"kl_coef": 0.04,+ "adv_norm": "std",+ "loss_agg": "token-mean",+ "ratio_level": "token",+ "filter_groups": false,"lr": 1e-06,"grad_clip": 1.0,"eval_every": 50,diff --git a/scripts/train_grpo.py b/scripts/train_grpo.pyindex 0b1ccc0..114d63a 100644--- a/scripts/train_grpo.py+++ b/scripts/train_grpo.py@@ -3,11 +3,16 @@ GRPO / RLVR on GSM8K (DeepSeek-R1 style), from scratch -- no critic, group-relatadvantages, verifiable reward.Per iteration: for each prompt sample a group of G completions, score each with the GSM8K-verifier, compute group-relative advantages, and update with a token-level clipped-surrogate + KL-to-reference penalty. An arithmetic warm-up curriculum runs first so the-policy gets non-zero reward variance before facing full GSM8K.+verifier, compute group-relative advantages, and update with a clipped surrogate ++KL-to-reference penalty. An arithmetic warm-up curriculum runs first so the policy gets+non-zero reward variance before facing full GSM8K.- python scripts/train_grpo.py+The 2025 variants are flags (see src/post_training/grpo.py for what each one changes):++ python scripts/train_grpo.py # GRPO (repo default)+ python scripts/train_grpo.py --adv_norm none --loss_agg seq-mean-token-sum-norm # Dr. GRPO+ python scripts/train_grpo.py --clip_high 0.28 --filter_groups true --kl_coef 0 # DAPO+ python scripts/train_grpo.py --ratio_level sequence --clip 0.0003 --clip_high 0.0004 # GSPOtorchrun --standalone --nproc_per_node=2 scripts/train_grpo.py"""@@ -83,13 +88,22 @@ def main():responses = [decode(seqs[i, plens[i]:seq_lens[i]].tolist()) for i in range(len(prompts))]rewards = torch.tensor([reward_gsm8k(responses[i], golds[i]) for i in range(len(prompts))],device=ctx.device, dtype=torch.float32)- adv = group_advantages(rewards, G)+ adv = group_advantages(rewards, G, scale=cfg.adv_norm)with torch.no_grad(), amp_autocast(cfg.amp_dtype, ctx.device):old_logp, _ = compute_logprobs(policy, seqs, rmask, temperature=cfg.temperature, requires_grad=False)ref_logp, _ = compute_logprobs(ref, seqs, rmask, temperature=cfg.temperature, requires_grad=False)old_logp, ref_logp = old_logp.float(), ref_logp.float()+ # DAPO dynamic sampling: a group where every answer got the same reward has zero+ # advantage everywhere, so it only adds the KL term and compute. Its tokens are masked+ # out of the loss. (Rows are masked, not removed, so every GPU still runs the same+ # number of backward passes, which DDP requires.)+ keep = torch.ones(seqs.size(0), dtype=torch.bool, device=ctx.device)+ if cfg.filter_groups:+ keep = (rewards.view(-1, G).std(dim=1) > 1e-6).repeat_interleave(G)+ train_mask = resp & keep[:, None]+policy.train()N = seqs.size(0)agg = {"loss": 0.0, "kl": 0.0, "clipfrac": 0.0, "n": 0}@@ -97,10 +111,13 @@ def main():perm = torch.randperm(N, device=ctx.device)for s in range(0, N, max(1, G)): # minibatch ~ one group's worthmb = perm[s:s + max(1, G)]+ if not ctx.enabled and not keep[mb].any():+ continue # nothing to learn from these rows (only safe to skip on a single process)with amp_autocast(cfg.amp_dtype, ctx.device):new_logp, _ = compute_logprobs(policy_ddp, seqs[mb], rmask[mb], temperature=cfg.temperature, requires_grad=True)- loss, st = grpo_loss(new_logp.float(), old_logp[mb], ref_logp[mb], adv[mb], resp[mb],- clip=cfg.clip, kl_coef=cfg.kl_coef)+ loss, st = grpo_loss(new_logp.float(), old_logp[mb], ref_logp[mb], adv[mb], train_mask[mb],+ clip=cfg.clip, kl_coef=cfg.kl_coef, clip_high=cfg.clip_high,+ loss_agg=cfg.loss_agg, ratio_level=cfg.ratio_level, max_len=cfg.rollout_len)optimizer.zero_grad(set_to_none=True)loss.backward()torch.nn.utils.clip_grad_norm_(policy_ddp.parameters(), cfg.grad_clip)diff --git a/src/post_training/grpo.py b/src/post_training/grpo.pyindex 6c9ba64..f5d527e 100644--- a/src/post_training/grpo.py+++ b/src/post_training/grpo.py@@ -1,70 +1,145 @@"""-GRPO (Group Relative Policy Optimization) core -- the DeepSeek-R1 RL algorithm.+GRPO (Group Relative Policy Optimization) core -- the DeepSeekMath / DeepSeek-R1 RL algorithm,+plus the switches that turn it into the 2025 follow-ups.GRPO drops PPO's value network. For each prompt it samples a GROUP of G completions,scores them with a verifiable reward, and uses the group's own mean/std to compute arelative advantage -- so the baseline is the group, not a learned critic. The update is a-token-level clipped surrogate plus a per-token KL penalty to the reference policy.+clipped surrogate plus a per-token KL penalty to the reference policy.++The variants differ in a few precise places, each one a keyword here:++================= ==========================================================================+variant what changes (keyword)+================= ==========================================================================+GRPO ``adv_norm="std"``; loss averaged per answer, then over answers+ (``loss_agg="seq-mean-token-mean"``, the paper's formula)+DAPO all tokens of the batch averaged together (``loss_agg="token-mean"``), a+ larger upper clip ``clip_high`` ("clip-higher", keeps exploration alive),+ groups with no reward spread skipped (``filter_groups`` in the trainer),+ usually ``kl_coef=0``+Dr. GRPO no division by the group std (``adv_norm="none"``) and a constant length+ normalizer (``loss_agg="seq-mean-token-sum-norm"``); both remove biases+ toward long wrong answers and toward easy/hard prompts+GSPO one importance ratio per answer, the length-normalized sequence likelihood+ ratio (``ratio_level="sequence"``), clipped with a tiny range (~3e-4)+================= ==========================================================================++The trainer default (``token-mean``, symmetric clip, std-normalized advantages) is exactly+what this repo has always run."""from __future__ import annotations+from typing import Literal+import torch+from jaxtyping import Bool, Float+from torch import Tensor++from src.post_training.utils import masked_mean, masked_mean_per_row-from src.post_training.utils import masked_mean+AdvantageNorm = Literal["std", "none"]+LossAggregation = Literal["token-mean", "seq-mean-token-mean", "seq-mean-token-sum-norm"]+RatioLevel = Literal["token", "sequence"]-def group_advantages(rewards: torch.Tensor, group_size: int, eps: float = 1e-4) -> torch.Tensor:+def group_advantages(+ rewards: Float[Tensor, " n"], group_size: int, eps: float = 1e-4, scale: AdvantageNorm = "std"+) -> Float[Tensor, " n"]:"""Group-relative advantage: ``(r - group_mean) / (group_std + eps)``.``rewards`` is (num_prompts * group_size,) laid out group-contiguously (all G samples- of prompt 0, then prompt 1, ...). Returns advantages of the same shape.+ of prompt 0, then prompt 1, ...). Returns advantages of the same shape. With+ ``scale="none"`` (Dr. GRPO) the advantage is just ``r - group_mean``: dividing by the std+ gives prompts that are almost always solved (or failed) a disproportionately large weight."""r = rewards.view(-1, group_size)- mean = r.mean(dim=1, keepdim=True)- std = r.std(dim=1, keepdim=True)- adv = (r - mean) / (std + eps)+ adv = r - r.mean(dim=1, keepdim=True)+ if scale == "std":+ adv = adv / (r.std(dim=1, keepdim=True) + eps)return adv.reshape(-1)-def k3_kl(new_logp: torch.Tensor, ref_logp: torch.Tensor) -> torch.Tensor:+def k3_kl(new_logp: Float[Tensor, "*shape"], ref_logp: Float[Tensor, "*shape"]) -> Float[Tensor, "*shape"]:"""Per-token unbiased, non-negative KL estimator (Schulman's k3) for KL(policy||ref)."""diff = ref_logp - new_logpreturn torch.exp(diff) - diff - 1.0+def aggregate_token_loss(+ per_token: Float[Tensor, "batch steps"],+ mask: Bool[Tensor, "batch steps"],+ mode: LossAggregation = "token-mean",+ max_len: int | None = None,+) -> Float[Tensor, ""]:+ """+ Reduce a per-token loss to one number. The choice matters more than it looks:++ - ``token-mean``: every token in the batch counts the same. Long answers get more say,+ which is what DAPO wants (long wrong answers are penalized in full).+ - ``seq-mean-token-mean``: average inside each answer, then across answers. Every answer+ counts the same, so each token of a long answer counts less. This is the GRPO paper.+ - ``seq-mean-token-sum-norm``: sum inside each answer, divide by a constant (the generation+ budget ``max_len``), then average. Dr. GRPO: unbiased and still length-independent.+ """+ m = mask.to(per_token.dtype)+ if mode == "token-mean":+ return masked_mean(per_token, m)+ if mode == "seq-mean-token-mean":+ return masked_mean_per_row(per_token, m).mean()+ if mode == "seq-mean-token-sum-norm":+ return ((per_token * m).sum(dim=-1) / float(max_len or per_token.size(-1))).mean()+ raise ValueError(f"unknown loss aggregation {mode!r}")++def grpo_loss(- new_logp: torch.Tensor,- old_logp: torch.Tensor,- ref_logp: torch.Tensor,- advantages: torch.Tensor,- resp_mask: torch.Tensor,+ new_logp: Float[Tensor, "batch steps"],+ old_logp: Float[Tensor, "batch steps"],+ ref_logp: Float[Tensor, "batch steps"],+ advantages: Float[Tensor, " batch"],+ resp_mask: Bool[Tensor, "batch steps"],clip: float = 0.2,kl_coef: float = 0.04,-) -> tuple[torch.Tensor, dict]:+ *,+ clip_high: float | None = None,+ loss_agg: LossAggregation = "token-mean",+ ratio_level: RatioLevel = "token",+ max_len: int | None = None,+) -> tuple[Float[Tensor, ""], dict[str, float]]:"""- Token-level clipped surrogate + KL penalty.+ Clipped surrogate + KL penalty, with the variant switches described in the module docstring.Args:new_logp/old_logp/ref_logp: (B, L) per-token log-probs (policy / sampling / ref).advantages: (B,) one scalar per completion, broadcast over its tokens.resp_mask: (B, L) bool over response tokens.+ clip, clip_high: the ratio may move in ``[1 - clip, 1 + clip_high]`` (``clip_high``+ defaults to ``clip``).+ loss_agg: how per-token terms are averaged (token-level ratio only).+ ratio_level: ``"token"`` (GRPO/DAPO) or ``"sequence"`` (GSPO).+ max_len: the constant normalizer for ``seq-mean-token-sum-norm``.Returns:(loss, stats) with mean KL and clip fraction for logging."""+ high = clip if clip_high is None else clip_highadv = advantages[:, None]- ratio = torch.exp(new_logp - old_logp)- surr1 = ratio * adv- surr2 = torch.clamp(ratio, 1.0 - clip, 1.0 + clip) * adv- surrogate = torch.min(surr1, surr2)kl = k3_kl(new_logp, ref_logp)- per_token = surrogate - kl_coef * kl- loss = -masked_mean(per_token, resp_mask)- stats = {- "kl": masked_mean(kl, resp_mask).item(),- "clipfrac": masked_mean(((ratio - 1.0).abs() > clip).float(), resp_mask).item(),- }+ if ratio_level == "sequence":+ # GSPO: s_i = exp(mean_t log(pi/pi_old)), one ratio for the whole answer.+ log_ratio = masked_mean_per_row(new_logp - old_logp, resp_mask)+ ratio = torch.exp(log_ratio)+ surrogate = torch.min(ratio * advantages, torch.clamp(ratio, 1.0 - clip, 1.0 + high) * advantages)+ loss = -(surrogate - kl_coef * masked_mean_per_row(kl, resp_mask)).mean()+ clipped = ((ratio < 1.0 - clip) | (ratio > 1.0 + high)).float().mean()+ else:+ ratio = torch.exp(new_logp - old_logp)+ surrogate = torch.min(ratio * adv, torch.clamp(ratio, 1.0 - clip, 1.0 + high) * adv)+ loss = -aggregate_token_loss(surrogate - kl_coef * kl, resp_mask, loss_agg, max_len)+ clipped = masked_mean(((ratio < 1.0 - clip) | (ratio > 1.0 + high)).float(), resp_mask)++ stats = {"kl": masked_mean(kl, resp_mask).item(), "clipfrac": clipped.item()}return loss, statsdiff --git a/tests/test_post_training_losses.py b/tests/test_post_training_losses.pyindex de0cabb..cd8e6cc 100644--- a/tests/test_post_training_losses.py+++ b/tests/test_post_training_losses.py@@ -1,12 +1,15 @@-"""The preference-optimization family: DPO, IPO, SimPO and conservative DPO."""+"""The preference-optimization family (DPO, IPO, SimPO, conservative DPO) and the GRPO variants."""from __future__ import annotations+import math+import pytestimport torchimport torch.nn.functional as Ffrom src.post_training.dpo import dpo_loss, implicit_accuracy, ipo_loss, simpo_loss+from src.post_training.grpo import aggregate_token_loss, group_advantages, grpo_lossdef _pairs():@@ -48,3 +51,49 @@ def test_simpo_is_reference_free_and_length_normalized() -> None:loss_long, _, _ = simpo_loss(2 * pc, 2 * pr, 2 * n, 2 * n, beta=2.0, gamma=0.5)assert torch.allclose(loss, loss_long)++def test_group_advantages_std_and_dr_grpo() -> None:+ r = torch.tensor([1.0, 0.0, 0.0, 0.0, 3.0, 1.0, 2.0, 2.0])+ std_adv = group_advantages(r, 4)+ centered = group_advantages(r, 4, scale="none")+ assert torch.allclose(centered, torch.tensor([0.75, -0.25, -0.25, -0.25, 1.0, -1.0, 0.0, 0.0]))+ assert torch.allclose(std_adv[:4] * r[:4].std(), centered[:4], atol=1e-3)+++def test_loss_aggregation_modes() -> None:+ per_token = torch.tensor([[1.0, 1.0, 1.0, 1.0], [4.0, 0.0, 0.0, 0.0]])+ mask = torch.tensor([[1, 1, 1, 1], [1, 0, 0, 0]], dtype=torch.bool)+ assert aggregate_token_loss(per_token, mask, "token-mean").item() == pytest.approx(8 / 5)+ assert aggregate_token_loss(per_token, mask, "seq-mean-token-mean").item() == pytest.approx((1 + 4) / 2)+ assert aggregate_token_loss(per_token, mask, "seq-mean-token-sum-norm", max_len=8).item() == pytest.approx((4 / 8 + 4 / 8) / 2)+++def test_grpo_default_is_unchanged_and_clip_higher_widens_the_range() -> None:+ torch.manual_seed(0)+ B, L = 4, 6+ old = torch.randn(B, L) - 2+ new = old + 0.25 # ratio = e^0.25 = 1.28 everywhere+ ref = old.clone()+ adv = torch.tensor([1.0, -1.0, 2.0, 0.5])+ mask = torch.ones(B, L, dtype=torch.bool)+ loss, stats = grpo_loss(new, old, ref, adv, mask, clip=0.2, kl_coef=0.0)+ ratio = math.exp(0.25)+ clipped = torch.tensor([min(ratio * a, min(max(ratio, 0.8), 1.2) * a) for a in adv.tolist()])+ assert loss.item() == pytest.approx(-clipped.mean().item(), rel=1e-5)+ assert stats["clipfrac"] == pytest.approx(1.0)+ _, wide = grpo_loss(new, old, ref, adv, mask, clip=0.2, clip_high=0.3, kl_coef=0.0)+ assert wide["clipfrac"] == pytest.approx(0.0) # 1.28 < 1.3: inside the clip-higher range+++def test_gspo_uses_one_ratio_per_answer() -> None:+ old = torch.zeros(2, 4)+ new = torch.tensor([[0.1, -0.1, 0.2, -0.2], [0.0, 0.0, 0.0, 0.0]]) # mean log-ratio 0 for both rows+ mask = torch.ones(2, 4, dtype=torch.bool)+ adv = torch.tensor([1.0, -1.0])+ loss, stats = grpo_loss(new, old, old, adv, mask, clip=1e-3, kl_coef=0.0, ratio_level="sequence")+ assert loss.item() == pytest.approx(0.0, abs=1e-6) # both sequence ratios are exactly 1+ assert stats["clipfrac"] == 0.0+ new.requires_grad_(True)+ loss, _ = grpo_loss(new, old, old, adv, mask, clip=1e-3, kl_coef=0.0, ratio_level="sequence")+ loss.backward()+ assert new.grad is not None and torch.allclose(new.grad[0], torch.full((4,), -0.125))