Skip to content

[rl] Score centering: score the top-k from the label's logprob - #6385

Open
tianyu-l wants to merge 1 commit into
dppo-score-centeringfrom
fused-topk-logprobs
Open

tianyu-l wants to merge 1 commit into
dppo-score-centeringfrom
fused-topk-logprobs

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

Score centering (#6378) scores the generator's top-k ids with a second log-softmax over the vocabulary, separate from the label's. With the compiled loss region the recipes use, that second pass keeps one more fp32 [T, V_local] for backward: for one 4,096-token loss chunk on Qwen3's 151,936-token vocabulary (one GB300, no TP) the loss's peak memory goes from 1.16 to 3.48 GiB and its forward + backward from 2.1 to 3.6 ms.

The label's logprob already carries the softmax normalizer:

log p_v = log p_y + (logits_v - logits_y) / T

so the k top-k logprobs need only k + 1 gathered logits. Their gradient reaches the dense -p term through log p_y's own graph (d log p_v = d log p_y + (e_v - e_y) / T), which the loss builds anyway. (SkyRL scores its top-k the same way, skyrl-project/SkyRL#2244; Miles scores [sampled, top-k] in one [T, 1 + k] call instead.)

Example.

before   compute_topk_logprobs(logits, ids)               -> log_softmax(logits / T).gather(ids)    saves fp32 [T, V]
after    compute_topk_logprobs(logits, ids, labels=y,
                               label_logprobs=log p_y)    -> log p_y + (logits[ids] - logits[y]) / T  saves [T, k + 1] ids

What changed

  • compute_topk_logprobs takes labels and label_logprobs and uses the formula above. Under TP, _VocabParallelGather gathers the k + 1 logits with one all-reduce (the owner shard contributes each logit, the others 0, so the sum is exact in any order) and scatters the gradient into the local shard. It replaces _VocabParallelTopKLogprobs (three all-reduces and a dense backward).
  • Batch-invariant mode keeps the full-vocabulary log-softmax for the top-k, as before. vLLM's V1 sampler scores its top-k that way. The label formula rounds the last bit differently for 12-16% of the entries (4,096 x 151,936 bf16 logits, k = 32, T = 1.0 and 0.8, max difference 9.5e-7), so batch-invariant mode would lose bitwise top-k parity with vLLM. That mode is for debugging, so its extra fp32 [T, V] doesn't matter.
  • ScoreCentering receives the labels and the trainer's label logprobs from PolicyGradientLoss.
  • The vLLM and SGLang batch-invariant hooks pass the sampled token and its logprob for the new arguments. In batch-invariant mode, compute_topk_logprobs ignores them. vLLM's hook patches the V2 sampler, so it only takes effect with [rl] generator: run on vLLM's model runner V2 (vLLM 0.34) #5956. Today's V1 runner computes the same full-vocabulary log-softmax itself.
  • losses/README.md: the trainer-cost note, with the numbers below.

Alternatives considered

  • One [T, 1 + k] call (Miles): log_softmax(logits / T).gather([label, top-k]), scoring the sampled token and the top-k from a single vocab-wide softmax (radixark/miles, loss/hub/score_centering/selected_log_probs.py). It shares one softmax instead of running two. It still saves the softmax over the vocabulary for backward (one fp32 [T, V] per chunk, unless compile recomputes it). Under TP it needs a vocab-parallel softmax with k + 1 targets: max, sum-exp and gather all-reduces. It also changes the label path. Miles currently keeps fp32 probabilities over [rows, V / TP], about 20 GB at 32K rows for Qwen3; its fused k-target kernel is still open (Fused log-prob op: K targets per row; score centering trains on it radixark/miles#3998). This PR adds no vocab-wide work on top of the label's cross-entropy, which the loss computes anyway, and leaves the label path untouched.
  • SkyRL ([algorithm] Score centering for off-policy correction (arXiv 2609.20807) skyrl-project/SkyRL#2244) scores the top-k as this PR does, from the label logprob.
  • verl (verl/trainer/ppo/score_centering.py) runs a separate chunked top-k pass that saves the logits and recomputes the softmax in backward. NeMo RL (ChunkedDistributedGatherLogprob) recomputes the softmax in backward per chunk.

Numerics

Outside batch-invariant mode, score centering's coefficients change by fp32 rounding: a different but equivalent formula for log p_v. Runs without score centering are unchanged. Batch-invariant mode is unchanged.

Batch-invariant parity, checked directly. On a GPU in batch-invariant mode, the trainer's top-k logprobs equal vLLM V1's (fp32 logits, divide by T, log_softmax, gather) bitwise, for 4,096 x 151,936 bf16 logits, k = 32, T = 1.0 and 0.8. The sampled token's logprob is also bitwise equal. Before this fix, the label formula left 12-16% of the top-k entries 1 ulp off.

Exactly-zero coefficients do not by themselves show that the top-k logprobs match. With an unclipped ratio weight, q * (p / q) and alpha = rho * (1 / rho) evaluate to p and 1 exactly in fp32, so the coefficients are 0 even if q and p differ slightly. Batch-invariant runs never clip.

End to end, with score centering on vs off: rl_grpo_qwen3_0_6b_varlen_batch_invariant (the RL loss-guard recipe, score centering on), real Qwen3-0.6B, TP 2 trainer + TP 2 generator, seed 42, deterministic, lockstep, 10 steps, at 0284cd1:

Generator loss/mean trainer/grad_norm/mean coefficient_l1
vLLM bitwise equal on vs off bitwise equal 0 every step
SGLang bitwise equal on vs off bitwise equal 0 every step

Performance

One loss chunk of 4,096 tokens and a 151,936-token vocabulary, GRPOLoss forward + backward, one GB300 without TP (second-fastest of 4 timed iterations after 2 warm-up ones; peak is torch.cuda.max_memory_allocated above the inputs):

Without score centering Score centering, before (#6384) Score centering, this PR
Compiled loss region (recipes' default): time 2.1 ms 3.6 ms 2.7 ms
Compiled: peak memory 1.16 GiB 3.48 GiB 2.32 GiB
Eager: time 15.1 ms 24.1 ms 16.1 ms
Eager: peak memory 9.27 GiB 9.27 GiB 9.27 GiB

The extra fp32 [T, V] is gone. What remains compiled (+1.16 GiB, one bf16 [T, V]) is a backward buffer of the logits' dtype; the gathered logits' gradient is the likely source, not yet profiled. losses/README.md carries the new numbers.

Testing

  • test_loss.py::test_vocab_parallel_topk_logprobs_parity: vocab-parallel top-k logprobs and gradients (now through the label logprob too) equal the full-vocabulary log-softmax ones, TP=4 and DP2xTP2 with strict SPMD typechecking. In bf16 the gradient arrives in two parts, each rounded once, so the bf16 cases compare with atol=2e-2.
  • test_score_centering.py, test_batch_invariance.py updated for the signature (the batch-invariant no-op test still requires bitwise equal loss and gradient with and without score centering).
  • test_sglang_bitwise_parity.py: compares the generator's top-k logprobs with the trainer's directly (passing the new arguments). All 11 classes CI runs pass on GB300 at 0284cd1: Varlen 8, MoEEP 6 (+1 skipped), GDN 8, GDNHiCache 9, SlidingWindow 7, MLA 6 (+1 skipped), DistMoE 7, KDA 7, MoEDPEP 7 (+1 skipped), KDADPEP 7 (+1 skipped), DistMoEDPEP 8.
  • 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: 953 passed, 5 skipped; 1 failure that also fails on main on this host (test_lora_head_only_matches_cross_entropy, aarch64).

Known issues / follow-ups

Stacked on #6384.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 25, 2026
@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

@github-actions
github-actions Bot requested a review from pzhan9 November 25, 2026 09:08
@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging: the stale losses/README.md cost note, and posting the pending GPU numbers and parity runs. See the 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. This replaces the second full log-softmax with a k + 1 logit gather, which is the right fix for the TODO in #6384. A maintainer still needs to review, since components/loss.py is core.

What this PR does. Before, the top-k logprobs that score centering needs were computed with a second log-softmax over the whole vocabulary, which kept another fp32 [T, V_local] alive for backward. The label's logprob already contains the softmax normalizer, so each top-k logprob can be read off it: log p_v = log p_y + (z_v - z_y) / T. That needs only k + 1 gathered logits per position, and the dense -p part of the gradient flows back through the existing compute_logprobs graph. Under TP, _VocabParallelGather does this with one all-reduce of [T, k + 1] logits, replacing three all-reduces and a dense backward.

Example. One position, T = 1, logits z = log([0.5, 0.3, 0.2]), label y = 0, top-k ids [2, 0]:

before   log_softmax(z)[[2, 0]]                     -> log([0.2, 0.5]); saves fp32 [1, 3] for backward
after    log p_0 + (z[[2, 0]] - z[0])
         = log 0.5 + (log 0.2 - log 0.5, 0)          -> log([0.2, 0.5]); saves ids [1, 3] only
grad     d log p_v = d log p_y + (e_v - e_y)          (the dense part comes from log p_y's CE backward)

Must fix

  1. README not updated. torchtitan/rl/trainer/losses/README.md:62-66 still says the top-k scoring "saves one more fp32 [T, V_local] for backward (TODO in score_centering.py)" and gives the old 1.16 -> 3.48 GiB numbers. This PR deletes that TODO, and the description lists "losses/README.md: the trainer-cost note" under "What changed", but the README is not in the diff. Replace the bullet with the new cost once the GPU numbers are in, or delete it if score centering now costs about the same as running without it.
  2. Description gaps. The "Summary (human-written)" section is empty, and the Numerics paragraph repeats the "Pending:" sentence from Performance. Since "batch-invariant SC on == off" is the claim that keeps the golden unchanged, please post those runs (or point to the ciflow/rl golden job) before merging.

Should consider

  • torchtitan/components/loss.py:631-647: the batch-invariant branch is no longer needed. The function now only selects logits, and that selection is exact under TP, so the extra [T, V] vocab all-gather can go (details and a suggestion inline).
Details
  • Masked rows. Ignored labels are clamped to id 0, and label_logprobs is 0 at those positions, so their top-k values are garbage but finite. ScoreCentering masks its inputs with torch.where (score_centering.py:130-131), and coefficients is 0 off the mask, so neither the metrics nor the gradient read those rows.
  • Gradient. correction = sum_v c_v (lp_v - sg(lp_v)) now sends sum_v c_v into trainer_logprobs, i.e. into the CE backward, plus c_v (e_v - e_y) / T through the gather. That is algebraically the old c_v (e_v - p). The two parts are added in the logits dtype, which explains the bf16 atol=2e-2 in test_loss.py. The extra error is about one bf16 step of |sum c_v|, which is small next to the main loss gradient.
  • SPMD types. _VocabParallelGather is S(-1) -> I@TP, the same type as the old Function. Its backward scatters an I gradient into each rank's own shard, so no collective is needed. The label_logprobs from _LossParallelCrossEntropy are also I@TP.
  • Batch-invariant parity. The trainer and both generator hooks compute log p_y with compute_logprobs. The rest of the formula is elementwise on the same divided logits, so the top-k logprobs stay bitwise equal whenever the sampled-token logprobs do. That condition is already a guaranteed invariant.
  • Callers. All compute_topk_logprobs callers (score centering, vLLM and SGLang hooks, three tests) are updated, and _VocabParallelTopKLogprobs has no remaining references.

Not verified: GPU memory and time numbers, batch-invariant SC on == off, and SGLang parity (all still pending in the description).

Comment on lines 631 to +647
if vocab_parallel_group is not None:
if global_vocab_size is None:
raise ValueError(
"global_vocab_size is required for vocab-parallel top-k logprobs"
)
if not is_in_batch_invariant_mode():
return _VocabParallelTopKLogprobs.apply(
if is_in_batch_invariant_mode():
# dst=I, as in compute_logprobs: backward slices the grad back to this rank's shard.
logits = spmd.redistribute(
logits, vocab_parallel_group, src=spmd.S(-1), dst=spmd.I
)
gathered = logits.gather(-1, token_ids)
else:
gathered = _VocabParallelGather.apply(
logits, token_ids, vocab_parallel_group, global_vocab_size
)
# dst=I, as in compute_logprobs: backward slices the grad back to this rank's shard.
logits = spmd.redistribute(
logits, vocab_parallel_group, src=spmd.S(-1), dst=spmd.I
)
return torch.log_softmax(logits.float(), dim=-1).gather(-1, token_ids)
else:
gathered = logits.gather(-1, token_ids)

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.

(should consider) After this change, compute_topk_logprobs no longer reduces over the vocabulary. Before, the batch-invariant branch was there so that the log-softmax ran through the same batch-invariant ops as the generator. Now the only vocab-dependent step is selecting k + 1 logits, and _VocabParallelGather already selects them exactly: the owner shard contributes x and every other rank contributes 0, and x + 0 is exact in any order and any accumulation dtype. The only difference is the sign of a zero.

So the TP + batch-invariant path can use _VocabParallelGather as well. That deletes this branch and saves one full [T, V] vocab all-gather per loss chunk in batch-invariant TP runs (rl_grpo_0_6b_tp4_batch_invariant). It also removes the "Batch-invariant mode gathers the vocab, as compute_logprobs does" sentence from the docstring (lines 618-620). The generator hooks pass vocab_parallel_group=None, so they don't change.

Suggested change
if vocab_parallel_group is not None:
if global_vocab_size is None:
raise ValueError(
"global_vocab_size is required for vocab-parallel top-k logprobs"
)
if not is_in_batch_invariant_mode():
return _VocabParallelTopKLogprobs.apply(
if is_in_batch_invariant_mode():
# dst=I, as in compute_logprobs: backward slices the grad back to this rank's shard.
logits = spmd.redistribute(
logits, vocab_parallel_group, src=spmd.S(-1), dst=spmd.I
)
gathered = logits.gather(-1, token_ids)
else:
gathered = _VocabParallelGather.apply(
logits, token_ids, vocab_parallel_group, global_vocab_size
)
# dst=I, as in compute_logprobs: backward slices the grad back to this rank's shard.
logits = spmd.redistribute(
logits, vocab_parallel_group, src=spmd.S(-1), dst=spmd.I
)
return torch.log_softmax(logits.float(), dim=-1).gather(-1, token_ids)
else:
gathered = logits.gather(-1, token_ids)
if vocab_parallel_group is not None:
if global_vocab_size is None:
raise ValueError(
"global_vocab_size is required for vocab-parallel top-k logprobs"
)
# A selection: exact, so batch-invariant mode needs no vocab all-gather here.
gathered = _VocabParallelGather.apply(
logits, token_ids, vocab_parallel_group, global_vocab_size
)
else:
gathered = logits.gather(-1, token_ids)

Unverified on GPU: the batch-invariant TP4 golden would confirm that the coefficients stay exactly 0.

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

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.

Applied in bb0d203: _VocabParallelGather now serves batch-invariant mode too (the vocab all-gather branch is gone, docstrings updated). GPU confirmation pending: the batch-invariant TP2 trainer run with score centering on vs off (bitwise loss/grad_norm, coefficients exactly 0) is queued behind tonight's convergence runs on the same machine.

@tianyu-l
tianyu-l force-pushed the fused-topk-logprobs branch from dd35cf2 to bb0d203 Compare November 25, 2026 09:17
@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 57s —— View job


Approve, with two items still open before merging: losses/README.md still has the old cost note, and the GPU numbers and parity runs haven't been posted yet. See the 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. bb0d203 applies the earlier suggestion correctly, and it introduces no new problems. Two items from the first review are still open. components/loss.py is core code, so a maintainer still needs to review.

What changed since the last review. When TP and batch-invariant mode are both on, compute_topk_logprobs now goes through _VocabParallelGather too. The [T, V] vocab all-gather branch is gone, and the docstrings say why that is exact.

Example. One row, TP=2, batch-invariant mode, label y = 0, top-k ids [2, 0], vocab shards [z0, z1 | z2, z3]:

before   all-gather -> [z0, z1, z2, z3].gather([0, 2, 0])         one [T, V] all-gather per chunk
after    rank0 [z0, 0, z0] + rank1 [0, z2, 0] = [z0, z2, z0]        one [T, k + 1] all-reduce; x + 0 is exact
         -> log p_y + ([z2, z0] - z0) / T                           same values bitwise as the gather on the generator side

The gather happens before the temperature division here, while compute_logprobs divides the full logits first. The division is elementwise, and it applies the same dtype promotion in both places, so the gathered values match bitwise.

Resolved

  • loss.py:631-647: the batch-invariant all-gather branch is removed (the earlier should-consider item).

Must fix (still open)

  1. torchtitan/rl/trainer/losses/README.md:62-66: this file still says the top-k scoring "saves one more fp32 [T, V_local] for backward (TODO in score_centering.py)", and it still quotes the 1.16 -> 3.48 GiB and 2.1 -> 3.6 ms numbers. This PR deletes that TODO. The description lists "losses/README.md: the trainer-cost note" under "What changed", but the file is not in the diff. Replace the bullet with the new cost once the GPU numbers are in, or delete it if score centering now costs about the same as running without it.
  2. Description. The "Summary (human-written)" section is still empty. The Numerics paragraph still repeats the "Pending:" sentence from Performance. The GPU results are still pending: batch-invariant runs with score centering on and off should give bitwise-equal loss and grad_norm with coefficients exactly 0, plus loss-chunk time and memory and the SGLang parity classes. Please post them before merging, since the batch-invariant claim is what keeps the golden unchanged.

Not verified: the GPU memory and time numbers, batch-invariant TP equality with score centering on vs off, and SGLang parity.

@tianyu-l
tianyu-l force-pushed the fused-topk-logprobs branch from bb0d203 to 13044da Compare November 25, 2026 10:32
@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 54s —— View job


Approve, with one item still open: the "Summary (human-written)" section is empty. The README cost note and the GPU results are now in. See the 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 README cost note and the GPU numerics, performance and SGLang parity results are now in. The only item left is the empty human-written summary. components/loss.py is core code, so a maintainer still needs to review.

What changed since the last review. losses/README.md now gives the new trainer cost: peak memory goes from 1.16 to 2.32 GiB and time from 2.1 to 2.7 ms, compiled. The description now has the batch-invariant results: with score centering on vs off, TP 2 trainer with vLLM and with SGLang, loss and grad_norm are bitwise equal and the coefficients are exactly 0 for 10 steps. It also has the perf table and the 11 SGLang parity classes. loss.py and the other code files are the same as at the last review.

Example. Where the remaining +1.16 GiB comes from, for the 4,096 x 151,936 chunk:

CE backward            -> grad_logits_ce   bf16 [T, V]
gather backward        -> zeros [T, V] + scatter of k + 1 values   bf16 [T, V]   (_VocabParallelGather.backward / Tensor.gather backward)
autograd accumulation  -> grad_logits_ce + grad_logits_gather
4096 * 151936 * 2 B = 1.16 GiB

This matches the README's "about one more bf16 [T, V_local]". It comes from autograd adding two separate dense gradient contributions into logits. Removing it would take a fused CE + gather backward, so it is not a blocker for this PR.

Resolved

  • torchtitan/rl/trainer/losses/README.md:62-67: the stale cost note and TODO reference are replaced with the new numbers.
  • Description: the duplicated "Pending:" sentences are gone. Batch-invariant on == off (vLLM and SGLang), the loss-chunk time and memory, and the SGLang parity classes are posted.

Must fix (still open)

  1. Description. The "Summary (human-written)" section is still empty. The author has to write it; agents leave it as is (CONTRIBUTING.md, "AI-assisted contributions").

Not verified: the GPU numbers above. The description says they were measured at bb0d203. That commit is not in this checkout, so I couldn't diff it against HEAD 13044da. The description says the only later change is the README, which agrees with the code diff being unchanged since the last review.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

remaining CI failure is due to pytorch nightly update, fixed in #6390

shuhuayu pushed a commit that referenced this pull request Nov 25, 2026
…#6390)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
PyTorch nightly removed
`torch.profiler.CuspyConfig.enable_event_node_ids`
(pytorch/pytorch#206322). Cuspy now reads CUPTI's native CUDA graph
fields for event-record nodes, and their spans come with
`enable_cuda_sync_events`. torchtitan still passes the kwarg, so every
CPU unit test run against the new nightly fails:

```
FAILED tests/unit_tests/cpu/observability/test_profiler.py::TestProfilerEnabled::test_cuspy_activity_config
TypeError: CuspyConfig.__init__() got an unexpected keyword argument 'enable_event_node_ids'
```

It shows up on unrelated PRs from about 10:00 UTC on 2026-11-25, e.g.
#6385 and `shuhuayu/k3-dm-stack-05`.

## What changed
- `CuspyTraceProfiler.Config.enable_event_node_ids` is removed, and is
no longer passed to `CuspyConfig`.
- `get_cuspy_cuda_graph_annotation_config` always keys annotations by
the capture graph (`key_by="auto"`). The exec-graph keying existed only
because Cuspy used to resolve event-record nodes by exec-graph id.
- Tests and the observability README are updated to match.

## User-facing changes
| Before | After |
| --- | --- |
| `CuspyTraceProfiler.Config(enable_event_node_ids=True)` | removed;
graph event-node spans come with `enable_cuda_sync_events=True` |

## Testing
- `pytest tests/unit_tests/cpu/observability/test_profiler.py
tests/unit_tests/cpu/test_trainer.py`: 63 passed, on torch
2.16.0.dev20261030, which still has the field. The new code passes no
kwarg the new nightly lacks.
- Not checked on a GPU: Cuspy traces of CUDA-graphed NCCL event nodes
with the new nightly. `key_by="auto"` relies on upstream's native graph
fields (CUPTI and driver 13.5+, per the upstream PR).
@tianyu-l
tianyu-l force-pushed the fused-topk-logprobs branch from 13044da to aa86f3f Compare November 25, 2026 19:57
@tianyu-l
tianyu-l force-pushed the fused-topk-logprobs branch from aa86f3f to ff33086 Compare November 25, 2026 20:15
@tianyu-l
tianyu-l removed this pull request from stack #6386 November 25, 2026 20:15
@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 31s —— View job


Approve -- the only item left is the empty "Summary (human-written)" section, plus one optional test cleanup. See the 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 squashed commit 0284cd1 puts batch-invariant mode back on the full-vocabulary log-softmax. That is the right call, and it introduces no new problems. The only must-fix left is the empty human-written summary. components/loss.py is core code, so a maintainer still needs to review.

What changed since the last review. With batch-invariant mode on, compute_topk_logprobs now ignores labels and label_logprobs. It divides by the temperature, all-gathers the vocab under TP, and gathers from log_softmax (loss.py:206-219). That is the same as the base branch. All other modes keep the label formula through _VocabParallelGather. This undoes my first review's suggestion, and that suggestion was wrong. Its claim that the label formula stays bitwise equal "whenever the sampled-token logprobs do" only holds when both sides run the same formula. vLLM's V1 runner doesn't use the hook. It scores its top-k with its own full-vocabulary log-softmax, and the author measured 12-16% of entries 1 ulp off with the label formula.

Example. One row in batch-invariant mode, generator on vLLM V1 (no hook), trainer at TP 2:

generator (V1)    log_softmax(z / T)[ids]                         its own kernel, no hook
trainer before    log p_y + (z[ids] - z[y]) / T                   ~15% of entries 1 ulp off -> coefficients != 0
trainer now       log_softmax(all_gather(z) / T)[ids]             bitwise equal (base-branch path)

Resolved

  • loss.py: batch-invariant parity with vLLM V1. The description's runs show score centering on vs off with bitwise-equal loss and grad_norm, coefficients exactly 0 with both vLLM and SGLang, and all 11 SGLang parity classes passing at 0284cd1.

Must fix (still open)

  1. Description. The "Summary (human-written)" section is still empty. The author has to write it; agents leave it as is (CONTRIBUTING.md, "AI-assisted contributions").

Should consider

  • tests/rl/unit_tests/cpu/test_batch_invariance.py:158-159 -- this asserts a kwarg that batch-invariant mode ignores, and its comment no longer holds (inline).
Details
  • Dead arguments in the hooks. Both generator hooks (vllm/batch_invariance.py:56-57, sglang/batch_invariance.py:75-76) pass labels and label_logprobs only because they are required kwargs. They are only active in batch-invariant mode, where those arguments are ignored. Passing real values is harmless, and they would be correct if a hook ever ran outside that mode. I'm not asking for a change here.
  • dtype. _VocabParallelGather now all-reduces in the logits' dtype (bf16) instead of fp32. Each element is x + 0, so the result is still exact. gathered / temperature.unsqueeze(-1) promotes a bf16 [T, k + 1] and an fp32 [T, 1] to fp32, the same promotion as compute_logprobs' division, so the trailing .float() does nothing.
  • Masked rows / gradient / SPMD types. These are unchanged from the earlier review: masked labels are clamped to 0 and their rows are masked by the caller, the gradient is sum c_v into the CE graph plus c_v (e_v - e_y) / T through the gather, and the gather is typed S(-1) -> I@TP.

Not verified: the GPU numbers and parity runs in the description (they need GPUs).

Comment on lines +158 to +159
# The top-k is scored from the sampled token's logprob.
torch.testing.assert_close(topk_kwargs["labels"], token_ids[:, 0].to(torch.int64))

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.

(should consider) This hook is only installed for batch-invariant mode, and in that mode compute_topk_logprobs now ignores labels and label_logprobs and runs the full-vocabulary log-softmax (loss.py:206-219). So the comment is wrong for the path that ships: the generator's top-k is not scored from the sampled token's logprob. The assertion checks a kwarg that path never reads. It would keep passing if the hook passed the wrong labels, and the expected above already checks the output values. Delete both lines.

Suggested change
# The top-k is scored from the sampled token's logprob.
torch.testing.assert_close(topk_kwargs["labels"], token_ids[:, 0].to(torch.int64))

@tianyu-l
tianyu-l force-pushed the fused-topk-logprobs branch from 0284cd1 to 0a723f3 Compare November 25, 2026 23:15
@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: image

Score centering used to run a second log-softmax over all 151,936 logits per position, and this PR gathers only 33 logits and reuses the label's logprob, so a compiled 4,096-token loss chunk on one GB300 drops from 3.48 to 2.32 GiB peak and from 3.6 to 2.7 ms.

log p_v = log p_y + (logits_v - logits_y) / T: the top-k logprobs need only
k + 1 gathered logits and the label's logprob, so the separate top-k
log-softmax (and its saved fp32 [T, V_local]) goes away. The generators'
batch-invariant hooks use the same formula, so trainer and generator top-k
logprobs stay bitwise equal.

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