Skip to content

[rl] Score centering: generator top-k logprobs and ScoreCentering for PolicyGradientLoss - #6378

Open
tianyu-l wants to merge 1 commit into
policy-gradient-lossfrom
score-centering
Open

tianyu-l wants to merge 1 commit into
policy-gradient-lossfrom
score-centering

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Summary (human-written)

derivation / motivation: https://fburl.com/5voz0fo4

Why

The generator samples from q, the trainer scores with p, and they always differ a little (kernels, MoE routing, quantization, stale weights in async runs). With q != p the policy gradient at every prefix gains a term with no reward information in it. With A the advantage, s_v = grad(log p_v), r = p / q and w(r) the weight the loss puts on a token's score:

E[A * w(r_y) * s_y | prefix] = V(prefix) * sum_v q_v w(r_v) s_v + signal

Where the weight is the ratio itself, q_v * r_v = p_v and sum_v p_v s_v = 0, so the IS ratio already cancels the mismatch there. The term comes from the tokens whose weight the loss clips (DAPO/GRPO), truncates (CISPO) or masks (IcePop), and those grow with the mismatch. It pulls p toward q after promising prefixes and pushes it away after bad ones, whether or not the token affects the reward; weight syncs copy the moved trainer back into the generator, so it compounds. GRPO's group-mean baseline zeroes V only at the first token. Score centering (arXiv 2609.20807; this takes over #5760) subtracts the term exactly at every position, from the generator's top-k logprobs. This is also why the paper pairs it with truncated or masked IS.

Example. One position, k = 2, constant advantage 1 (no signal, so the update should be 0), GRPOLoss with clip_eps = 0.2, gradient on the logits averaged over the sampled token:

trainer p      = [0.40, 0.30, 0.15, 0.10, 0.05]
generator q    = [0.50, 0.22, 0.14, 0.09, 0.05]   (the trainer sees only q's top-2 and its tail mass)
ratio r = p/q  = [0.80, 1.36, 1.07, 1.11, 1.00]   token 1 is clipped (r > 1.2, A > 0)
weight w       = [0.80, 0,    1.07, 1.11, 1.00]
GRPOLoss                      update = q w - (sum q w) p = [0.12, -0.21, 0.045, 0.03, 0.015]   (pure drift)
GRPOLoss + ScoreCentering     c = [0, -0.30]             = [0,     0,    0,     0,    0    ]
no token clipped (w = r)      q w = p                    -> 0 with or without score centering

What changed

Loss (logic).

  • ScoreCentering (trainer/losses/score_centering.py): an optional component, PolicyGradientLoss.Config.score_centering: ScoreCentering.Config | None. It adds the gradient of A * sum_H sg(c_v) * log p_v to each token's loss (written as c_v * (log p_v - sg(log p_v)), so its forward value is 0 and loss/mean stays comparable with runs without score centering), c_v = q_v w(p_v/q_v) - alpha p_v, alpha = rho w(1/rho), rho = generator over trainer tail mass. Docstring has the derivation and the example above.
  • PolicyGradientLoss.log_token_weight(log_ratio, advantages): each loss declares the weight its surrogate puts on a token's score, so score centering composes with any loss whose weight is a function of the ratio. DAPOLoss/GRPOLoss: w = r unless the clip binds in the advantage's direction (and 0 beyond the |log r| <= 10 clamp); CISPOLoss: min(r, cap); IcePopLoss: r inside its band. DPPOLoss raises at config time: its trust region depends on p - q, so tail tokens don't share one weight and the tail can't be folded into the top-k (TODO: a full-vocabulary tail term). The weights are computed in log space (q * (p/q) = p exactly inside a band).
  • compute_topk_logprobs (components/loss.py): logprobs of [T, k] ids under softmax(logits / T). Under TP it uses three all-reduces without gathering the vocab (_VocabParallelTopKLogprobs, from [rl] Score centering: generator top-k logprobs + ScoreCenteringLoss #5760). Batch-invariant mode gathers the vocab once and takes log_softmax(...).gather; the vLLM batch-invariant logprob hook now scores the sampled column with compute_logprobs (as before) and the top-k columns with this same function, so generator and trainer top-k logprobs match bitwise (verified end to end below) with one full-vocabulary pass instead of k + 1.

Configuration (logic). k lives in ScoreCentering.Config.num_topk_logprobs (default 32: k = 32 and 128 matched full-vocabulary centering in every setting of the paper). The controller derives everything else from it, as it does for the seed, the stop tokens and max_num_seqs: Controller.Config.num_topk_logprobs reads the policy loss; training requests get SamplingConfig.num_topk_logprobs = k, validation requests 0; generators get max_num_topk_logprobs = k (vLLM's max_logprobs); the batcher gets k. A recipe that sets generator.sampling.num_topk_logprobs itself raises.

Transport (mostly from #5760). vLLM logprobs=k -> FinishedRequest/Completion/RolloutTurn [n, k] int32 ids + fp32 logprobs (the engine checks vLLM's [sampled, top-1..top-k] row layout) -> TrainingSample, one row per loss token -> microbatch rows -> TrainingMicrobatch.to_input_dict scatters them to [T, k] on the device (masked_scatter_, no host sync) -> loss kwargs. loss_kwarg_sharding shards a [T, k] loss input like the labels on T (CP, SPMD types); every model's preprocess_inputs uses it (mechanical: Decoder, MTP, qwen3_5, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, HF backend).

Debugging. RolloutSampleRecorder(log_logprobs=True) also dumps each turn's top-k rows (2k numbers per token; TODO: a separate flag if those dumps get too large).

Not yet supported: SGLangEngine raises (next PR). Verifiers rollouts carry no top-k rows yet (PR after), so the batcher's row check ends such a run.

Recipes. rl_cispo_score_centering_qwen3_0_6b_varlen and rl_icepop_score_centering_qwen3_0_6b_varlen: the paper's TIS + SC and masked IS + SC: #6376's rl_cispo_qwen3_0_6b_varlen and rl_icepop_qwen3_0_6b_varlen with score_centering=ScoreCentering.Config(). Like those, they are in torchtitan_recipes/tests/rl/alphabet_sort.py until the convergence runs back them. rl_grpo_qwen3_0_6b_varlen_batch_invariant, the CI RL loss-guard recipe, enables score centering. In batch-invariant mode its coefficients are exactly 0, so the guard's golden must not change; any misaligned top-k row, temperature mismatch or generator/trainer logprob difference would change the loss.

User-facing changes

Before After
no score centering GRPOLoss.Config(..., score_centering=ScoreCentering.Config()) (any PolicyGradientLoss)
GenerationEngine(...), Generator(...) add max_num_topk_logprobs
Batcher(...) adds num_topk_logprobs

Numerics

  • Score centering off: no numerics change (the off path computes the same ops as before).
  • Score centering on, batch-invariant: bitwise equal to off. rl_grpo_qwen3_0_6b_varlen_batch_invariant on real Qwen3-0.6B, seed 42, deterministic, lockstep, 10 steps, trainer TP=2 + generator TP=2 (4x GB300; scripts/rl/loss_compare.py's config with TP 2), same commit with and without score centering:
Metric Steps Result
loss/mean 10 bitwise equal
trainer/grad_norm/mean 10 bitwise equal
score_centering/coefficient_l1/mean 10 exactly 0 every step
score_centering/{generator,trainer}_topk_mass/mean 10 equal, 0.9994-0.99999 (the correction runs; it adds 0)
  • Score centering on, default (not batch-invariant) recipes: rl_cispo_score_centering_qwen3_0_6b_varlen and rl_icepop_score_centering_qwen3_0_6b_varlen, 10 steps, same setup but compiled loss region and vLLM's own kernels. The correction is live but small: coefficient_l1 per token goes from 8e-4 at step 1 to 6e-4 at step 10 (CISPO) and from 3e-4 to 2e-4 (IcePop), with top-k mass 1.00. ratio_truncated_frac / ratio_masked_frac stay 0, but they count only sampled tokens; the coefficients also cover the unsampled top-k tokens and the tail.
  • Score centering on, with a real mismatch (all five losses, with the commits up to [rl] Score centering for DPPOLoss #6384):

Stale-rollout runs. Alphabet sort on Qwen3-0.6B: rl_grpo_qwen3_0_6b_varlen with the loss swapped, trainer TP 2 + vLLM TP 2 on 4x GB300, 100 steps, seeds 42/43/44, compiled loss region, not batch-invariant. target_offpolicy_steps=3 makes rollouts stale: the mean policy age is about 2.9 steps, so the generator's q is an older policy than the trainer's p. The table shows mean reward over each run's last 20 steps (it starts near 0.29). "Collapsed at N" means entropy collapse: about 95% of groups had zero reward variance, 10 batches in a row had nothing to train on, and the controller stopped the run at step N.

Loss Score centering Seed 42 Seed 43 Seed 44 Final entropy (3 seeds) Clipped / truncated / masked / dropped coefficient_l1
GRPO off 0.429 0.428 0.410 0.042, 0.027, 0.036 0.9-1.0% -
GRPO on 0.418 0.434 0.431 0.075, 0.054, 0.065 1.2-1.8% 4.4e-2 to 4.7e-2
CISPO off 0.307 collapsed at 35 0.413 0.059, 0.011, 0.038 0.1% -
CISPO on 0.433 collapsed at 32 0.401 0.051, 0.008, 0.063 0.1% 2.2e-3 to 3.1e-3
IcePop off 0.453 0.436 0.317 0.044, 0.031, 0.005 0.2-0.4% -
IcePop on collapsed at 70 0.457 0.417 0.009, 0.037, 0.033 0.3% 2.3e-3 to 4.8e-3
DPPO off 0.455 0.437 0.421 0.036, 0.044, 0.027 0.2% -
DPPO on 0.454 0.451 0.458 0.044, 0.047, 0.026 0.2-0.4% 2.4e-3 to 3.9e-3

Reading:

  • With stale rollouts the correction is live, unlike the batch-invariant runs where it is exactly 0. For GRPO it is about 4.5e-2 per token, 75x the lockstep value; for CISPO, IcePop and DPPO it is about 3e-3.
  • No configuration got worse with score centering. GRPO ends with higher entropy in all 3 seeds (0.054-0.075 vs 0.027-0.042) at similar reward. DPPO + score centering is slightly better and less spread (0.451-0.458 vs 0.421-0.455).
  • Entropy collapse at this learning rate happens with and without score centering (CISPO seed 43 both ways; IcePop seed 42 with, and seed 44 nearly, without).
  • 100 steps and 3 seeds on a toy task are not enough to claim a reward gain.

Testing

  • tests/rl/unit_tests/cpu/test_score_centering.py (new):
    • log_token_weight equals the surrogate's gradient for DAPO/GRPO, across both clip bounds and the clamp (catches a surrogate edited without its weight).
    • (Every case below runs for DAPO, GRPO, CISPO and IcePop.) Full-vocabulary head, constant advantage, large mismatch: the expected update is 0 to 1e-6 with score centering and clearly nonzero without (catches a wrong coefficient, sign or weight).
    • k < V with a proportional generator tail, tail ratio inside and outside the clip band: still exactly 0 (catches a wrong rho/alpha).
    • A generator equal to the trainer: loss and gradient bitwise equal with and without score centering (the batch-invariant no-op).
  • test_loss.py: vocab-parallel top-k logprobs and gradients equal full-vocabulary ones with temperatures (TP=4 and DP2xTP2, strict SPMD typecheck).
  • From [rl] Score centering: generator top-k logprobs + ScoreCenteringLoss #5760: CP sharding of [T, k] loss inputs, batcher row scatter and empty-bin [0, k] rows and row-count check, vLLM row parsing, rollout plumbing.
  • pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_loss.py tests/unit_tests/cpu/models/common/test_decoder_loss_kwargs.py: 830 passed, 7 skipped; 1 failure that also fails on the base branch on this host (test_lora_head_only_matches_cross_entropy, aarch64).

Known issues / follow-ups

Truncated sampling (top-p, top-k) stays unsupported with score centering, as without it; replaying the sampler's support would make centering exact there: #6387.
Stacked on #6376. Trainer cost, measured on one GB300 without TP for one loss chunk of 4,096 tokens and a 151,936-token vocabulary: with the compiled loss region the recipes use, score centering (k = 32) raises the loss's peak memory from 1.16 to 3.48 GiB and its forward + backward from 2.1 to 3.6 ms, because the separate top-k scoring saves one more fp32 [T, V_local] for backward (TODO in score_centering.py; eager: 9.27 GiB either way, 15 -> 24 ms). A follow-up scores the top-k from the label's logprob instead, which removes it. (Also in losses/README.md.) Next: SGLang (#6379) and Verifiers (#6380) top-k logprobs. Co-authored with @felipemello1 (Co-authored-by trailer): the transport, the vocab-parallel top-k function and several tests come from #5760.

@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

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging (fill in the human-written summary, post the mismatched-generator convergence runs): 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. The math, the clip-aware weights and the generator -> batcher -> loss row alignment check out. The two things still missing are the human-written summary and end-to-end evidence with a real mismatch. A maintainer still needs to review this, since it touches components/loss.py and every model's preprocess_inputs.

What this PR does. It asks vLLM for the top-k logprobs at every training token and ships them as one row per loss token. On the device they are scattered to [T, k], sharded along T like the labels. PolicyGradientLoss then adds A * sum_H sg(c_v) * (log p_v - sg(log p_v)), where c_v = q_v w(p_v/q_v) - alpha p_v. This removes, at every position, the expected-gradient term that pulls p toward q with no reward signal. Each loss declares its weight through log_token_weight. The controller reads k off the loss config and wires it to the generator, the requests and the batcher.

Example. I checked the description's example by hand. With p = [.40,.30,.15,.10,.05], q = [.50,.22,.14,.09,.05], k = 2 and A = 1:

rho = 0.28/0.30, c = [0.127, -0.060], sum c = 0.067
GRPOLoss        expected logit update = q - p                     = [ .10, -.08, -.01, -.01,  0  ]
+ScoreCentering q - p - (c_H - sum(c) * p)                         = [  0,    0,    0, -.003, .003]

With clipping, w depends on sign(A). The correction still cancels exactly, because c uses the same per-sign w (E[A+] c+ + E[A-] c-). The batch-invariant no-op also holds: if p == q bitwise, then log w = 0, log rho = 0 and alpha = 1, so c = q - p = 0 exactly.

Must fix

  1. PR description -- "Summary (human-written)" is empty. Fill it in.
  2. Convergence evidence -- the only end-to-end result is the batch-invariant run, where the correction is exactly 0 by construction. That shows the no-op case is safe, but not that the correction helps or is stable. CLAUDE.md asks for convergence on representative data for computation changes. Please post the mismatched-generator runs before merging: loss, reward, coefficient_l1 and topk_mass, with and without score centering, over several seeds.

Should consider

  • torchtitan/rl/generator/vllm/batch_invariance.py:46-60 (not in the diff). The comment "SamplingParams(logprobs=0) makes real requests K=1" is now wrong. With score centering on, real requests have K = k + 1 = 33, so the hook runs 33 full-vocab cross_entropy calls per decode step. That now includes the CI loss-guard recipe rl_grpo_qwen3_0_6b_varlen_batch_invariant. This PR's own claim (compute_topk_logprobs docstring) is that log_softmax(...).gather is bitwise equal to -cross_entropy per column. If so, the hook could make one log_softmax(logits.float(), -1).gather(-1, token_ids) call. At minimum, update the comment. The per-step generator cost is unverified.

Questions

  • _VocabParallelTopKLogprobs and the gather path in compute_topk_logprobs add a second fp32 [T_chunk, V_local] saved tensor per chunk, on top of compute_logprobs's (the TODO in score_centering.py). Have you measured peak memory with k = 32 on a 152k-vocab model without TP? Users turning this on would want that number in the README.
Details

Gate. The problem is real: q != p always holds (kernels, MoE routing, stale async weights). The technique comes from a paper (arXiv 2609.20807) and is opt-in. The design is two-sided by nature (generator top-k plus trainer correction). #5760 is closed and taken over here; this PR is stacked on #6376 (open). #5707 (lm_head only on loss tokens) gathers loss_inputs along dim 0, so [T, k] kwargs should compose with it.

Checked:

  • log_token_weight (DAPO/GRPO) against -min(rA, clip(r)A): it is the gradient branch for A >= 0 and A < 0, and the |log r| <= 10 clamp matches torch.clamp's inclusive gradient. -inf generator top-k entries give log w = -inf, so their coefficient is 0 and no NaN appears.
  • alpha = rho * w(1/rho) uses -log_rho as the tail log-ratio. Off-mask rows are masked before exp, so NaN placeholders don't leak into the result.
  • Row alignment: RolloutTurn completion tokens are exactly Completion.token_ids. TrainingSampleBuilder adds rows only for completion tokens (loss_mask = True). The batcher checks rows against loss_mask[1:] for each sample and filters (not truncates) long samples. masked_scatter_ on the label-aligned loss_mask places row t at labels[t]. Empty bins give [0, k].
  • vLLM: processed_logprobs with top_p == 1 enforced, so the generator's top-k is softmax(logits / T), the same as the trainer's. max_logprobs is set only when k > 0. Rows are checked against the sampled column.
  • Sharding: loss_kwarg_sharding is used at every preprocess_inputs (deepseek_v4 and qwen3_8_flash_next inherit it through super(); flux drops loss_kwargs). ChunkedLossWrapper splits loss_inputs along dim 0. The TP path gives I@TP output with a local-only backward. CP and PP pass the extra kwargs through like the other per-token kwargs.
  • With score centering off: as_input_dict is unchanged and the loss runs the same ops, so numerics don't change.

Not verified: GPU runs (the batch-invariant bitwise claim and the vLLM [sampled, top-1..top-k] layout come from the author's runs and the CPU test that mocks it), generator throughput with k = 32, and peak memory.

@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 3m 49s —— View job


Approve -- please address the items before merging (fill in the human-written summary; post the mismatched-generator convergence runs): 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. At 646e5b0 the code is correct. The amended commit fixes the batch-invariant hook I raised last time. Two of the earlier must-fix items are still open: the human-written summary and evidence that score centering helps when the generator really differs from the trainer. A maintainer still needs to review this, because it touches components/loss.py and the preprocess_inputs of every model.

What this PR does. vLLM now returns its top-k logprobs for every training token. They travel as one row per loss token and are scattered to [T, k] on the device, sharded along T the same way as the labels. PolicyGradientLoss then adds A * sum_H sg(c_v) * (log p_v - sg(log p_v)), with c_v = q_v w(p_v/q_v) - alpha p_v. This cancels, at every position, the part of the expected gradient that pulls p toward q without any reward signal. Each loss supplies its weight w through log_token_weight. The controller reads k from the loss config.

Example. The trainer has p = [.40,.30,.15,.10,.05] and the generator has q = [.50,.22,.14,.09,.05], with k = 2 and A = 1. Then rho = 0.28/0.30 and c = [0.127, -0.060]:

GRPOLoss           expected logit update = q - p = [ .10, -.08, -.01, -.01,  0  ]
+ ScoreCentering   expected logit update         = [  0,    0,    0, -.003, .003]
p == q bitwise     log w = 0, log rho = 0, alpha = 1  ->  c = 0 exactly (the batch-invariant golden stays unchanged)

Must fix

  1. PR description. The "Summary (human-written)" section is still empty.
  2. Convergence evidence. The only end-to-end run is still the batch-invariant one, where the correction is exactly 0 by construction. The new losses/README.md also says the paper validates score centering with REINFORCE and truncated/masked IS, not with PPO clipping. So the DAPO/GRPO combination this PR ships has no published or posted evidence. Before merging, post the mismatched-generator runs: loss, reward, coefficient_l1 and topk_mass, with and without score centering, over several seeds.

Questions

  • Still open from the last review: what is the peak-memory cost of k = 32 without TP on a 152k vocabulary? There, compute_topk_logprobs saves a second fp32 [T_chunk, V] log_softmax output per chunk for backward. A user deciding whether to turn this on needs that number, ideally in losses/README.md.
Details

Since the previous review (ddd0ade, force-pushed): batch_invariance.py now scores the sampled column with compute_logprobs and the top-k columns with one compute_topk_logprobs call. That is one full-vocabulary pass instead of k + 1 cross_entropy calls, and the stale "logprobs=0 makes K=1" comment is gone. Both sides call the same pair of functions: compute_logprobs for the sampled token and log_softmax(...).gather for the top-k. So the bitwise claim rests on the same ops on both sides, not on cross_entropy and log_softmax agreeing with each other.

Re-checked at HEAD:

  • log_token_weight (DAPO/GRPO) is the gradient branch of -min(rA, clip(r)A) for each sign of A, including the inclusive |log r| <= 10 clamp. alpha uses the tail log-ratio -log_rho. Off-mask rows are zeroed before exp, so NaN placeholders don't leak.
  • Row alignment. The batcher counts rows against the raw loss_mask[1:], and to_input_dict scatters with that same raw loss_mask, not target_mask. Tokens with a non-finite generator logprob still get their row and are then masked by effective_loss_mask, so later rows don't shift. PP microbatches are separate TrainingMicrobatches, each with its own rows. RDMA transport picks up the new fields through dataclasses.fields.
  • _VocabParallelTopKLogprobs backward: -sum_j g_j * softmax_v + scatter_add(g) is the exact gradient of x_id - lse. It needs no collective, because the output is I@TP.
  • With score centering off, as_input_dict and the loss ops are unchanged, so numerics don't change.
  • max_logprobs is set whenever k > 0 (vLLM's default cap is 20 < 32), and engine_kwargs can no longer override it.

Not verified: the vLLM [sampled, top-1..top-k] flat layout when the sampled token is also in the top-k (the row check would raise rather than misalign), the batch-invariant bitwise run, generator throughput and peak memory with k = 32. All of these need GPUs.

@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 2m 12s —— View job


Approve -- please address the items before merging (fill in the human-written summary; relabel the description's "GRPOLoss" example, which shows w = 1 numbers; post the mismatched-generator runs with clipped fractions): 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. At 6442d9b the code still checks out. Two must-fix items from the last review are still open, and I found that the PR's motivating example mislabels which loss it describes. A maintainer still needs to review this, because it touches components/loss.py and the preprocess_inputs of every model.

What this PR does. vLLM now returns its top-k logprobs for every training token. They travel as [T, k] loss inputs, sharded along T like the labels. PolicyGradientLoss then adds A * sum_H sg(c_v) * (log p_v - sg(log p_v)) with c_v = q_v w(p_v/q_v) - alpha p_v. This removes the part of the expected gradient that carries no reward signal and comes from the weights the loss puts on tokens.

Example. This is the description's case (k = 2, A = 1) run through GRPOLoss (clip_eps = 0.2) instead of w = 1. The ratios are r = p/q = [0.80, 1.36, 1.07, 1.11, 1.00]. Token 1 is clipped (r > 1.2, A > 0), so w = [0.8, 0, 1.07, 1.11, 1.0] and q*w = [.40, 0, .15, .10, .05]:

w = 1 (REINFORCE)          expected logit update = q - p                 = [ .10, -.08, -.01,  -.01, 0   ]
GRPOLoss                   sum q w e_v - (sum q w) p                     = [ .12, -.21, .045,  .03, .015]
GRPOLoss + ScoreCentering  c = [0, -0.30], alpha = 1                     = [  0,    0,   0,    0,   0  ]
GRPOLoss, no token clipped q w = p  ->  update = p - p = 0 with or without score centering

The correction is right. But the drift in a ratio-weighted loss comes entirely from clipped, truncated or masked tokens, not from q != p as such.

Must fix

  1. PR description. The "Summary (human-written)" section is still empty. Also, the "Example" table labels the w = 1 numbers as GRPOLoss. GRPO's ratio already cancels the drift on unclipped tokens; the score_centering.py docstring correctly says "w = 1". Relabel the row as REINFORCE (w = 1), or use the GRPO rows above. Then say in "Why" that for DAPO/GRPO/CISPO/IcePop the correction acts only where the weight is clipped, capped or masked.
  2. Convergence evidence (still open). The only end-to-end run is still the batch-invariant one, where c = 0 by construction. Given the point above, the mismatched-generator runs should also report loss/ratio_clipped_frac (or ratio_truncated_frac/ratio_masked_frac) next to coefficient_l1, with and without score centering, over several seeds. That shows how much of the mismatch actually reaches the correction.

Should consider

  • torchtitan/rl/trainer/losses/README.md:22 -- the same overstatement as in the description (inline comment).

Questions

  • Still open: what does k = 32 cost in peak memory without TP on a 152k vocabulary? compute_topk_logprobs saves a second fp32 [T_chunk, V] per chunk for backward.
Details

Since the last review. The branch was force-pushed from 646e5b0 to 6442d9b. 646e5b0 isn't in this shallow checkout, so I couldn't diff the two commits; I re-read the full diff against policy-gradient-loss instead. The previous fix is still in place: the batch-invariant hook scores the sampled column with compute_logprobs and the top-k columns with a single compute_topk_logprobs call, and max_logprobs is reserved against engine_kwargs overrides.

Why the GRPO drift is clip-only. PolicyGradientLoss uses r = p / q_generator (policy_gradient.py:164-169). For w = r, q_v w_v = p_v and sum_v p_v grad(log p_v) = 0. The drift term is therefore V * sum_{v clipped} (q_v w_v - p_v) s_v, which is non-zero only on tokens where log_token_weight returns -inf or a capped value. That also explains why the paper pairs score centering with truncated or masked IS. It is the reason to report clipped fractions with the convergence runs, and it is not a defect in the code.

Re-checked at HEAD: the log_token_weight branches against each surrogate's gradient, including the inclusive |log r| <= 10 clamp. alpha uses the tail ratio -log_rho. NaN/zero placeholders off the mask are masked before exp. Rows are counted against loss_mask[1:] and scattered with the raw label-aligned loss_mask. _VocabParallelTopKLogprobs backward is the exact gradient of x_id - lse with no collective. With score centering off, as_input_dict and the loss ops are unchanged.

Not verified: the GPU runs (the batch-invariant bitwise run, the vLLM [sampled, top-1..top-k] layout), and generator throughput and peak memory with k = 32.

Comment thread torchtitan/rl/trainer/losses/README.md Outdated
Comment on lines +22 to +27
The trainer's `p` and the generator's `q` always differ a little (kernels, quantization, MoE
routing, stale weights). Then the expected gradient at every prefix gains a term that holds
no reward information: it distills the trainer toward the generator, scaled by how promising
the prefix is, and weight syncs copy the moved trainer back into the generator, so it
compounds. Score centering ([arXiv 2609.20807](https://arxiv.org/abs/2609.20807)) subtracts
that term at every position. It composes with any `PolicyGradientLoss`:

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 overstates the drift for every loss in the table. All four supported losses weight by the ratio r = p/q (log_token_weight returns log_ratio inside the band). Where no clip, cap or mask binds, the drift term is V * sum_v q_v (p_v/q_v) s_v = V * sum_v p_v s_v = 0, so the IS ratio already cancels the mismatch there. ScoreCentering's own metric comment says the same: coefficient_l1 is 0 "when no weight caps or masks a ratio". The drift comes only from tokens whose weight is clipped (DAPO/GRPO), truncated (CISPO) or masked (IcePop), and that is all score centering corrects. A user deciding whether to pay for the k = 32 transport and the extra [T, V_local] saved tensor needs this sentence. A suggested wording: "With an importance-weighted loss (w = r) the term is 0 wherever the ratio is not clipped, truncated or masked; it comes from those tokens, which grow with the mismatch (loss/ratio_clipped_frac and friends)."

Comment on lines +217 to +225
# Null at k=0, so every dump keeps one schema.
topk_token_ids = turn.completion_topk_token_ids
topk_logprobs = turn.completion_topk_logprobs
encoded["completion_topk_token_ids"] = (
None if topk_token_ids is None else topk_token_ids.tolist()
)
encoded["completion_topk_logprobs"] = (
None if topk_logprobs is None else topk_logprobs.tolist()
)

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.

would this be too much to record? should we create another separate flag? can be a TODO for later

Comment thread torchtitan_recipes/rl/alphabet_sort.py Outdated
Comment on lines +235 to +256
def rl_cispo_score_centering_qwen3_0_6b_varlen(
*, seq_len: int = 2048
) -> Controller.Config:
"""``rl_cispo_qwen3_0_6b_varlen`` with score centering: arXiv 2609.20807's TIS + SC
(6 GPUs: 4 gen + 2 train)."""
config = rl_cispo_qwen3_0_6b_varlen(seq_len=seq_len)
config.trainer.loss.loss_fn = dataclasses.replace(
config.trainer.loss.loss_fn, score_centering=ScoreCentering.Config()
)
return config


def rl_icepop_score_centering_qwen3_0_6b_varlen(
*, seq_len: int = 2048
) -> Controller.Config:
"""``rl_icepop_qwen3_0_6b_varlen`` with score centering: arXiv 2609.20807's masked IS + SC
(6 GPUs: 4 gen + 2 train)."""
config = rl_icepop_qwen3_0_6b_varlen(seq_len=seq_len)
config.trainer.loss.loss_fn = dataclasses.replace(
config.trainer.loss.loss_fn, score_centering=ScoreCentering.Config()
)
return 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.

these are not verified recipes, should we put under torchtitan_recipes/tests/rl/ instead?

@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 8s —— View job


Approve -- please address the items before merging (fill in the human-written summary; address @tianyu-l's two comments by moving the score-centering recipes to torchtitan_recipes/tests/rl/ and adding the recorder TODO; post the mismatched-generator runs): review

@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 3m 24s —— View job


Approve -- please address the items before merging (still open: the human-written summary and the mismatched-generator runs; new: the Verifiers top-k guard is swallowed by the controller's rollout loop, so delete it and let the batcher's row check end the run): 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. At dd164c9 the loss math, the weights for each loss and the row alignment from generator to loss all still check out. Two earlier items are still open. One new item: the Verifiers guard is swallowed by the controller's rollout loop, so it doesn't stop the run. A maintainer still needs to review this, because it touches components/loss.py and the preprocess_inputs of every model.

What this PR does. vLLM returns its top-k logprobs for each training token, and the loss receives them as [T, k] inputs sharded like the labels. PolicyGradientLoss then adds A * sum_H sg(c_v) * (log p_v - sg(log p_v)), with c_v = q_v w(p_v/q_v) - alpha p_v. This cancels the drift that carries no reward signal and comes from tokens the loss clips, truncates or masks.

Example. This is the description's GRPOLoss case (clip_eps = 0.2, k = 2, A = 1). I re-derived it at HEAD:

r = p/q = [0.80, 1.36, 1.07, 1.11, 1.00]   token 1 clipped -> w = [0.8, 0, 1.07, 1.11, 1.0]
GRPOLoss                  q*w - 0.70 p     = [.12, -.21, .045, .03, .015]
+ ScoreCentering          rho = .28/.30, alpha = rho * w(1/rho) = 1, c = [0, -.30]  -> 0

Must fix

  1. PR description (still open). The "Summary (human-written)" section is empty.
  2. Convergence evidence (still open). The description says the runs are still in progress. Before merging, post the runs with a deliberately mismatched generator, with and without score centering, over several seeds: loss, reward, coefficient_l1 and the ratio_*_frac metrics.
  3. torchtitan/rl/examples/verifiers/rollouter.py:266-271 -- the check is caught by except Exception in the controller's rollout loop, so every group gets dropped and the run never stops. Deleting the check lets the batcher's row check end the run (inline comment).
Details

Force-pushed since the last review (4339a4d). That commit isn't in this shallow checkout, so I re-read the full diff against policy-gradient-loss.

Re-checked:

  • Tail fold. Tail tokens have ratio 1/rho, so log_token_weight(-log_rho) is right. Folding the tail through sum_v p_v s_v = 0 gives alpha = rho * w(1/rho).
  • -inf generator top-k entries. For each loss's log_token_weight they give a 0 coefficient, not NaN.
  • Off-mask rows. They use effective_loss_mask, so tokens with a non-finite generator logprob are masked before exp.
  • Batch-invariant no-op. The correction's forward value is exactly 0, and its gradient adds exact zeros to the logits' gradient.
  • Row alignment. TrainingSampleBuilder adds rows only for completion tokens. The batcher checks each sample against loss_mask[1:], and masked_scatter_ uses the raw loss_mask.
  • ChunkedLossWrapper. It is the only loss wrapper (components/loss.py:942), so Controller.Config.num_topk_logprobs finds every PolicyGradientLoss.
  • No golden changes. No golden files change, which is consistent with the no-op claim.

SGLangEngine. It raises in engine __init__ during generator setup, so that guard does stop the run.

Not verified: the GPU runs (batch-invariant bitwise equality, vLLM's [sampled, top-1..top-k] layout), and my reading that the Verifiers case loops forever rather than eventually exiting.

Comment on lines +266 to +271
# TODO: carry the generator's top-k logprobs through Verifiers' traces.
if sampling.num_topk_logprobs > 0:
raise ValueError(
"Verifiers rollouts do not carry the generator's top-k logprobs yet: "
"score centering (ScoreCentering.Config) needs another rollouter."
)

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 ValueError never stops the run. run_group runs inside the rollout-worker actor, and the controller's rollout loop (controller.py:1322-1347) wraps run_group_rollouts in except Exception:. That handler logs "rollout group N failed; dropping" and finalizes an empty group with rollout/group_failures += 1. With score centering on, every training group fails this way, so the trainer never gets a batch. As far as I can tell from the code, the run then keeps admitting groups and dropping them instead of exiting. I haven't run this.

Without this check, the run would actually stop. The turns built at line 556 carry no top-k, so the batcher's row check raises ... has 0 top-k rows for N loss tokens, and per its own TODO that error escapes add_group and ends the run.

The smallest fix is to delete these 6 lines and rely on the batcher check, perhaps adding "(Verifiers rollouts don't carry them yet)" to its message. The alternative is to raise somewhere the controller doesn't swallow, e.g. at setup, but that would mean telling the rollouter about the loss. That isn't worth it while #6380 is next.

@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


Approve -- please address the item before merging (still open: the human-written summary; the Verifiers guard and the convergence evidence are resolved): 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 item below before merging. The Verifiers guard is gone and the stale-rollout runs are posted. The only must-fix left is the human-written summary. A maintainer still needs to review this, because it touches components/loss.py and the preprocess_inputs of every model.

What this PR does. vLLM returns its top-k logprobs for each training token, and the loss receives them as [T, k] inputs sharded like the labels. PolicyGradientLoss then adds A * sum_H sg(c_v) * (log p_v - sg(log p_v)), with c_v = q_v w(p_v/q_v) - alpha p_v. This cancels the reward-free drift that comes from tokens the loss clips, truncates or masks.

Example. The description's GRPOLoss case (clip_eps = 0.2, k = 2, A = 1), unchanged:

r = p/q = [0.80, 1.36, 1.07, 1.11, 1.00]   token 1 clipped -> w = [0.8, 0, 1.07, 1.11, 1.0]
GRPOLoss                  q*w - 0.70 p     = [.12, -.21, .045, .03, .015]
+ ScoreCentering          c = [0, -.30]    -> 0

Resolved since the last review

  • verifiers/rollouter.py: the swallowed ValueError is deleted. A Verifiers run with score centering now hits the batcher's row check (batcher.py:2028-2035 in the diff), which escapes add_group and ends the run. losses/README.md documents this.
  • Convergence evidence: the stale-rollout table (target_offpolicy_steps=3, 100 steps, 3 seeds) shows the correction is live (coefficient_l1 about 4.5e-2 for GRPO, about 3e-3 otherwise), next to the clipped/truncated/masked fractions. That is enough to merge an opt-in feature, and the description doesn't claim a reward gain.

Must fix

  1. PR description (still open). The "Summary (human-written)" section is empty.

Should consider

  • Description, stale-rollout table. Three small accuracy fixes:
    • It says "all five losses", but it lists four (no DAPO).
    • The DPPO "on" rows can't run at this PR's HEAD, because DPPOLoss.Config.__post_init__ raises on score_centering (dppo.py:2212-2216 in the diff). They come from #6384. Mark those rows "(needs #6384)" so a reader doesn't try to reproduce them here.
    • "No configuration got worse with score centering" is too strong. IcePop seed 42 collapses at step 70 with score centering and reaches 0.453 without it. "No consistent regression across seeds" matches the table.
Details

dd164c9 was force-pushed to 25adbd7. The old commit isn't in this shallow checkout, so I re-read gh pr diff for:

  • the batcher row check and the to_input_dict scatter
  • policy_gradient.py
  • the four log_token_weight implementations and the DPPO ban
  • losses/README.md

torchtitan/rl/examples/ no longer references top-k at all. I read #6384's description to see where the DPPO rows come from: it removes the ban and bounds the tail weight with p_max. I found no new problems in the code.

Not verified: the GPU runs (batch-invariant bitwise equality, vLLM's [sampled, top-1..top-k] layout, the stale-rollout table).

@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: image

With GRPO clipping one token's weight, a 5-token example gets an update of +0.12 to −0.21 with no reward behind it, and score centering, using the generator's top-2 logprobs (k = 32 by default), adds coefficients 0 and −0.30 that bring every update to 0.

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