Repository navigation
Conversation
|
@claude review |
There was a problem hiding this comment.
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
- README not updated.
torchtitan/rl/trainer/losses/README.md:62-66still says the top-k scoring "saves one more fp32[T, V_local]for backward (TODO inscore_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. - 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/rlgolden 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_logprobsis 0 at those positions, so their top-k values are garbage but finite.ScoreCenteringmasks its inputs withtorch.where(score_centering.py:130-131), andcoefficientsis 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 sendssum_v c_vintotrainer_logprobs, i.e. into the CE backward, plusc_v (e_v - e_y) / Tthrough the gather. That is algebraically the oldc_v (e_v - p). The two parts are added in the logits dtype, which explains the bf16atol=2e-2intest_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.
_VocabParallelGatheris 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. Thelabel_logprobsfrom_LossParallelCrossEntropyare also I@TP. - Batch-invariant parity. The trainer and both generator hooks compute
log p_ywithcompute_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_logprobscallers (score centering, vLLM and SGLang hooks, three tests) are updated, and_VocabParallelTopKLogprobshas no remaining references.
Not verified: GPU memory and time numbers, batch-invariant SC on == off, and SGLang parity (all still pending in the description).
| 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) |
There was a problem hiding this comment.
(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.
| 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.
There was a problem hiding this comment.
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.
dd35cf2 to
bb0d203
Compare
|
@claude review again |
There was a problem hiding this comment.
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)
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 inscore_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.- 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.
bb0d203 to
13044da
Compare
|
@claude review again |
There was a problem hiding this comment.
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)
- 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.
|
remaining CI failure is due to pytorch nightly update, fixed in #6390 |
…#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).
13044da to
aa86f3f
Compare
aa86f3f to
ff33086
Compare
ff33086 to
0284cd1
Compare
|
@claude review again |
There was a problem hiding this comment.
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)
- 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) passlabelsandlabel_logprobsonly 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.
_VocabParallelGathernow all-reduces in the logits' dtype (bf16) instead of fp32. Each element isx + 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 ascompute_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_vinto the CE graph plusc_v (e_v - e_y) / Tthrough 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).
| # The top-k is scored from the sampled token's logprob. | ||
| torch.testing.assert_close(topk_kwargs["labels"], token_ids[:, 0].to(torch.int64)) |
There was a problem hiding this comment.
(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.
| # The top-k is scored from the sampled token's logprob. | |
| torch.testing.assert_close(topk_kwargs["labels"], token_ids[:, 0].to(torch.int64)) |
0284cd1 to
0a723f3
Compare
0a723f3 to
9f0ecef
Compare
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.
9f0ecef to
c21f5ca
Compare

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:
so the k top-k logprobs need only k + 1 gathered logits. Their gradient reaches the dense
-pterm throughlog 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.
What changed
compute_topk_logprobstakeslabelsandlabel_logprobsand uses the formula above. Under TP,_VocabParallelGathergathers 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).[T, V]doesn't matter.ScoreCenteringreceives the labels and the trainer's label logprobs fromPolicyGradientLoss.compute_topk_logprobsignores 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
[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.log p_y's rounding. In fp32 that error is last-bit level, far below the trainer/generator mismatch score centering corrects. Logprob precision near p ~ 1 (open draft fix(lm_head): exact log-probabilities and gradients for near-certain tokens PrimeIntellect-ai/prime-rl#4561) would affect the label and the top-k together here.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)andalpha = rho * (1 / rho)evaluate topand 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:loss/meantrainer/grad_norm/meancoefficient_l1Performance
One loss chunk of 4,096 tokens and a 151,936-token vocabulary,
GRPOLossforward + backward, one GB300 without TP (second-fastest of 4 timed iterations after 2 warm-up ones; peak istorch.cuda.max_memory_allocatedabove the inputs):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.mdcarries 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 withatol=2e-2.test_score_centering.py,test_batch_invariance.pyupdated 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.