Repository navigation
Conversation
|
@claude review |
|
Claude finished @tianyu-l's task in 7m 51s —— View job Needs discussion: a dense |
There was a problem hiding this comment.
Verdict: Needs discussion -- the replay math is right, but a dense [T, 2 * top_k] layout with the same device memory might make RaggedTensor, its three core hooks, and the score-centering rewrite unnecessary.
What this PR does. It allows top-k/top-p sampling on SGLang. Each sampled token's kept set S and the generator's q_S travel to the trainer. The trainer renormalizes its logprobs over the same tokens, so the ratio compares p_S with q_S. Kept sets are packed per loss token and padded on device into a RaggedTensor (capacity T * 2 * top_k). CP, SPMD annotation and ChunkedLossWrapper learn to shard or split it. Score centering moves to flat entries with per-row index_add.
Example.
p = [A .50, B .30, C .15, D .05], top_p 0.8 -> S = {A, B}, sampled B, q_S(B) = 0.375
main : SamplingConfig(top_p=0.8) raises
PR : log p_S(B) = logit_B/T - logsumexp_{A,B}(logit/T) = log 0.375 -> ratio 1.0
gradient reaches only A and B; transport: ids [A, B], lengths [2] per loss token
Must fix
- The PR description's "Summary (human-written)" section is empty.
torchtitan/rl/generator/vllm/engine.py:783-- vLLM and Verifiers withtop_k/top_pfail per request at runtime, not at config time (inline).torchtitan/rl/generator/types.py:35,torchtitan/rl/examples/verifiers/generation_server.py:456-- docs point tokept_token_idsfields that don't exist (inline).
Should consider
torchtitan/rl/trainer/batcher.py:142--generator_kept_logprobsis shipped and padded even without score centering, its only reader (inline).
Questions
-
Dense vs ragged. The ragged capacity
T * 2kis the same device memory as a dense[T, 2k]tensor with a validity mask. The dense tensor can be built on device from the same packed transport, without a host sync, the waytake_rowsalready computes positions. Dense would:- remove
ragged_tensor.py, its test, and theshard_tensors,annotate_input_spmd_typesandChunkedLossWrapperbranches (the[T, k]top-k path already covers all three); - keep
ScoreCenteringon[T, k]with.sum(-1), so the top-k path's last-bit numerics change andindex_addatomics go away; - make
compute_kept_set_logprobsa masked logsumexp over the existing gather.
That is roughly 350-400 fewer lines. The cost: a row with more than
2kmembers raises, instead of the microbatch (or CP rank, or chunk) average exceeding2k. With top-k alone every row has at leastkmembers, so pooling only helps when a few rows carry more thankextra tied tokens. How often did kept sets exceedtop_k, and by how much, in the GB300 runs? The "Alternatives considered" entry compares against a small margin that drops rows; it doesn't compare against this same-memory dense layout that raises. - remove
Details
- Checked: the NaN paths in
compute_kept_set_logprobs. With padding clamped into an empty last row,exp(-inf - -inf)is NaN in forward, but every NaN stops at atorch.where, so gradients stay finite. - Checked: per-loss-token alignment (
masked_scatter_on the fullloss_mask, matching_pack_kept_sets'loss_mask[1:]count). - Checked: CP load-balanced sharding uses the same permutation slice as
_permute_tensor. - Checked: PP microbatches are prepared one
TrainingMicrobatchat a time, so the schedule never splits aRaggedTensor. - Validation rollouts inherit
top_k/top_p(controller.py:1072replaces only temperature), so greedy validation also requests SGLang sampling masks and runssampled_logprobs. - Core code is touched (CP, SPMD,
components/loss.py): a maintainer still needs to review.
Not verified: SGLang's return_sampling_mask / SamplingMaskChunk API, and whether it keeps ties at the top-k cutoff (the 2 * top_k capacity rests on this); greedy validation with a sampling mask; the GPU numerics in the description.
| """ | ||
| # TODO: replay top-k/top-p kept sets on vLLM's V2 model runner (#5956): its sampler returns | ||
| # them (return_sampling_mask), and processed logprobs renormalize over them. | ||
| if sampling.filters_vocab: |
There was a problem hiding this comment.
This raise happens per request, not at config time. _build_sampling_params runs inside the try at line 562, so the ValueError turns into a rejected request: with VLLMEngine (the default engine) and top_k set, the job loads the models and then every rollout fails, and it never stops with a clear config error.
Verifiers has the same gap. VerifiersRollouter (examples/verifiers/rollouter.py:324) doesn't forward top_k, so top_k=64, top_p=1.0 samples from the full vocabulary, and the run only dies later when _pack_kept_sets raises "has no kept sets". With top_p < 1 the generation server's SamplingConfig rejects each request instead.
Fix: raise in Controller.Config.__post_init__ when generator.sampling.filters_vocab is set with an engine or rollouter that can't return kept sets. For example, add an engine-config property like the existing uses_mooncake_store (False by default, True on SGLangEngine.Config) and check the rollouter type. Then delete this per-request raise.
| ``top_p`` of their probability); None keeps every token. | ||
|
|
||
| When ``top_k`` or ``top_p`` filters the vocabulary, the generator returns each sampled token's | ||
| kept set (``FinishedRequest.kept_token_ids``) and the trainer replays it: it renormalizes its |
There was a problem hiding this comment.
FinishedRequest.kept_token_ids doesn't exist. The field is kept_sets.
| kept set (``FinishedRequest.kept_token_ids``) and the trainer replays it: it renormalizes its | |
| kept set (``FinishedRequest.kept_sets``) and the trainer replays it: it renormalizes its |
| # computes logprobs over the full vocabulary. TODO(mask-replay): allow them, as for top_p < 1. | ||
| # Verifiers sends top_k=-1 and min_p=0.0 on every call. Refuse values that filter. | ||
| # TODO: allow top_k / top_p < 1: return each completion's kept sets | ||
| # (`Completion.kept_token_ids`) with the top-k rows, and slice them per trainable span in |
There was a problem hiding this comment.
Completion.kept_token_ids doesn't exist. The field is Completion.kept_sets.
| # (`Completion.kept_token_ids`) with the top-k rows, and slice them per trainable span in | |
| # (`Completion.kept_sets`) with the top-k rows, and slice them per trainable span in |
| loss_kwargs["generator_topk_logprobs"] = self.generator_topk_logprobs | ||
| if self.generator_kept_lengths is not None: | ||
| loss_kwargs["generator_kept_token_ids"] = self.generator_kept_token_ids | ||
| loss_kwargs["generator_kept_logprobs"] = self.generator_kept_logprobs |
There was a problem hiding this comment.
PolicyGradientLoss only reads generator_kept_logprobs in the score-centering branch (policy_gradient.py:233-236). The SGLang engine already uses the kept logprobs to set generator_logprobs. Without score centering, this ships and pads a [T * 2 * top_k] fp32 buffer per microbatch that nothing reads (and CP-shards and chunk-splits it too).
Suggestion: pack it only when the loss has score centering, the same way num_topk_logprobs is gated on ScoreCentering.Config.
7d3deae to
426c9cd
Compare
|
@claude review again |
|
Claude finished @tianyu-l's task in 3m 11s —— View job Approve -- please address the items before merging (the human-written summary is still empty; a maintainer still needs to review the core change in |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the dense [T, top_k] rewrite drops RaggedTensor and its core hooks, and vLLM and Verifiers now fail when the config is checked. Only the human-written summary is still missing. components/loss.py is core code, so a maintainer still needs to review.
What changed since the last review. Kept sets are now padded to [T, top_k]: ids are padded with 0 and logprobs with -inf, which marks the padding. A kept set wider than top_k raises. On the trainer they reuse the top-k path's expansion, CP sharding (the generic loss_kwarg_sharding) and chunking. compute_kept_set_logprobs is a masked logsumexp over the gathered logits. ScoreCentering now takes head logprobs plus an optional head mask. The controller checks returns_kept_sets on the engine and rollouter configs.
Example.
top_k 3, kept sets [[5, 7], [2]] for two loss tokens
batcher -> ids [[5, 7, 0], [2, 0, 0]], logprobs [[-0.4, -1.1, -inf], [0.0, -inf, -inf]]
trainer -> log p_S(y) = logit_y/T - logsumexp over the finite-logprob columns
VLLMEngine + top_k=64 -> before: every request rejected at runtime; now: ValueError at config time
Earlier findings
- Resolved: vLLM and Verifiers are now rejected at config time (
controller.py:557), and the per-request raise is gone. - Resolved: the
kept_token_idsdoc references now saykept_sets. - Resolved:
generator_kept_logprobsis now always read, because it supplies the kept mask (policy_gradient.py:176). - Resolved: dense vs ragged. The description now compares the two and reports kept-set sizes: max 64, none above
top_k. - Still open: the "Summary (human-written)" section is empty.
Must fix
- The PR description's "Summary (human-written)" section is empty. The author has to write it.
Should consider
torchtitan/components/loss.py:699-- this gather-and-scale code is copied fromcompute_topk_logprobs; move it into one shared helper (inline).torchtitan/rl/controller/controller.py:634--max_kept_set_sizeis justsampling.top_k(inline).
Details
- Checked: NaN paths. A row without kept tokens normalizes over its placeholders. Masked entries pass a zero gradient through both
torch.wheres, and the entropy and score-centeringwheres drop the0 * -infNaNs. - Checked: score centering over a kept set. Both tail masses clamp to
_MIN_TAIL_MASS(1e-6), sorhois about 1. Whateveralphais,sum_S p_S grad log p_S = 0makes thealpha * pterm's gradient vanish. On the top-k path, the newwhereon the probabilities only changes rows off the loss mask, and those are masked downstream. - Checked: alignment.
_pack_kept_setscountsloss_mask[1:], the same as the top-k rows.to_input_dictexpands withmasked_scatter_on the same mask, with -inf fill for the logprobs. - Checked: RDMA microbatches and SPMD annotation handle loss kwargs generically (
decoder_sharding.loss_kwarg_sharding), so the new tensors need no change there. - Checked: batch-invariant mode with top-k/top-p raises at config time.
Not verified: SGLang's return_sampling_mask, sampling_logprobs_mode="support" and SamplingMaskChunk at the pinned version; greedy validation with a sampling mask; the GPU numerics in the description.
| # Ignored labels (loss-masked positions) gather a placeholder column; callers mask | ||
| # those rows. | ||
| token_ids = torch.cat( | ||
| [labels.clamp_min(0).unsqueeze(-1), kept_token_ids], dim=-1 | ||
| ).long() | ||
| if vocab_parallel_group is not None: | ||
| gathered = _VocabParallelGather.apply( | ||
| logits, token_ids, vocab_parallel_group, global_vocab_size | ||
| ) | ||
| else: | ||
| gathered = logits.gather(-1, token_ids) | ||
| # compute_logprobs' division, after the gather: elementwise, so the values are the same. | ||
| scaled = (gathered / temperature.unsqueeze(-1)).float() |
There was a problem hiding this comment.
These 13 lines are the same as compute_topk_logprobs' non-batch-invariant path (lines 645-657): prepend the label, gather (with _VocabParallelGather under TP), then divide by the temperature and cast to fp32. If one copy changes, for example the order of the division and the cast, the top-k head and the kept-set head will score logits differently, and nothing flags it.
Suggestion: move them into a private _gather_scaled_logits(logits, token_ids, *, labels, vocab_parallel_group, global_vocab_size, temperature) -> [T, 1 + k] that both functions call. That removes about 10 lines, and the two paths then scale logits identically by construction.
| sampling = self.generator.sampling | ||
| if not sampling.filters_vocab: | ||
| return None | ||
| assert sampling.top_k is not None | ||
| return sampling.top_k |
There was a problem hiding this comment.
top_p < 1 already requires top_k (SamplingConfig.__post_init__), so filters_vocab holds exactly when top_k is not None. The branch and the assert can't change the result.
| sampling = self.generator.sampling | |
| if not sampling.filters_vocab: | |
| return None | |
| assert sampling.top_k is not None | |
| return sampling.top_k | |
| return self.generator.sampling.top_k |
With top-k/top-p sampling the generator samples each token from its kept set S, renormalized (q_S). The generator (SGLang) now returns each token's kept set and q_S over it (KeptSets); the batcher pads them to [T, top_k] rows (-inf marks padding; a larger kept set raises), and the loss renormalizes the trainer's logprobs over the same tokens (compute_kept_set_logprobs). The kept set is score centering's head, with no tail. The controller rejects top-k/top-p sampling with an engine or rollouter that can't return kept sets (vLLM until its V2 model runner, #5956; Verifiers).
426c9cd to
fc5b1bc
Compare
Summary (human-written)
Why
RL in torchtitan can only sample from the full vocabulary:
SamplingConfigrejectstop_p < 1and has notop_k. With top-k/top-p sampling the generator samples each token from its kept setS(the tokens the filters keep), renormalized:q_S. A trainer scoring the full vocabulary comparesp(y)withq_S(y)and puts every importance ratio below 1 by the mass the filters drop, even when the trainer and the generator agree; score centering (#6378) would also model a tail the generator never samples.This PR replays the kept set, as Miles (radixark/miles#3354) and NeMo RL (sampler replay) do: the generator returns each token's kept set, and the trainer renormalizes over the same tokens. Part of #6387: vLLM (after #5956), Verifiers, batch-invariant mode with top-k/top-p and the sparse LM-head backward stay TODOs.
Example (one position, top-p 0.8, trainer equal to the generator):
What changed
Generator
SamplingConfig.top_k;top_p < 1requires it: it bounds each kept set, which top-p alone doesn't (on a flat distribution top-p can keep most of the vocabulary).SamplingConfig.filters_vocab.SGLangEnginerequests each token's kept set with its logprobs renormalized over it (return_sampling_mask,sampling_logprobs_mode="support", only on requests that filter), at the pinned SGLang. The generator logprob becomes the sampled token's, from its kept set. TODO for [Feat] sampling: Return sampling logprobs and masks through two independent flags sgl-project/sglang#51439's new flags.returns_kept_setsonGenerationEngine.ConfigandRollouter.Config): only SGLang does. vLLM's V1 model runner can't (TODO for [rl] generator: run on vLLM's model runner V2 (vLLM 0.34) #5956's V2 runner); the Verifiers generation server keeps refusing top-k/top-p (TODO).Transport (mirrors #6378's top-k fields):
KeptSets(ids, logprobs, sizes, packed token after token, with avalidatecheck) travels onFinishedRequest->Completion->RolloutTurn->TrainingSample, one kept set per loss token. The batcher pads each to a[top_k]row (ids with 0, logprobs with -inf, which marks the padding) and raises on a larger kept set;to_input_dictexpands the rows to[T, top_k]exactly like the top-k rows, so CP sharding, SPMD typing and the chunked loss need no change. The rollout recorder dumpscompletion_kept_sets.Trainer
compute_kept_set_logprobs(components/loss.py):log p_S(v) = logits_v / T - logsumexp_{u in S}(logits_u / T), a masked logsumexp over the label's and the kept tokens' gathered logits (_VocabParallelGather, one TP all-reduce, as for the top-k), no[T, V]softmax.PolicyGradientLossreplays the kept sets when it receives them;trainer/entropy/meanis then the entropy ofp_S.ScoreCenteringtakes the head logprobs[T, k](the caller scores the top-k withcompute_topk_logprobs, or passes the kept sets) and an optional head mask for kept-set padding. A kept set holds all of the generator's probability, so its tail is empty and the centering exact.q_Sfrom probabilities, not with the trainer's function (TODO).Mechanical, skimmable: the ~35 test hunks that add
max_kept_set_size=NonetoBatcherconstructions, and the transport fields indispatcher.py,rollouter.py,rollout/types.py,training_sample_builder.py.Alternatives considered
2 * top_kper token it used twice the memory of[T, top_k], and it added aRaggedTensorwith CP, SPMD and chunked-loss hooks (~480 more lines). Measured kept sets are small and never exceededtop_k(Numerics), so a ragged capacity well belowtop_kper token could save memory, but it would need an overflow policy for workloads with wide kept sets.log p(y)next to the replayedlog p_S(y)from the same logits.User-facing changes
SamplingConfig(top_p=0.95)raisesSamplingConfig(top_p=0.95, top_k=64)samples top-k/top-p, and the loss replays the kept sets (SGLang)SamplingConfig.top_ktop_k: int | None = NoneVLLMEnginesamples with anytop_pup to 1top_kortop_p < 1withVLLMEngineor the Verifiers rollouterBatcher(..., num_topk_logprobs=k)max_kept_set_size(int | None, required;top_kwith filtering)completion_topk_*completion_kept_sets(null without filtering)score_centering/*_topk_mass= the top-k's masscoefficient_l1is the informative metricNumerics
scripts/rl/loss_compare.py's deterministic configuration (seed 42, lockstep,target_offpolicy_steps=0) with the trainer at TP 2 and the generator at TP 2 (4 GB300s), Qwen3-0.6B alphabet sort.Top-k 64 / top-p 0.95, CISPO + score centering, SGLang (
rl_cispo_score_centering_qwen3_0_6b_varlen_sglang_top_punder those overrides), 30 steps:bit_wise/logprob_diff/mean(trainerlog p_S(y)- SGLanglog q_S(y))loss/ratio_meanscore_centering/coefficient_l1/meanloss/mean,trainer/grad_norm/mean(0.11-1.33)Against the ragged first revision: step 1 has the same loss, entropy and reward and a grad norm 1.4e-4 relative apart (logsumexp vs scatter-reduce rounding); from step 2 the weights differ in the last bits, the generator samples other rollouts, and the runs drift apart as any two non-batch-invariant runs do.
Kept-set sizes (10 steps, 12,077 loss tokens, top-k 64 / top-p 0.95): mean 1.10, p99 2, p99.9 4, max 64; 0 above
top_k.Batch-invariant (
rl_grpo_qwen3_0_6b_varlen_batch_invariant, which enables score centering), vLLM, 10 steps: score centering on vs off bitwise equalloss/meanandtrainer/grad_norm/mean,coefficient_l1exactly 0, and bitwise equal to the previous revision, so the golden is unchanged.Testing
test_loss.py::test_vocab_parallel_kept_set_logprobs_parity: padded kept-set logprobs and gradients, vocab-sharded (TP 4, DP 2 x TP 2) under strict SPMD typechecking, match a per-token renormalization (fp32 and bf16); a token without a kept set keeps the gradient finite.test_score_centering.py::test_score_centering_cancels_drift_over_the_kept_set: replay + score centering (padded rows) makes the expected update overy ~ q_Sexactly 0 at a constant advantage for all five losses and both advantage signs; without centering it isn't, and only kept tokens' logits move.test_batcher.py::test_microbatch_ships_kept_sets_for_loss_tokens_only: padded rows, alignment with the shifted labels, per-sample count check, and the raise on a kept set wider thantop_k.pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_loss.py tests/unit_tests/cpu/models/common/test_cp_attention.py tests/unit_tests/cpu/models/common/test_decoder_loss_kwargs.py: 937 passed, 7 skipped; 1 failure that also fails on main on this host (test_lora_head_only_matches_cross_entropy, aarch64).Known issues / follow-ups