Repository navigation
Conversation
|
@claude review |
There was a problem hiding this comment.
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
- Description: the "Summary (human-written)" section is empty.
- Overlap with #5474. #5474 targets the same duplication with
losses/common.py(score_tokens+policy_metrics) and addsDPPOLossas 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_0and 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. - A base class with one subclass (
.claude/rules/design.md: "Don't add ... a base class with a single subclass").PolicyGradientLosshas onetoken_lossimplementation, DAPO's; GRPO reuses it. Score centering, the next PR, doesn't need the base: it could go onDAPOLoss, and GRPO would inherit it. The first PR that actually needs the base is the truncated/masked IS loss. Either landPolicyGradientLossin that PR, or reorder the stack so the second subclass arrives with the base.
Should consider
torchtitan/rl/trainer/losses/grpo.py:29-32-- skipsDAPOLoss.__init__(inline comment).
Details
- Checked the moved code: the op order in
PolicyGradientLoss.__call__matches the oldDAPOLoss.__call__, and the metric keys are in the same order (ratio_clipped_fracis spliced in where it was). The only extra work is a secondtorch.clampover[T]insidetoken_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.Configwith the same field names. Nothing passed the**kwargsthat the oldGRPOLoss.__init__accepted, so removing it is safe. test_policy_loss_configs.py:61still holds: itsisinstance(..., (DAPOLoss.Config, GRPOLoss.Config))check is unaffected by the change to the configs' base class.test_losses.pyimports the private_normalizefrom another module. That predates this PR (it used to come fromdapo.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).
|
@claude review again |
There was a problem hiding this comment.
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
- Empty "Summary (human-written)" -- still open. The author has to write it; agents leave it blank.
- 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.
- 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,
PolicyGradientLossis 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-- skipsDAPOLoss.__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).
8a47832 to
cb29656
Compare
|
@claude review again |
There was a problem hiding this comment.
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 propertiesConfigurable.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
- Empty "Summary (human-written)" -- still open. The author has to write it.
- 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.
- 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,
PolicyGradientLossis left with one surrogate.
Resolved
grpo.pyskippingDAPOLoss.__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.
3b6a42e to
11e37ff
Compare
|
@claude review again |
There was a problem hiding this comment.
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
- Empty "Summary (human-written)" -- still open. The author has to write it.
- 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.
- 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,
PolicyGradientLossends up with a single surrogate.
No new problems in 11e37ff.
Details
GRPOLoss.__init__forwards**kwargstoDAPOLoss.__init__, which doesn't accept any. That is the same onmain, 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_fracsits betweenloss/ratio_meanandbit_wise/logprob_diff/mean) against the oldDAPOLoss.__call__. Both are unchanged. - I checked the
PolicyGradientLossdocstring example (ratio=1.65,clip_high=0.2, so-min(1.65, 1.2) = -1.2), and it is consistent withDAPOLoss.token_loss.
Not verified: the GB300 bitwise loss/grad_norm runs and the compiled-region parity check (both need a GPU).
11e37ff to
57f7d0a
Compare
57f7d0a to
2fe38f1
Compare
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class Config(Loss.Config): | ||
| class Config(PolicyGradientLoss.Config): |
There was a problem hiding this comment.
should inherit DAPOLoss.Config?
|
@claude review again |
8938bbf to
69d143b
Compare
|
@claude review |
|
Claude finished @tianyu-l's task in 1m 2s —— View job Approve, with one item to address before merging: |
There was a problem hiding this comment.
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
- 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_highvsDPPOLoss.max_ratio: fixed. CISPO now usesmax_ratio: float = 2.0and checks>= 1in__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 totorchtitan_recipes.rl.
Details
PolicyGradientLoss.token_metricsdocuments that keys must end in_frac/_mean. That matchescombine_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 keysloss/trust_region_dropped_frac,loss/ratio_truncated_fracandloss/ratio_masked_fracfollow the rule.- I re-checked
PolicyGradientLoss.__call__against the oldDAPOLoss.__call__(ratio_clipped_fracsits betweenratio_meanandbit_wise/*). It is unchanged since the last review. GRPOLoss.Configstill inheritsPolicyGradientLoss.Config, notDAPOLoss.Config. That is the right base: inheritingDAPOLoss.Configwould add two clip fields that GRPO's__init__ignores.- In-repo importers of the moved
_normalizeandMAX_LOG_RATIOare onlytest_losses.pyand the loss modules. Nothing else importedlosses.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.
69d143b to
925e7f1
Compare
a5e6525 to
5df7b5d
Compare
|
numerics failure is on main as well, due to nightly update |
5df7b5d to
6a23c61
Compare
6a23c61 to
4e49ec5
Compare
…PPO losses Co-authored-by: Felipe Mello <[email protected]>
4e49ec5 to
0a66076
Compare
felipemello1
left a comment
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
|
Comment by claude:
Most of these predate the stack; they move into 1) Add an opt-in dual clip to DAPO/GRPO. For A < 0 the weight on grad(log p) is r, until the So the more off-policy a bad token is, the more it dominates the gradient, until log r = 10.
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
2) --- 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 metrics3) Delete --- 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 --- 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):
On the stack top, these diffs pass |
|
@claude please review my review |
|
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 |
There was a problem hiding this comment.
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
importance_sampling.py: one file per loss. Correct.CISPOLossandIcePopLossshare no code (_in_bandis used only by IcePop). The "importance sampling" grouping also doesn't hold:DPPOLossis truncated IS plus a mask too (dppo.py:72), yet it has its own file. The fix is mechanical: move each class intocispo.pyandicepop.py, and update the one import atlosses/__init__.py:10. Nothing else importsimportance_sampling, and no README mentions it.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 reciperl_grpo_qwen3_0_6b_varlen_batch_invariantand its goldens. Pick the loss from convergence runs withtarget_offpolicy_steps > 0, where the losses actually differ, and not from this PR's runs.
Follow-up comment
- Dual clip. The math is right. For
A < 0andr > 1 + high,-min(rA, clip(r)A) = -rA, so the weight isr, unbounded until theMAX_LOG_RATIOclamp atpolicy_gradient.py:141zeroes the gradient. The proposedtorch.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). ratio_clipped_fraccounted by the sign of A. Correct.dapo.py:50countsA > 0, r < 1 - low, but thereminpicksrAand the gradient is unchanged. The proposed condition matches exactly the tokens whose gradient the clip zeroes. It changes the meaning of an existing metric onmain, though, so put it in a separate metrics PR, not in this refactor.- Delete
loss/ratio_mean. Partly correct. Its value is set by outliers (one token ate^10in 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. - 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 atpolicy_gradient.py:175), so keep both. This also goes in the metrics PR. - Citations. No change needed. Optionally, cite DPPO's App. E next to
max_ratio = 5.0atdppo.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.

Summary (human-written)
Why
torchtitan's RL trainer has one policy surrogate, the PPO clip (
DAPOLoss, andGRPOLossas 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), atA = 1, as a function ofr = p / q:What changed
losses/policy_gradient.py:PolicyGradientLosswith 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), abstracttoken_loss(tokens), optionaltoken_metrics(tokens)._normalizemoves here unchanged;_MAX_LOG_RATIOmoves here as the publicMAX_LOG_RATIO(same value, 10.0), since the tests and the next PR import it.DAPOLosskeeps its config and ops (its__call__body is moved, not rewritten).GRPOLossis unchanged except that itsConfigsubclassesPolicyGradientLoss.Config, which providesglobal_vocab_size.losses/importance_sampling.py:CISPOLoss(weightmin(r, max_ratio),max_ratio2 as in verl and arXiv 2609.20807, the same name and meaning asDPPOLoss.max_ratio) andIcePopLoss(weightrin[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:DPPOLossfrom [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 rejectsdivergence_threshold <= 0andmax_ratio < 1, like CISPO's and IcePop's.rl_dppo_qwen3_0_6b_varlen,rl_cispo_qwen3_0_6b_varlenandrl_icepop_qwen3_0_6b_varlen:rl_grpo_qwen3_0_6b_varlenwith each loss. They live intorchtitan_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_lossand before normalization, so no loss can skip it or normalize it differently. #5474 is closed in favor of this PR; itsDPPOLossis here.Numerics
DAPOLoss/GRPOLossunchanged. Bitwise identical loss and grad_norm vs. main, deterministic + batch-invariantrl_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):loss/meantrainer/grad_norm/meanNew losses, end to end with the compiled
"loss"region (the recipes' default local-compile regions): each new recipe andrl_grpo_qwen3_0_6b_varlenfor 10 steps on real Qwen3-0.6B, seed 42, deterministic, lockstep, trainer TP=2 + generator TP=2 (4x GB300), not batch-invariant:rl_grpo_qwen3_0_6b_varlenrl_dppo_qwen3_0_6b_varlenrl_cispo_qwen3_0_6b_varlenrl_icepop_qwen3_0_6b_varlenAll 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'sloss/meanis 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. newDAPOLossandGRPOLosson 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 * wwith 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).test_policy_loss_configs.pybuilds 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 forDPPOLoss(#6384), and scoring the top-k from the label's logprob (#6385).