Repository navigation
Conversation
|
@claude review |
643709e to
ddd0ade
Compare
There was a problem hiding this comment.
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
- PR description -- "Summary (human-written)" is empty. Fill it in.
- 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_l1andtopk_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 haveK = k + 1 = 33, so the hook runs 33 full-vocabcross_entropycalls per decode step. That now includes the CI loss-guard reciperl_grpo_qwen3_0_6b_varlen_batch_invariant. This PR's own claim (compute_topk_logprobsdocstring) is thatlog_softmax(...).gatheris bitwise equal to-cross_entropyper column. If so, the hook could make onelog_softmax(logits.float(), -1).gather(-1, token_ids)call. At minimum, update the comment. The per-step generator cost is unverified.
Questions
_VocabParallelTopKLogprobsand the gather path incompute_topk_logprobsadd a second fp32[T_chunk, V_local]saved tensor per chunk, on top ofcompute_logprobs's (the TODO inscore_centering.py). Have you measured peak memory withk = 32on 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 forA >= 0andA < 0, and the|log r| <= 10clamp matchestorch.clamp's inclusive gradient.-infgenerator top-k entries givelog w = -inf, so their coefficient is 0 and no NaN appears.alpha = rho * w(1/rho)uses-log_rhoas the tail log-ratio. Off-mask rows are masked beforeexp, so NaN placeholders don't leak into the result.- Row alignment:
RolloutTurncompletion tokens are exactlyCompletion.token_ids.TrainingSampleBuilderadds rows only for completion tokens (loss_mask = True). The batcher checks rows againstloss_mask[1:]for each sample and filters (not truncates) long samples.masked_scatter_on the label-alignedloss_maskplaces rowtatlabels[t]. Empty bins give[0, k]. - vLLM:
processed_logprobswithtop_p == 1enforced, so the generator's top-k issoftmax(logits / T), the same as the trainer's.max_logprobsis set only whenk > 0. Rows are checked against the sampled column. - Sharding:
loss_kwarg_shardingis used at everypreprocess_inputs(deepseek_v4 and qwen3_8_flash_next inherit it throughsuper(); flux dropsloss_kwargs).ChunkedLossWrappersplitsloss_inputsalong dim 0. The TP path givesI@TPoutput 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_dictis 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.
ddd0ade to
646e5b0
Compare
|
@claude review |
There was a problem hiding this comment.
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
- PR description. The "Summary (human-written)" section is still empty.
- 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.mdalso 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_l1andtopk_mass, with and without score centering, over several seeds.
Questions
- Still open from the last review: what is the peak-memory cost of
k = 32without TP on a 152k vocabulary? There,compute_topk_logprobssaves a second fp32[T_chunk, V]log_softmaxoutput per chunk for backward. A user deciding whether to turn this on needs that number, ideally inlosses/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 ofA, including the inclusive|log r| <= 10clamp.alphauses the tail log-ratio-log_rho. Off-mask rows are zeroed beforeexp, so NaN placeholders don't leak.- Row alignment. The batcher counts rows against the raw
loss_mask[1:], andto_input_dictscatters with that same rawloss_mask, nottarget_mask. Tokens with a non-finite generator logprob still get their row and are then masked byeffective_loss_mask, so later rows don't shift. PP microbatches are separateTrainingMicrobatches, each with its own rows. RDMA transport picks up the new fields throughdataclasses.fields. _VocabParallelTopKLogprobsbackward:-sum_j g_j * softmax_v + scatter_add(g)is the exact gradient ofx_id - lse. It needs no collective, because the output isI@TP.- With score centering off,
as_input_dictand the loss ops are unchanged, so numerics don't change. max_logprobsis set wheneverk > 0(vLLM's default cap is 20 < 32), andengine_kwargscan 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.
13b18aa to
6442d9b
Compare
|
@claude review again |
There was a problem hiding this comment.
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
- PR description. The "Summary (human-written)" section is still empty. Also, the "Example" table labels the
w = 1numbers asGRPOLoss. GRPO's ratio already cancels the drift on unclipped tokens; thescore_centering.pydocstring 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. - Convergence evidence (still open). The only end-to-end run is still the batch-invariant one, where
c = 0by construction. Given the point above, the mismatched-generator runs should also reportloss/ratio_clipped_frac(orratio_truncated_frac/ratio_masked_frac) next tocoefficient_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 = 32cost in peak memory without TP on a 152k vocabulary?compute_topk_logprobssaves 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.
| 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`: |
There was a problem hiding this comment.
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)."
6442d9b to
f0c9b67
Compare
| # 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() | ||
| ) |
There was a problem hiding this comment.
would this be too much to record? should we create another separate flag? can be a TODO for later
| 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 |
There was a problem hiding this comment.
these are not verified recipes, should we put under torchtitan_recipes/tests/rl/ instead?
|
@claude review again |
|
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 |
|
@claude review |
|
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 |
There was a problem hiding this comment.
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
- PR description (still open). The "Summary (human-written)" section is empty.
- 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_l1and theratio_*_fracmetrics. torchtitan/rl/examples/verifiers/rollouter.py:266-271-- the check is caught byexcept Exceptionin 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, solog_token_weight(-log_rho)is right. Folding the tail throughsum_v p_v s_v = 0givesalpha = rho * w(1/rho). -infgenerator top-k entries. For each loss'slog_token_weightthey give a 0 coefficient, not NaN.- Off-mask rows. They use
effective_loss_mask, so tokens with a non-finite generator logprob are masked beforeexp. - Batch-invariant no-op. The correction's forward value is exactly 0, and its gradient adds exact zeros to the logits' gradient.
- Row alignment.
TrainingSampleBuilderadds rows only for completion tokens. The batcher checks each sample againstloss_mask[1:], andmasked_scatter_uses the rawloss_mask. ChunkedLossWrapper. It is the only loss wrapper (components/loss.py:942), soController.Config.num_topk_logprobsfinds everyPolicyGradientLoss.- 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.
| # 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." | ||
| ) |
There was a problem hiding this comment.
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.
dd164c9 to
25adbd7
Compare
|
@claude review again |
There was a problem hiding this comment.
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 swallowedValueErroris deleted. A Verifiers run with score centering now hits the batcher's row check (batcher.py:2028-2035in the diff), which escapesadd_groupand ends the run.losses/README.mddocuments this.- Convergence evidence: the stale-rollout table (
target_offpolicy_steps=3, 100 steps, 3 seeds) shows the correction is live (coefficient_l1about 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
- 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 onscore_centering(dppo.py:2212-2216in 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_dictscatter policy_gradient.py- the four
log_token_weightimplementations 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).
25adbd7 to
adce5c1
Compare
adce5c1 to
f9a69ce
Compare
f9a69ce to
a5acfb7
Compare
a5acfb7 to
ed81764
Compare
… PolicyGradientLoss Co-authored-by: Felipe Mello <[email protected]>
ed81764 to
e68b0a4
Compare

Summary (human-written)
derivation / motivation: https://fburl.com/5voz0fo4
Why
The generator samples from
q, the trainer scores withp, and they always differ a little (kernels, MoE routing, quantization, stale weights in async runs). Withq != pthe policy gradient at every prefix gains a term with no reward information in it. WithAthe advantage,s_v = grad(log p_v),r = p / qandw(r)the weight the loss puts on a token's score:Where the weight is the ratio itself,
q_v * r_v = p_vandsum_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 pullsptowardqafter 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 zeroesVonly 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),
GRPOLosswithclip_eps = 0.2, gradient on the logits averaged over the sampled token:What changed
Loss (logic).
ScoreCentering(trainer/losses/score_centering.py): an optional component,PolicyGradientLoss.Config.score_centering: ScoreCentering.Config | None. It adds the gradient ofA * sum_H sg(c_v) * log p_vto each token's loss (written asc_v * (log p_v - sg(log p_v)), so its forward value is 0 andloss/meanstays 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 = runless the clip binds in the advantage's direction (and 0 beyond the|log r| <= 10clamp);CISPOLoss:min(r, cap);IcePopLoss:rinside its band.DPPOLossraises at config time: its trust region depends onp - 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) = pexactly inside a band).compute_topk_logprobs(components/loss.py): logprobs of[T, k]ids undersoftmax(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 takeslog_softmax(...).gather; the vLLM batch-invariant logprob hook now scores the sampled column withcompute_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).
klives inScoreCentering.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 andmax_num_seqs:Controller.Config.num_topk_logprobsreads the policy loss; training requests getSamplingConfig.num_topk_logprobs = k, validation requests 0; generators getmax_num_topk_logprobs = k(vLLM'smax_logprobs); the batcher getsk. A recipe that setsgenerator.sampling.num_topk_logprobsitself 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_dictscatters them to[T, k]on the device (masked_scatter_, no host sync) -> loss kwargs.loss_kwarg_shardingshards a[T, k]loss input like the labels onT(CP, SPMD types); every model'spreprocess_inputsuses 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:
SGLangEngineraises (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_varlenandrl_icepop_score_centering_qwen3_0_6b_varlen: the paper's TIS + SC and masked IS + SC: #6376'srl_cispo_qwen3_0_6b_varlenandrl_icepop_qwen3_0_6b_varlenwithscore_centering=ScoreCentering.Config(). Like those, they are intorchtitan_recipes/tests/rl/alphabet_sort.pyuntil 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
GRPOLoss.Config(..., score_centering=ScoreCentering.Config())(anyPolicyGradientLoss)GenerationEngine(...),Generator(...)max_num_topk_logprobsBatcher(...)num_topk_logprobsNumerics
rl_grpo_qwen3_0_6b_varlen_batch_invarianton 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:loss/meantrainer/grad_norm/meanscore_centering/coefficient_l1/meanscore_centering/{generator,trainer}_topk_mass/meanrl_cispo_score_centering_qwen3_0_6b_varlenandrl_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_l1per 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_fracstay 0, but they count only sampled tokens; the coefficients also cover the unsampled top-k tokens and the tail.Stale-rollout runs. Alphabet sort on Qwen3-0.6B:
rl_grpo_qwen3_0_6b_varlenwith 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=3makes rollouts stale: the mean policy age is about 2.9 steps, so the generator'sqis an older policy than the trainer'sp. 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.coefficient_l1Reading:
Testing
tests/rl/unit_tests/cpu/test_score_centering.py(new):log_token_weightequals the surrogate's gradient for DAPO/GRPO, across both clip bounds and the clamp (catches a surrogate edited without its weight).rho/alpha).test_loss.py: vocab-parallel top-k logprobs and gradients equal full-vocabulary ones with temperatures (TP=4 and DP2xTP2, strict SPMD typecheck).[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 inscore_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 inlosses/README.md.) Next: SGLang (#6379) and Verifiers (#6380) top-k logprobs. Co-authored with @felipemello1 (Co-authored-bytrailer): the transport, the vocab-parallel top-k function and several tests come from #5760.