Skip to content

[rl] trainer: PolicyGradientLoss with DAPO, GRPO, CISPO, IcePop and DPPO losses - #6376

Open
tianyu-l wants to merge 1 commit into
mainfrom
policy-gradient-loss
Open

tianyu-l wants to merge 1 commit into
mainfrom
policy-gradient-loss

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

torchtitan's RL trainer has one policy surrogate, the PPO clip (DAPOLoss, and GRPOLoss as its symmetric case). Recent RL work replaces it: truncated importance sampling (CISPO / TIS), masked importance sampling (IcePop / MIS), and a trust region on each token's probability (DPPO). Score centering (arXiv 2609.20807, next in this stack) is validated with truncated and masked IS, not the PPO clip. DAPOLoss.__call__ holds everything a policy loss shares (trainer logprobs at the sampling temperature, dropping non-finite generator logprobs, the clamped ratio, normalization, seven metrics) inline next to the clip, so each new loss would copy it, as the open DPPO and score-centering PRs did.

This PR adds PolicyGradientLoss(Loss), which owns the shared body once, and four losses on it besides DAPO. It takes over #5474 (DPPO), coordinated with its author.

Example. Each loss is its per-token surrogate; the weight it puts on a token's score grad(log p), at A = 1, as a function of r = p / q:

r                       0.4    1.0    1.3    3.0    6.0
GRPOLoss (eps 0.2)      0.4    1.0    0      0      0      PPO clip zeroes up-weighted tokens
CISPOLoss (cap 2)       0.4    1.0    1.3    2.0    2.0    truncated, never zeroed
IcePopLoss [0.5, 5]     0      1.0    1.3    3.0    0      masked outside the band
DPPOLoss                min(r, 5), and 0 once sign(A) * (p - q) > 0.2: bounds the probability change, not the ratio
class CISPOLoss(PolicyGradientLoss):
    def token_loss(self, tokens: ScoredTokens) -> torch.Tensor:
        weight = torch.clamp(tokens.ratio, max=self.max_ratio).detach()
        return -tokens.advantages * weight * tokens.trainer_logprobs

What changed

  • losses/policy_gradient.py: PolicyGradientLoss with the template __call__ (the "loss" local-compile region), ScoredTokens (trainer and generator logprobs, the clamped ratio, the advantage; the generator logprob equals the detached trainer logprob off the loss mask, so a surrogate never sees a dropped token's non-finite logprob), abstract token_loss(tokens), optional token_metrics(tokens). _normalize moves here unchanged; _MAX_LOG_RATIO moves here as the public MAX_LOG_RATIO (same value, 10.0), since the tests and the next PR import it.
  • DAPOLoss keeps its config and ops (its __call__ body is moved, not rewritten). GRPOLoss is unchanged except that its Config subclasses PolicyGradientLoss.Config, which provides global_vocab_size.
  • losses/importance_sampling.py: CISPOLoss (weight min(r, max_ratio), max_ratio 2 as in verl and arXiv 2609.20807, the same name and meaning as DPPOLoss.max_ratio) and IcePopLoss (weight r in [0.5, 5], IcePop's default; without IcePop's separate PPO clip between policy versions, since the generator's logprobs are the old policy).
  • losses/dppo.py: DPPOLoss from [rl] One scoring step and one metrics step for every RL loss; add DPPOLoss #5474 (arXiv 2602.04879), rebuilt on the base: same ops, loss and metrics as [rl] One scoring step and one metrics step for every RL loss; add DPPOLoss #5474's; its config now rejects divergence_threshold <= 0 and max_ratio < 1, like CISPO's and IcePop's.
  • Recipes rl_dppo_qwen3_0_6b_varlen, rl_cispo_qwen3_0_6b_varlen and rl_icepop_qwen3_0_6b_varlen: rl_grpo_qwen3_0_6b_varlen with each loss. They live in torchtitan_recipes/tests/rl/alphabet_sort.py (unverified recipes) until convergence runs back them; the next PR adds their score-centering variants there too.

Relation to #5474

#5474 removed the same duplication with free functions each loss calls. This stack uses a base class because score centering, next, must apply to every policy loss: in the template it is added after token_loss and before normalization, so no loss can skip it or normalize it differently. #5474 is closed in favor of this PR; its DPPOLoss is here.

Numerics

DAPOLoss/GRPOLoss unchanged. Bitwise identical loss and grad_norm vs. main, deterministic + batch-invariant rl_grpo_qwen3_0_6b_varlen_batch_invariant (the RL loss-guard recipe) on real Qwen3-0.6B, seed 42, 10 steps, lockstep, trainer TP=2 + generator TP=2 (4x GB300; scripts/rl/loss_compare.py's config with TP 2):

Metric Steps Result
loss/mean 10 bitwise equal
trainer/grad_norm/mean 10 bitwise equal

New losses, end to end with the compiled "loss" region (the recipes' default local-compile regions): each new recipe and rl_grpo_qwen3_0_6b_varlen for 10 steps on real Qwen3-0.6B, seed 42, deterministic, lockstep, trainer TP=2 + generator TP=2 (4x GB300), not batch-invariant:

Recipe Mean reward, steps 1 -> 10 Fraction of tokens clipped / truncated / masked / dropped Final grad_norm
rl_grpo_qwen3_0_6b_varlen 0.482 -> 0.245 clipped 0.15% -> 0.09% 0.548
rl_dppo_qwen3_0_6b_varlen 0.482 -> 0.255 truncated 0, dropped 0 0.603
rl_cispo_qwen3_0_6b_varlen 0.482 -> 0.255 truncated 0 0.603
rl_icepop_qwen3_0_6b_varlen 0.482 -> 0.255 masked 0 0.603

All three compile and train with finite loss and gradients. Ten lockstep steps are too short to compare learning (reward is noisy at this length); with no token past a bound, DPPO, CISPO and IcePop all reduce to -A * sg(r) * log p, so their runs are bitwise identical to each other, as expected. GRPO differs because its surrogate's forward value is -min(r A, clip(r) A) and 0.1% of its tokens are clipped. DPPO's loss/mean is the REINFORCE surrogate, not comparable with GRPO's on one dashboard.

Batch-invariant mode runs the loss eagerly, so the compiled "loss" region was also checked against the old code directly: old vs. new DAPOLoss and GRPOLoss on random [1024, 151936] bf16 logits with non-finite and masked generator logprobs give bitwise equal loss, logits gradient and every metric (same keys and order), eager on CPU and compiled on GB300.

Longer runs with stale rollouts (100 steps, 3 seeds, target_offpolicy_steps=3, all five losses with and without score centering) are in #6378's description. Every loss trains there; some runs at this learning rate stop early from entropy collapse, with and without score centering.

Testing

  • test_losses.py::test_policy_loss_weights_each_token_score (new): for all five losses, d token_loss / d log p = -A * w with the weight in the table above, over ratios in [e^-2, e^2] so every clip, cap, band and trust region binds (catches a surrogate that drifts from its documented weight).
  • DPPO tests from [rl] One scoring step and one metrics step for every RL loss; add DPPOLoss #5474: the docstring example, a move of exactly the threshold, non-finite generator logprobs.
  • test_policy_loss_configs.py builds the three new recipes.
  • pytest tests/rl/unit_tests/cpu: 781 passed, 7 skipped.

Known issues / follow-ups

Stacked on #6395, which fixes main's lint (a profiler kwarg left behind by two concurrent merges) and is not part of score centering. Next in the stack: score centering (#6378), SGLang (#6379) and Verifiers (#6380) top-k logprobs, score centering for DPPOLoss (#6384), and scoring the top-k from the label's logprob (#6385).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 25, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@tianyu-l
tianyu-l added this pull request to stack #6377 November 25, 2026 05:35
@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 2s —— View job


Needs discussion: this overlaps open PR #5474, which takes the opposite design, and the new base class has only one real subclass so far. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Needs discussion -- #5474 (felipemello1) is still open and makes the same refactor with the opposite design (free functions, no base class). This PR's base class also has only one real subclass today, so maintainers need to pick one approach before either lands.

What this PR does. It moves the body of DAPOLoss.__call__ into a new abstract PolicyGradientLoss(Loss) that is a template method. That body covers tempered trainer logprobs, dropping tokens with a non-finite generator logprob, the clamped ratio, normalization, and the shared metrics. Subclasses implement token_loss(ratio, advantages) and, optionally, token_metrics(ratio). GRPOLoss stays a subclass of DAPOLoss, but its config now inherits from PolicyGradientLoss.Config and it sets both clip bounds from clip_eps. The op order is unchanged; I traced the moved code line by line and it matches.

Example.

# before: GRPOLoss rebuilds a DAPOLoss.Config, forwarding every field by hand
super().__init__(DAPOLoss.Config(ratio_clip_low=c.clip_eps,
                                 ratio_clip_high=c.clip_eps,
                                 global_vocab_size=c.global_vocab_size))
# after: shared fields come from PolicyGradientLoss.Config; DAPO only writes
def token_loss(self, ratio, advantages):
    return -torch.min(ratio * advantages, self._clip(ratio) * advantages)

Must fix

  1. Description: the "Summary (human-written)" section is empty.
  2. Overlap with #5474. #5474 targets the same duplication with losses/common.py (score_tokens + policy_metrics) and adds DPPOLoss as a second consumer. It deliberately rejects this PR's design ("Why not a base class with one __call__ and a per-loss hook? Each loss's __call__ shows its whole computation in ~25 lines; a hook would hide half of it in the base class"). It also deals with the per-loss kwargs problem (is_policy_age_0 and similar inputs breaking other losses), which this PR doesn't. Landing both would mean two ways of writing an RL loss. Please decide with felipemello1 which design wins and close the other, or say in this description why this one supersedes #5474.
  3. A base class with one subclass (.claude/rules/design.md: "Don't add ... a base class with a single subclass"). PolicyGradientLoss has one token_loss implementation, DAPO's; GRPO reuses it. Score centering, the next PR, doesn't need the base: it could go on DAPOLoss, and GRPO would inherit it. The first PR that actually needs the base is the truncated/masked IS loss. Either land PolicyGradientLoss in that PR, or reorder the stack so the second subclass arrives with the base.

Should consider

  • torchtitan/rl/trainer/losses/grpo.py:29-32 -- skips DAPOLoss.__init__ (inline comment).
Details
  • Checked the moved code: the op order in PolicyGradientLoss.__call__ matches the old DAPOLoss.__call__, and the metric keys are in the same order (ratio_clipped_frac is spliced in where it was). The only extra work is a second torch.clamp over [T] inside token_metrics, in no-grad and within the compiled region, so the cost is negligible.
  • All in-repo callers build the loss through DAPOLoss.Config / GRPOLoss.Config with the same field names. Nothing passed the **kwargs that the old GRPOLoss.__init__ accepted, so removing it is safe.
  • test_policy_loss_configs.py:61 still holds: its isinstance(..., (DAPOLoss.Config, GRPOLoss.Config)) check is unaffected by the change to the configs' base class.
  • test_losses.py imports the private _normalize from another module. That predates this PR (it used to come from dapo.py), so it isn't flagged here.

Not verified: the GB300 bitwise loss and grad_norm runs, and the compiled-region parity on GB300 (needs a GPU).

Comment thread torchtitan/rl/trainer/losses/grpo.py Resolved
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 9s —— View job


Needs discussion: the description now makes the case against #5474, but that PR is still open with no decision between the two designs, and the code hasn't changed since the last review. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Needs discussion -- the description now argues for the base class over #5474, but #5474 is still open and nobody has picked between the two designs. The code is the same as last review (still one commit, ff4be44).

What changed since the last review. No code changed. The description gained a "Relation to #5474" section. It argues that score centering (next PR) has to sit inside the template __call__, between token_loss and normalization, so no policy loss can skip it or normalize it differently. It says optional inputs added to the shared __call__ reach every loss. And it says truncated-IS and masked-IS later in the stack add two more surrogates.

Example. Here is the case the description uses against #5474. DPPOLoss (#5474) drops a token when sign(A) * (p - p_gen) > threshold. p - p_gen = q * (ratio - 1) depends on q as well as on ratio, so token_loss(ratio, advantages) can't express it without widening the abstract signature for every subclass. That matches #5474's diff. It means the template fits ratio-only surrogates (PPO/DAPO clip, truncated/masked IS) and needs a signature change for anything else.

Earlier must-fix items

  1. Empty "Summary (human-written)" -- still open. The author has to write it; agents leave it blank.
  2. Overlap with #5474 -- partly resolved. The description now explains why this design should win, and the DPPO point above holds up against #5474's code. #5474 (felipemello1) is still open with no reply. Its description rejects this design on purpose ("a hook would hide half of it in the base class"). Please settle this with felipemello1, then close or rebase one of the two PRs so the repo doesn't end up with two ways to write an RL loss.
  3. Base class with one subclass -- answered in the description, so no longer blocking on its own. The case for it is the stack: score centering needs a single template, and truncated/masked IS are the second and third surrogates. If the IS PRs stall, PolicyGradientLoss is left with one implementation. Land the stack together, or at least don't land this ahead of score centering.

Should consider (still open)

  • torchtitan/rl/trainer/losses/grpo.py:29-32 -- skips DAPOLoss.__init__ and sets its attributes by hand. See the earlier inline comment; it is unchanged.

No new problems found. I re-traced the moved __call__ against the base: the op order and metric key order are unchanged.

Not verified: the GB300 bitwise loss/grad_norm and compiled-region parity runs (need a GPU).

@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch 2 times, most recently from 8a47832 to cb29656 Compare November 25, 2026 05:59
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 5s —— View job


Needs discussion: the GRPOLoss init fix is resolved, but #5474 is still open with no decision between the two designs. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Needs discussion -- the code change from the last review is fine, but #5474 is still open with no reply, so nobody has chosen between the two designs.

What changed since the last review. The PR is now one commit, cb29656, replacing ff4be44. GRPOLoss no longer has its own __init__. Instead, GRPOLoss.Config defines read-only ratio_clip_low/ratio_clip_high properties that return clip_eps, so construction runs through the normal DAPOLoss.__init__ -> PolicyGradientLoss.__init__ chain. The rest of the diff is the same as before.

Example.

c = GRPOLoss.Config(clip_eps=0.3)
[f.name for f in dataclasses.fields(c)]   # ['global_vocab_size', 'clip_eps'] -- properties are not fields
loss = c.build()                          # GRPOLoss(config=replace(c)) -> DAPOLoss.__init__
loss.ratio_clip_low, loss.ratio_clip_high # (0.3, 0.3), read through the properties

Configurable.Config.to_dict, traverse, and build all walk dataclasses.fields() (torchtitan/config/configurable.py:51-169). The properties never show up in serialization or traversal, and replace(self) in build() keeps clip_eps. Setting ratio_clip_low on a GRPO config through --override fails loudly with AttributeError (the property has no setter), which is the right result.

Earlier must-fix items

  1. Empty "Summary (human-written)" -- still open. The author has to write it.
  2. Overlap with #5474 -- still open. The description argues for this design, but #5474 (felipemello1) is still open, has had no new comments or reviews, and its description still rejects a base-class hook design. Please settle this with felipemello1 and close or rebase one of the two PRs.
  3. Base class with one subclass -- unchanged since the last review: acceptable only as part of the stack. Don't land this ahead of score centering. If the truncated/masked IS PRs stall, PolicyGradientLoss is left with one surrogate.

Resolved

  • grpo.py skipping DAPOLoss.__init__ -- fixed by the config properties.

No new problems in cb29656.

Not verified: the GB300 bitwise loss/grad_norm and compiled-region parity runs (need a GPU). I couldn't run the CPU loss tests in this environment because Python execution was not permitted.

Base automatically changed from sglang-reject-original-logprob to main November 25, 2026 06:01
@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch 2 times, most recently from 3b6a42e to 11e37ff Compare November 25, 2026 06:04
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 53s —— View job


Needs discussion: 11e37ff goes back to main's GRPOLoss.__init__ and has no new problems, but #5474 is still open with no reply, so the two designs haven't been settled. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Needs discussion -- the new commit is fine, but #5474 is still open and nobody has replied there (no activity since 2026-10-18), so the two designs still haven't been settled.

What changed since the last review. The PR is still one commit, now 11e37ff instead of cb29656. The GRPOLoss.Config properties are gone. GRPOLoss.__init__ (grpo.py:29-37) is back to the version on main: it builds a DAPOLoss.Config with both clip bounds set to clip_eps and calls super().__init__. The only remaining change in grpo.py is the Config base class (Loss.Config -> PolicyGradientLoss.Config), which matches the description. dapo.py and policy_gradient.py are the same as in the last review.

Example.

c = GRPOLoss.Config(clip_eps=0.3, global_vocab_size=V)
loss = c.build()
# GRPOLoss.__init__ -> DAPOLoss.__init__(DAPOLoss.Config(0.3, 0.3, V))
#                   -> PolicyGradientLoss.__init__  (sets global_vocab_size)
loss.ratio_clip_low, loss.ratio_clip_high, loss.global_vocab_size  # (0.3, 0.3, V)

Construction still runs through the normal super() chain, so the earlier concern about skipping DAPOLoss.__init__ stays resolved. This version is also smaller than the properties one.

Earlier must-fix items

  1. Empty "Summary (human-written)" -- still open. The author has to write it.
  2. Overlap with #5474 -- still open. The description argues for the base-class design, but #5474 (felipemello1) is still open with no reply, and its description still rejects this approach. Please settle it with felipemello1, then close or rebase one of the two PRs.
  3. Base class with one subclass -- unchanged, and acceptable only as part of the stack. Don't land this ahead of score centering. If the truncated/masked IS PRs stall, PolicyGradientLoss ends up with a single surrogate.

No new problems in 11e37ff.

Details
  • GRPOLoss.__init__ forwards **kwargs to DAPOLoss.__init__, which doesn't accept any. That is the same on main, and no in-repo caller passes kwargs, so this PR doesn't introduce it. If someone touches this later, they could drop the **kwargs.
  • I re-checked the PolicyGradientLoss.__call__ op order and the metric key order (loss/ratio_clipped_frac sits between loss/ratio_mean and bit_wise/logprob_diff/mean) against the old DAPOLoss.__call__. Both are unchanged.
  • I checked the PolicyGradientLoss docstring example (ratio=1.65, clip_high=0.2, so -min(1.65, 1.2) = -1.2), and it is consistent with DAPOLoss.token_loss.

Not verified: the GB300 bitwise loss/grad_norm runs and the compiled-region parity check (both need a GPU).

@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch from 11e37ff to 57f7d0a Compare November 25, 2026 06:29
@tianyu-l tianyu-l changed the title [rl] trainer: PolicyGradientLoss base for DAPOLoss and GRPOLoss [rl] trainer: PolicyGradientLoss with DAPO, GRPO, CISPO, IcePop and DPPO losses Nov 25, 2026
@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch from 57f7d0a to 2fe38f1 Compare November 25, 2026 06:42

@dataclass(kw_only=True, slots=True)
class Config(Loss.Config):
class Config(PolicyGradientLoss.Config):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should inherit DAPOLoss.Config?

@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 2s —— View job


Approve, with one item to address before merging: 69d143b fixes both should-consider items from the last review (CISPO's cap is now max_ratio, and the test-recipe module's docstring now says where unverified recipes go), but the human-written summary is still empty. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. 69d143b fixes both should-consider items from the last review. The empty human-written summary is the only thing left.

What this PR does. It moves the shared body of DAPOLoss.__call__ into PolicyGradientLoss, a template __call__ inside the "loss" local-compile region. That body does the tempered trainer logprobs, drops tokens whose generator logprob is non-finite, computes the clamped ratio, normalizes, and builds the shared metrics. Each surrogate then implements only token_loss(ScoredTokens) and, optionally, token_metrics. On top of the base it adds DPPOLoss (from #5474), CISPOLoss (truncated IS) and IcePopLoss (masked IS), and an unverified recipe for each in torchtitan_recipes/tests/rl/. DAPOLoss/GRPOLoss keep the same op order and the same metric key order.

Example.

# A = 1; the weight each loss puts on grad(log p), as a function of r = p / q
r       = [0.4, 1.0, 1.3, 3.0, 6.0]
GRPO    = [0.4, 1.0, 0,   0,   0  ]   # -min(rA, clip(r)A), eps 0.2
CISPO   = [0.4, 1.0, 1.3, 2.0, 2.0]   # -A * sg(min(r, max_ratio=2)) * log p
IcePop  = [0,   1.0, 1.3, 3.0, 0  ]   # -A * sg(r * [0.5 <= r <= 5]) * log p
# Off the loss mask: ratio = 1 and generator_logprobs = trainer_logprobs.detach(),
# so DPPO's p - q is 0 there and a nan generator logprob never reaches a surrogate.

Must fix

  1. Description: the "Summary (human-written)" section is still empty. The author has to write it; agents leave it blank.

Resolved since the last review

  • importance_sampling.py, CISPOLoss.ratio_clip_high vs DPPOLoss.max_ratio: fixed. CISPO now uses max_ratio: float = 2.0 and checks >= 1 in __post_init__, matching DPPO. The gradient-weight test and the description use the new value.
  • torchtitan_recipes/tests/rl/alphabet_sort.py, where unverified recipes go: fixed. The module docstring now says unverified recipes live here until convergence runs move them to torchtitan_recipes.rl.
Details
  • PolicyGradientLoss.token_metrics documents that keys must end in _frac/_mean. That matches combine_microbatch_metrics (torchtitan/rl/controller/metrics.py:80): those keys are summed across microbatches, and other keys keep only the first microbatch's value. The new keys loss/trust_region_dropped_frac, loss/ratio_truncated_frac and loss/ratio_masked_frac follow the rule.
  • I re-checked PolicyGradientLoss.__call__ against the old DAPOLoss.__call__ (ratio_clipped_frac sits between ratio_mean and bit_wise/*). It is unchanged since the last review.
  • GRPOLoss.Config still inherits PolicyGradientLoss.Config, not DAPOLoss.Config. That is the right base: inheriting DAPOLoss.Config would add two clip fields that GRPO's __init__ ignores.
  • In-repo importers of the moved _normalize and MAX_LOG_RATIO are only test_losses.py and the loss modules. Nothing else imported losses.dapo._MAX_LOG_RATIO.

Not verified: the GB300 bitwise and compiled-region runs (they need a GPU). A maintainer still needs to review the three new losses.

@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch from 69d143b to 925e7f1 Compare November 25, 2026 08:27
@tianyu-l
tianyu-l removed this pull request from stack #6377 November 25, 2026 09:08
@tianyu-l
tianyu-l added this pull request to stack #6386 November 25, 2026 09:08
@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch 2 times, most recently from a5e6525 to 5df7b5d Compare November 25, 2026 20:14
@tianyu-l
tianyu-l removed this pull request from stack #6386 November 25, 2026 20:15
@tianyu-l
tianyu-l changed the base branch from main to cuspy-kernel-spans-exec-keying November 25, 2026 20:15
@tianyu-l
tianyu-l added this pull request to stack #6396 November 25, 2026 20:15
Base automatically changed from cuspy-kernel-spans-exec-keying to main November 25, 2026 21:38
@tianyu-l

Copy link
Copy Markdown
Contributor Author

numerics failure is on main as well, due to nightly update

@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: image

This PR moves the shared policy-loss steps from DAPOLoss into a PolicyGradientLoss base class with a token_loss slot, filled by DAPO and GRPO (weight 0 once r > 1.2) and three new losses: CISPO (capped at 2), IcePop (0 outside r 0.5 to 5) and DPPO (capped at 5, 0 once p − q > 0.2).

@tianyu-l
tianyu-l force-pushed the policy-gradient-loss branch from 6a23c61 to 4e49ec5 Compare November 26, 2026 04:08

@felipemello1 felipemello1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice! Just minor comments. I will also launch an agent to see how numerics + metrics compare vs other metrics. I will approve after that.

def rl_dppo_qwen3_0_6b_varlen(*, seq_len: int = 2048) -> Controller.Config:
"""``rl_grpo_qwen3_0_6b_varlen`` with ``DPPOLoss`` (6 GPUs: 4 gen + 2 train)."""
config = rl_grpo_qwen3_0_6b_varlen(seq_len=seq_len)
config.trainer.loss.loss_fn = DPPOLoss.Config(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i dont know if you do that for later PRs, but lets update the losses for all of the configs to what we believe is the most robust one? not sure if DPPO or IcePop? Maybe in a separate PR, so we can update the unit tests as well

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My personal opinion is that every loss should have its own file, i.e. cispo.py, icepop.py

I dont think its intuitive that we have dapo.py, dppo.py, grpo.py, but then importance_sampling.py

@felipemello1

Copy link
Copy Markdown
Contributor

Comment by claude:

Check Result
Loss and gradient vs verl / SkyRL / slime, configured alike (CPU, adversarial batch) gradients match to 1e-6; every gap is by design: their log-r clamp is ±20 or absent (fix 1), SkyRL's DPPO has no cap, SkyRL's score centering renormalizes over the top-k. No library combines PPO-clip or DPPO with score centering, so those have no reference
CP=2 (head-tail, Ulysses), TP=2, CP×TP, compiled loss, CUDA graphs (GPU, Qwen3.5-0.8B, stack top #6385) each rank's gradient = eager recompute to 3e-8; graph replay bitwise
Metrics vs 9 libraries fixes 2-4

Most of these predate the stack; they move into PolicyGradientLoss here.

1) Add an opt-in dual clip to DAPO/GRPO. For A < 0 the weight on grad(log p) is r, until the MAX_LOG_RATIO
clamp zeroes it:

log r       0     1.0    3.9    9.9       10.1
r           1     2.7    50     19,930    24,300
today       1     2.7    50     19,930    0
c = 3       1     2.7    0      0         0

So the more off-policy a bad token is, the more it dominates the gradient, until log r = 10.
Neither the GRPO nor the DAPO paper uses a dual clip. In libraries:

Dual clip Libraries
on by default (c = 3) verl
off by default SkyRL, NeMo-RL, molt, AReaL, slime, miles, ROLL
set to c = 10 in their DAPO recipes verl, SkyRL, NeMo-RL, molt

The diff matches verl's loss and gradient at c = 3 and c = 10.

--- a/torchtitan/rl/trainer/losses/dapo.py
+++ b/torchtitan/rl/trainer/losses/dapo.py
         ratio_clip_high: float = 0.2
         ...
+        ratio_clip_c: float | None = None
+        """Dual clip (https://arxiv.org/abs/1912.09729), e.g. 3: with ``A < 0``, the token loss is
+        capped at ``-ratio_clip_c * A``, so a token with ``r > ratio_clip_c`` gets no gradient.
+        None keeps that token's weight ``r``, up to ``exp(MAX_LOG_RATIO)``."""
+
+        def __post_init__(self) -> None:
+            if self.ratio_clip_c is not None and self.ratio_clip_c <= 1:
+                raise ValueError(
+                    f"DAPOLoss.ratio_clip_c must be > 1, got {self.ratio_clip_c}"
+                )

     def __init__(self, config: Config) -> None:
         super().__init__(config)
         self.ratio_clip_low = config.ratio_clip_low
         self.ratio_clip_high = config.ratio_clip_high
+        self.ratio_clip_c = config.ratio_clip_c

     def token_loss(self, tokens: ScoredTokens) -> torch.Tensor:
         ratio, advantages = tokens.ratio, tokens.advantages
         clipped_ratio = self._clip(ratio)
-        return -torch.min(ratio * advantages, clipped_ratio * advantages)
+        token_loss = -torch.min(ratio * advantages, clipped_ratio * advantages)
+        if self.ratio_clip_c is not None:
+            dual_clipped = torch.minimum(token_loss, -self.ratio_clip_c * advantages)
+            token_loss = torch.where(advantages < 0, dual_clipped, token_loss)
+        return token_loss

GRPOLoss.Config forwards the same field. log_token_weight (#6378) needs one line too; see there.

2) ratio_clipped_frac: count only tokens whose gradient the clip zeroes. Today it also counts tokens the clip
doesn't touch. Example: A > 0 with r = 0.5 is outside the band, but min(r·A, clip(r)·A) picks r·A, so its
gradient is unchanged. verl, SkyRL, slime, miles, AReaL, ROLL and molt count by the sign of A, which is what the
score-centering README (#6378) assumes.

--- a/torchtitan/rl/trainer/losses/dapo.py
+++ b/torchtitan/rl/trainer/losses/dapo.py
     def token_metrics(self, tokens: ScoredTokens) -> dict[str, torch.Tensor]:
-        ratio_clipped = torch.abs(tokens.ratio - self._clip(tokens.ratio)) > 1e-6
-        return {"loss/ratio_clipped_frac": ratio_clipped.float()}
+        # Tokens whose gradient the clip zeroes: r above the band with A > 0, below it with A < 0.
+        ratio, advantages = tokens.ratio, tokens.advantages
+        clipped = ((advantages > 0) & (ratio > 1 + self.ratio_clip_high)) | (
+            (advantages < 0) & (ratio < 1 - self.ratio_clip_low)
+        )
+        metrics = {"loss/ratio_clipped_frac": clipped.float()}
+        if self.ratio_clip_c is not None:
+            metrics["loss/ratio_dual_clipped_frac"] = (
+                (advantages < 0) & (ratio > self.ratio_clip_c)
+            ).float()
+        return metrics

3) Delete loss/ratio_mean. For tokens sampled from q, E_q[p/q] = sum_v p_v = 1 whatever the mismatch, so
the mean only tracks outliers. Example: one token at the clamp (r = e^10) in a 1,000-token batch adds 22 to it.
Fix 4 and logprob_diff/max cover what it was meant to show. All 9 libraries log some ratio mean, mostly raw;
I'd still drop ours, or average the capped weight as verl, SkyRL and NeMo-RL do.

--- a/torchtitan/rl/trainer/losses/policy_gradient.py
+++ b/torchtitan/rl/trainer/losses/policy_gradient.py
-            masked_ratio = ratio * effective_loss_mask
             metrics = {
                 "loss/mean": loss.detach(),
-                "loss/ratio_mean": _normalize(
-                    masked_ratio.sum(), global_loss_token_counts
-                ),

4) Add logprob_diff/abs_mean. The signed mean lets mismatches cancel: tokens at log r = +12 and -12 average
to 0. verl, SkyRL, slime, miles, AReaL, NeMo-RL and molt log the abs version. A k3 KL (7 of the 9 libraries log one) is not
proposed: per token it grows like r, so outliers dominate it, as they do ratio_mean.

--- a/torchtitan/rl/trainer/losses/policy_gradient.py
+++ b/torchtitan/rl/trainer/losses/policy_gradient.py
                 "bit_wise/logprob_diff/mean": _normalize(
                     diff_for_metrics.float().sum(), global_loss_token_counts
                 ),
+                "bit_wise/logprob_diff/abs_mean": _normalize(
+                    diff_for_metrics.abs().float().sum(), global_loss_token_counts
+                ),

5) Citation nits (the defaults are fine):

Item Note
DPPO max_ratio = 5 DPPO paper, App. E: "C=5 by default"
CISPO max_ratio = 2 the docstring's source (truncated-IS cap) is right. Context: the CISPO paper gives no cap; ScaleRL found 4, 5 and 8 equal; SkyRL uses 5
IcePop band [0.5, 5] IcePop paper, Sec. 2.3.4 (App. C: [0.5, 2] destabilizes training)
#6385 body cites SkyRL#2244 that PR closed unmerged; SkyRL main renormalizes over the top-k

On the stack top, these diffs pass test_losses.py and test_score_centering.py.

@felipemello1

Copy link
Copy Markdown
Contributor

@claude please review my review

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 49s —— View job


Your file-split comment is right and can go in this PR; the dual clip and the metrics changes are sound but belong in follow-up PRs, since this PR promises bitwise-identical DAPO/GRPO metrics. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This covers @felipemello1's review: the two inline comments and the five proposals in the follow-up comment. I checked each against the code at 0a66076. It is not a re-review of the diff.

Summary. The file-split comment is right and is a mechanical change that can go in this PR. The analysis behind proposals 1-4 is right, but none of them belongs in this PR. The PR's numerics claim is that DAPOLoss/GRPOLoss stay bitwise equal to main, "every metric (same keys and order)" included. Proposals 2 and 3 break that claim, and proposal 1 adds a knob that nothing uses.

Inline comments

  1. importance_sampling.py: one file per loss. Correct. CISPOLoss and IcePopLoss share no code (_in_band is used only by IcePop). The "importance sampling" grouping also doesn't hold: DPPOLoss is truncated IS plus a mask too (dppo.py:72), yet it has its own file. The fix is mechanical: move each class into cispo.py and icepop.py, and update the one import at losses/__init__.py:10. Nothing else imports importance_sampling, and no README mentions it.
  2. tests/rl/alphabet_sort.py:89: switch every config to the most robust loss. Partly correct. A separate PR is the right place. It also needs evidence first. The description says 10 lockstep steps can't rank the losses. It also says some of #6378's 100-step runs stopped from entropy collapse, with and without score centering. Changing the loss of the verified GRPO recipes changes their numerics, including the RL loss-guard recipe rl_grpo_qwen3_0_6b_varlen_batch_invariant and its goldens. Pick the loss from convergence runs with target_offpolicy_steps > 0, where the losses actually differ, and not from this PR's runs.

Follow-up comment

  1. Dual clip. The math is right. For A < 0 and r > 1 + high, -min(rA, clip(r)A) = -rA, so the weight is r, unbounded until the MAX_LOG_RATIO clamp at policy_gradient.py:141 zeroes the gradient. The proposed torch.where(A < 0, minimum(loss, -c*A), loss) is correct too. But it adds a config field that no recipe sets (config.md: "Expose only options a verified recipe uses"), and this PR already adds three losses that bound the weight on these tokens. Leave it out here. Add it later together with a recipe that sets it (e.g. c = 10, as the comment says DAPO recipes elsewhere do).
  2. ratio_clipped_frac counted by the sign of A. Correct. dapo.py:50 counts A > 0, r < 1 - low, but there min picks rA and the gradient is unchanged. The proposed condition matches exactly the tokens whose gradient the clip zeroes. It changes the meaning of an existing metric on main, though, so put it in a separate metrics PR, not in this refactor.
  3. Delete loss/ratio_mean. Partly correct. Its value is set by outliers (one token at e^10 in 1,000 tokens adds 22, as the comment says). But that sensitivity is also what makes it useful as a mismatch alarm, and deleting a metric key breaks dashboards. Either way it's a maintainer call for the metrics PR, not this one.
  4. Add logprob_diff/abs_mean. Correct and cheap. Note that the signed mean isn't redundant with it: it is the k1 estimate of -KL(q || p) (comment at policy_gradient.py:175), so keep both. This also goes in the metrics PR.
  5. Citations. No change needed. Optionally, cite DPPO's App. E next to max_ratio = 5.0 at dppo.py:54, as CISPO and IcePop already do for theirs.

Nothing missed in the review rises to a must-fix.

Before merge: fill in the human-written summary.

Not verified: the comparisons with the 9 RL libraries, the gradient match with verl/SkyRL/slime to 1e-6, the CP/TP/CUDA-graph results, and the claim that #6378's README assumes the sign-based clip count.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants