Skip to content

[rl] SGLang generator: top-k logprobs for score centering - #6379

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

tianyu-l wants to merge 1 commit into
score-centeringfrom
sglang-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) needs the generator's top-k logprobs per generated token. With SGLangEngine it raises today.

Example. rl_grpo_qwen3_0_6b_varlen_sglang with GRPOLoss.Config(..., score_centering=ScoreCentering.Config()):

before: ValueError at SGLangEngine init: "SGLangEngine returns no top-k logprobs yet"
after:  each training request asks SGLang for top_logprobs_num=32; FinishedRequest carries
        [num_tokens, 32] ids and logprobs, as with vLLM

What changed

  • SGLangEngine.add_requests passes SamplingConfig.num_topk_logprobs as SGLang's top_logprobs_num (validation requests ask for 0). SGLang computes them from the same temperature-scaled full-vocabulary logprobs as the sampled token's (SGLANG_RETURN_ORIGINAL_LOGPROB is rejected since [rl] SGLang generator: reject SGLANG_RETURN_ORIGINAL_LOGPROB #6375), and its top-k doesn't depend on the sampled token. SGLang needs no engine-wide bound, so max_num_topk_logprobs is unused.
  • _OutputCollector concatenates SGLang's streamed output_top_logprobs_{val,idx} increments per request (the same offsets as the token logprobs) and checks they form [num_tokens, k].
  • Batch-invariant mode (README updated): TrainerLogprobsSampler also recomputes the top-k values at SGLang's ids with the trainer's compute_topk_logprobs, so they match the trainer's bitwise (before, only the sampled token's logprob was recomputed).

Testing

  • test_sglang_bitwise_parity.py: new test_trainer_vs_sglang_topk_logprobs in the shared base class, so every parity class runs it: SGLang's top-k logprobs at decode equal the trainer's compute_topk_logprobs of the same ids, bitwise. Catches a misaligned row (streamed increments) or a top-k computed outside the trainer's code path; either would make score centering's coefficients nonzero in batch-invariant mode.
    • GB300, .venv-sglang at the README's SGLang commit: all 11 classes that CI runs pass, each including the new top-k check (the Dist-MoE classes set their per-call token count through a _before_trainer_forward hook that both trainer helpers call):
Class Result
Varlen (Qwen3-0.6B, TP 2) 8 passed
MoEEP 6 passed, 1 skipped
GDN 8 passed
GDNHiCache 9 passed
SlidingWindow 7 passed
MLA 6 passed, 1 skipped
DistMoE (EP 2 over TP 2) 7 passed
KDA 7 passed
MoEDPEP 7 passed, 1 skipped
KDADPEP 7 passed, 1 skipped
DistMoEDPEP (DP 2 x TP 2, EP 4) 8 passed
  • The new test is the only behavior change for k = 0 requests: max_num_topk_logprobs is accepted and ignored.

Known issues / follow-ups

Stacked on #6378. Next: Verifiers (#6380).

@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
tianyu-l added this pull request to stack #6377 November 25, 2026 06:29
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging: review (the human-written summary is empty, and the new top-k test skips the Dist-MoE token-count setup).

@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 engine change is small and correct: it passes num_topk_logprobs through as SGLang's top_logprobs_num and concatenates the streamed rows. The remaining items are in the description and the new test.

What this PR does. It removes the SGLangEngine guard that rejected score centering. Each request now asks SGLang for top_logprobs_num = num_topk_logprobs. _OutputCollector concatenates SGLang's streamed top-k increments into [num_tokens, k] arrays on FinishedRequest, matching what VLLMEngine returns. In batch-invariant mode, TrainerLogprobsSampler also recomputes the top-k values at SGLang's chosen ids with the trainer's compute_topk_logprobs, the same thing the vLLM hook does (vllm/batch_invariance.py:53).

Example.

GRPOLoss.Config(score_centering=ScoreCentering.Config())  # k = 32, generator = SGLangEngine
before: ValueError at SGLangEngine.__init__ ("returns no top-k logprobs yet")
after:  training request  -> top_logprobs_num=32 -> FinishedRequest.topk_token_ids/topk_logprobs [n, 32]
        validation request -> top_logprobs_num=0  -> topk_* = None
        batch-invariant:   SGLang's ids, trainer's compute_topk_logprobs values -> coefficients == 0

Must fix

  1. PR description. "Summary (human-written)" is empty. The testing section also says "every class passes", but its table covers 7 of the 11 parity classes and leaves out GDNHiCache, KDADPEP, DistMoE and DistMoEDPEP. Please fill in the summary and either add those rows or say they were skipped (e.g. no dist_moe package).
  2. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:319 -- _trainer_topk_logprobs skips the Dist-MoE classes' per-call token-count setup, so on those classes the new test depends on state left by an earlier test (inline).

Should consider

  • tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:292 -- fold the top-k check into test_trainer_vs_sglang_decode rather than adding a second generate to every class (inline).
  • torchtitan/rl/generator/sglang/engine.py:940 -- the shape check mostly repeats batcher.py:1015 (inline).

Questions

  • With k = 32, SGLang's get_top_logprobs does a .tolist() of [B, 32] every decode step, and in batch-invariant mode the new sampler adds one small host-to-device copy per row. Have you measured decode throughput with score centering on vs. off for rl_grpo_qwen3_0_6b_varlen_sglang? The batch-invariant path is debug-only, so its cost matters less; the non-invariant cost is what users will see.
Details
  • Gate: the problem is real (the guard is removed at engine.py:236). The work belongs in the engine, and the trainer side already exists in #6378. The vLLM side is already done, so this isn't one-sided. I found no overlapping open PR.
  • Mixed batches: validation requests (k = 0) and training requests (k > 0) can share a decode step. TrainerLogprobsSampler selects only the rows with len(ids) > 0, and the collector keys on output_top_logprobs_val is not None per batch, with an empty list per k = 0 request. A k = 0 request ends with topk_logprobs == [], so topk_arrays returns None. That's correct.
  • Aborted requests (AbortReq path) carry no top-k. That's fine: token_env.py:237 turns them into ERROR_INFRA before they reach the batcher.
  • I could not read the SGLang source at the README commit. The claims that the top-k ids come from the same temperature-scaled logprobs as the sampled token, and that the CUDA-tensor rows written by TrainerLogprobsSampler reach _OutputCollector in a form np.asarray accepts, rest on the author's GB300 run.

Not verified: no GPU or SGLang in this environment, so none of the parity tests were run here.

Comment on lines +319 to +333
def _trainer_topk_logprobs(self, sequences, *, prompt_lengths, topk_token_ids):
"""The trainer's ``compute_topk_logprobs`` of ``topk_token_ids`` at each
completion position, from one packed prefill of ``sequences``."""
with self.parallelism_context.activate_spmd(), torch.no_grad():
packed = torch.cat(
[torch.tensor(ids, device=self.device) for ids in sequences]
)
positions = torch.cat(
[torch.arange(len(ids), device=self.device) for ids in sequences]
)
logits = self.model(
packed,
attention_metadata=self.model._get_attention_metadata(positions),
positions=positions,
)

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 calls self.model(...) directly, so it skips the _trainer_logprobs override in TestSGLangBitwiseParityDistMoE (line ~822), which calls trainer_dist_moe_runtime.set_num_local_input_tokens_per_call(...) before every trainer forward. The test is in the base class, so it also runs on DistMoE and DistMoEDPEP. There, the trainer forward uses whatever count the previous test left behind, or the runtime's initial value if you run the test alone with -k topk. It passes only if that count happens to match this batch. The PR's results table doesn't list either Dist-MoE class (or GDNHiCache/KDADPEP), so I can't tell whether this path has run at all.

Smallest fix: move the Dist-MoE count setup into a hook that both helpers call. For example, add def _before_trainer_forward(self, sequences): pass to the base class, call it from _trainer_logprobs and _trainer_topk_logprobs, and have the Dist-MoE class override the hook instead of _trainer_logprobs.

Comment on lines +292 to +296
def test_trainer_vs_sglang_topk_logprobs(self):
"""Score centering's top-k logprobs: SGLang's at decode equal the trainer's
``compute_topk_logprobs`` at the same ids, so its coefficients are 0."""
results = self._generate(
self.prompt_ids, num_topk_logprobs=self.NUM_TOPK_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.

The new test adds one more SGLang generate plus a trainer prefill to each of about 11 parity classes, several of them 4-GPU. Instead, test_trainer_vs_sglang_decode could request num_topk_logprobs=self.NUM_TOPK_LOGPROBS in _check_trainer_vs_sglang_decode and check the top-k from the same results. That gives:

  • one generate instead of two;
  • a check that the sampled-token logprobs stay bitwise equal when k > 0 (the new test doesn't check that);
  • top-k coverage on the shared-prompt, cached-KV request in that test, which is the path real GRPO groups take.

_trainer_topk_logprobs also repeats the packing and forward in _varlen_prefill_logprobs (test_bitwise_parity.py:383). If the forward is shared, the Dist-MoE issue above goes away too.

Comment on lines +940 to +949
num_tokens = len(self.token_ids)
if (
topk_logprobs.ndim != 2
or topk_logprobs.shape[0] != num_tokens
or topk_token_ids.shape != topk_logprobs.shape
):
raise ValueError(
f"{request_id}: top-k rows of shape {topk_logprobs.shape} for "
f"{num_tokens} tokens"
)

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.

Two of these checks are already handled elsewhere:

  • A row count that doesn't match the token count is caught by the batcher at batcher.py:1015, which checks rows against loss tokens.
  • Ragged rows already make np.asarray(..., dtype=...) raise.

The only new invariant this checks is that ids and logprobs have the same k. Unlike vLLM's flat layout (vllm/engine.py:828), SGLang can't shift rows here: it returns one row per token, at the same offsets as the token logprobs. Consider dropping the check, or cutting it down to the ids-vs-logprobs shape comparison. Without it, topk_arrays becomes two np.asarray calls that could be inlined at the single call site.

@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 0s —— View job


Approve -- please address the items before merging: review. The diff is unchanged since the last review, so both must-fix items are still open: the empty summary and incomplete test table, and the Dist-MoE token-count setup in the top-k test.

@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 new commit (9e4151c, replacing 3cd40b3) has the same diff as the one I reviewed before: all four files and every hunk match. So both earlier must-fix items are still open, and there are no new findings.

Still open from the last review

  1. PR description. "Summary (human-written)" is still the template placeholder. The testing section still says "every class passes", but the table lists only 7 of the 11 parity classes. GDNHiCache, KDADPEP, DistMoE and DistMoEDPEP are missing. Add those rows, or say they were skipped and why.
  2. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:333 -- _trainer_topk_logprobs still calls self.model(...) directly. The Dist-MoE classes put their set_num_local_input_tokens_per_call setup in a _trainer_logprobs override (line 822). This helper doesn't go through that override, so on DistMoE and DistMoEDPEP the new test depends on whatever token count an earlier test left behind. Running it alone with -k topk would use the runtime's initial count instead. The fix is a _before_trainer_forward(sequences) hook that both helpers call and the Dist-MoE class overrides. The inline comment from the last review still applies.

Should consider (still open)

  • test_sglang_bitwise_parity.py:292 -- fold the top-k check into test_trainer_vs_sglang_decode to save one generate per class. That would also check that the sampled-token logprobs stay bitwise equal when k > 0, and would cover the cached-KV shared-prompt request.
  • torchtitan/rl/generator/sglang/engine.py:940 -- most of the shape check repeats the batcher's row-count check (batcher.py:1015). Only the ids-vs-logprobs shape comparison is new.

Questions (still open)

  • Have you measured decode throughput with score centering on vs. off on SGLang (k = 32)? This is about the cost of the per-step top-k .tolist() outside batch-invariant mode.

A maintainer still needs to review this PR.

Not verified: there is no GPU or SGLang in this environment, so I didn't run the parity tests.

@tianyu-l
tianyu-l force-pushed the sglang-topk-logprobs branch from 9e4151c to 2b31156 Compare November 25, 2026 07:43
@tianyu-l
tianyu-l marked this pull request as ready for review November 25, 2026 07:55
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 25, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 25, 2026 07:55
@tianyu-l
tianyu-l force-pushed the sglang-topk-logprobs branch from 2b31156 to 911ffb8 Compare November 25, 2026 08:08
@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 47s —— View job


Approve -- please address the item before merging: review. The Dist-MoE test fix and the full results table are in; only the empty human-written summary is left.

@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 new commit (911ffb8) fixes the Dist-MoE test setup and fills in the results table. The only must-fix left is the empty human-written summary.

Resolved since the last review

  • Dist-MoE token count in the top-k test: fixed. _before_trainer_forward(sequences) (test_sglang_bitwise_parity.py:258) now runs at the start of both _trainer_logprobs (:263) and _trainer_topk_logprobs (:328). The Dist-MoE class overrides the hook (:829) and no longer overrides _trainer_logprobs. No other self.model(...) call skips the hook.
  • Results table: it now lists all 11 parity classes, including GDNHiCache, KDADPEP, DistMoE and DistMoEDPEP.

Must fix

  1. PR description. "Summary (human-written)" is still the template placeholder. The author needs to write it.

Should consider (still open, not blocking)

  • test_sglang_bitwise_parity.py:298: you could fold the top-k check into test_trainer_vs_sglang_decode. That saves one generate per class, checks that the sampled-token logprobs stay bitwise equal when k > 0, and covers the cached-KV shared-prompt request.
  • torchtitan/rl/generator/sglang/engine.py:940: most of the shape check repeats batcher.py:1015. Only the ids-vs-logprobs shape comparison is new.

Questions (still open)

  • Have you measured decode throughput on SGLang with score centering on vs. off (k = 32)? This is about the cost of SGLang's per-step top-k .tolist() outside batch-invariant mode.

The diff touches the RL generator, so a maintainer still needs to review.

Not verified: there is no GPU or SGLang here, so I didn't run the parity tests. The passing results come from the author's GB300 run.

@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: image

Each training request now asks SGLang for its top 32 tokens per generated token, the streamed rows are stacked into one tokens × 32 array per request, and validation requests ask for none.

@tianyu-l
tianyu-l force-pushed the sglang-topk-logprobs branch from 7462582 to 1288014 Compare November 26, 2026 04:08

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