Skip to content

[rl] Replay top-k/top-p kept sets in the policy loss - #6406

Open
tianyu-l wants to merge 1 commit into
fused-topk-logprobsfrom
sampler-replay
Open

tianyu-l wants to merge 1 commit into
fused-topk-logprobsfrom
sampler-replay

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

RL in torchtitan can only sample from the full vocabulary: SamplingConfig rejects top_p < 1 and has no top_k. With top-k/top-p sampling the generator samples each token from its kept set S (the tokens the filters keep), renormalized: q_S. A trainer scoring the full vocabulary compares p(y) with q_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):

p           = [A 0.50, B 0.30, C 0.15, D 0.05]      S = {A, B}
q_S         = [0.625, 0.375, 0, 0]                  sampled: B
before      : ratio p(B) / q_S(B)   = 0.30 / 0.375 = 0.8
after       : ratio p_S(B) / q_S(B) = (0.30 / 0.80) / 0.375 = 1.0
gradient    : B up, A down; C and D get none

What changed

Generator

  • SamplingConfig.top_k; top_p < 1 requires 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.
  • SGLangEngine requests 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.
  • The controller rejects top-k/top-p sampling at config time unless the engine and the rollouter return kept sets (returns_kept_sets on GenerationEngine.Config and Rollouter.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 a validate check) travels on FinishedRequest -> 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_dict expands 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 dumps completion_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.
  • PolicyGradientLoss replays the kept sets when it receives them; trainer/entropy/mean is then the entropy of p_S.
  • ScoreCentering takes the head logprobs [T, k] (the caller scores the top-k with compute_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.
  • Batch-invariant mode with top-k/top-p raises: SGLang computes q_S from probabilities, not with the trainer's function (TODO).

Mechanical, skimmable: the ~35 test hunks that add max_kept_set_size=None to Batcher constructions, and the transport fields in dispatcher.py, rollouter.py, rollout/types.py, training_sample_builder.py.

Alternatives considered

  • Ragged (CSR) kept sets with a fixed capacity per microbatch (the first revision of this PR): pools room across tokens, but needs a fixed capacity for accelerator graphs; at 2 * top_k per token it used twice the memory of [T, top_k], and it added a RaggedTensor with CP, SPMD and chunked-loss hooks (~480 more lines). Measured kept sets are small and never exceeded top_k (Numerics), so a ragged capacity well below top_k per token could save memory, but it would need an overflow policy for workloads with wide kept sets.
  • Recomputing top-k/top-p on the trainer's logits (NeMo RL's default): when the two models differ (bf16, quantization, stale weights), a sampled token can fall outside the trainer's kept set and is dropped. Replay keeps every sampled token.
  • Full-vocabulary policy with the sampler's filtered logprob (Miles' proposed default, feat(args): opt in to sampling-support replay with --use-rollout-sampling-support-replay radixark/miles#4816): keeps a full-vocabulary objective but puts every ratio below 1 by the dropped mass. A future full-vocabulary term (reference KL, distillation) doesn't need it either: it can compute the trainer's full-vocabulary log p(y) next to the replayed log p_S(y) from the same logits.

User-facing changes

Before After
SamplingConfig(top_p=0.95) raises SamplingConfig(top_p=0.95, top_k=64) samples top-k/top-p, and the loss replays the kept sets (SGLang)
no SamplingConfig.top_k top_k: int | None = None
VLLMEngine samples with any top_p up to 1 the controller raises on top_k or top_p < 1 with VLLMEngine or the Verifiers rollouter
Batcher(..., num_topk_logprobs=k) also max_kept_set_size (int | None, required; top_k with filtering)
rollout recorder dumps completion_topk_* also completion_kept_sets (null without filtering)
score_centering/*_topk_mass = the top-k's mass under replay, 1 by construction; coefficient_l1 is the informative metric

Numerics

  • Runs without top-k/top-p: unchanged. The score-centering top-k path computes the same values as [rl] Score centering: score the top-k from the label's logprob #6385 (only the head logprobs moved to the caller, and masked entries are zeroed explicitly); batch-invariant runs stay bitwise (below).
  • All runs below: 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_p under those overrides), 30 steps:

Metric Graphs off Graphs on (RDMA reading off, per-group graphs)
bit_wise/logprob_diff/mean (trainer log p_S(y) - SGLang log q_S(y)) within +-6e-8 every step bitwise equal to graphs off
loss/ratio_mean 1.0 every step bitwise equal
score_centering/coefficient_l1/mean <= 1.2e-5 bitwise equal
loss/mean, trainer/grad_norm/mean (0.11-1.33) bitwise equal

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 equal loss/mean and trainer/grad_norm/mean, coefficient_l1 exactly 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 over y ~ q_S exactly 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 than top_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

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 26, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 26, 2026
@tianyu-l
tianyu-l added this pull request to stack #6396 November 26, 2026 04:55
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@github-actions
github-actions Bot requested a review from drisspg November 26, 2026 04:55
@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 7m 51s —— View job


Needs discussion: a dense [T, 2*top_k] layout uses the same memory and might remove RaggedTensor, its hooks into CP, SPMD and the chunked loss, and the score-centering rewrite. Also, vLLM and Verifiers fail when each request runs instead of when the config is checked. See 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: 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

  1. The PR description's "Summary (human-written)" section is empty.
  2. torchtitan/rl/generator/vllm/engine.py:783 -- vLLM and Verifiers with top_k/top_p fail per request at runtime, not at config time (inline).
  3. torchtitan/rl/generator/types.py:35, torchtitan/rl/examples/verifiers/generation_server.py:456 -- docs point to kept_token_ids fields that don't exist (inline).

Should consider

  • torchtitan/rl/trainer/batcher.py:142 -- generator_kept_logprobs is shipped and padded even without score centering, its only reader (inline).

Questions

  • Dense vs ragged. The ragged capacity T * 2k is 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 way take_rows already computes positions. Dense would:

    • remove ragged_tensor.py, its test, and the shard_tensors, annotate_input_spmd_types and ChunkedLossWrapper branches (the [T, k] top-k path already covers all three);
    • keep ScoreCentering on [T, k] with .sum(-1), so the top-k path's last-bit numerics change and index_add atomics go away;
    • make compute_kept_set_logprobs a masked logsumexp over the existing gather.

    That is roughly 350-400 fewer lines. The cost: a row with more than 2k members raises, instead of the microbatch (or CP rank, or chunk) average exceeding 2k. With top-k alone every row has at least k members, so pooling only helps when a few rows carry more than k extra tied tokens. How often did kept sets exceed top_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.

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 a torch.where, so gradients stay finite.
  • Checked: per-loss-token alignment (masked_scatter_ on the full loss_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 TrainingMicrobatch at a time, so the schedule never splits a RaggedTensor.
  • Validation rollouts inherit top_k/top_p (controller.py:1072 replaces only temperature), so greedy validation also requests SGLang sampling masks and runs sampled_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.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
"""
# 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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This 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.

Comment thread torchtitan/rl/generator/types.py Outdated
``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

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.

FinishedRequest.kept_token_ids doesn't exist. The field is kept_sets.

Suggested change
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

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.

Completion.kept_token_ids doesn't exist. The field is Completion.kept_sets.

Suggested change
# (`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

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.

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.

@tianyu-l
tianyu-l force-pushed the sampler-replay branch 2 times, most recently from 7d3deae to 426c9cd Compare November 27, 2026 23:08
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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 components/loss.py). See 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 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_ids doc references now say kept_sets.
  • Resolved: generator_kept_logprobs is 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

  1. 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 from compute_topk_logprobs; move it into one shared helper (inline).
  • torchtitan/rl/controller/controller.py:634 -- max_kept_set_size is just sampling.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-centering wheres drop the 0 * -inf NaNs.
  • Checked: score centering over a kept set. Both tail masses clamp to _MIN_TAIL_MASS (1e-6), so rho is about 1. Whatever alpha is, sum_S p_S grad log p_S = 0 makes the alpha * p term's gradient vanish. On the top-k path, the new where on the probabilities only changes rows off the loss mask, and those are masked downstream.
  • Checked: alignment. _pack_kept_sets counts loss_mask[1:], the same as the top-k rows. to_input_dict expands with masked_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.

Comment thread torchtitan/components/loss.py Outdated
Comment on lines +699 to +711
# 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()

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.

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.

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +634 to +638
sampling = self.generator.sampling
if not sampling.filters_vocab:
return None
assert sampling.top_k is not None
return sampling.top_k

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.

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.

Suggested change
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).

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.

[rl] Score centering under top-p / top-k sampling: replay the sampler's support

1 participant