Skip to content

[rl] Score centering: generator top-k logprobs + ScoreCenteringLoss - #5760

Closed
felipemello1 wants to merge 14 commits into
pytorch:mainfrom
felipemello1:felipemello1/score-centering
Closed

felipemello1 wants to merge 14 commits into
pytorch:mainfrom
felipemello1:felipemello1/score-centering

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: Adds score centering (https://arxiv.org/abs/2609.20807), an opt-in RL loss that cancels the bias a trainer/generator mismatch adds to the policy gradient. Turn it on with SamplingConfig.num_topk_logprobs=k and ScoreCenteringLoss. With k=0 (the default) nothing changes.

vLLM logprobs=k -> Completion [generated, k] -> TrainingSample [loss tokens, k] -> microbatch [loss tokens, k]
                -> TrainingMicrobatch.to_input_dict: scatter to [T, k] on the trainer's device -> ScoreCenteringLoss
generator=Generator.Config(sampling=SamplingConfig(..., num_topk_logprobs=32)),
trainer=Trainer.Config(loss=ChunkedLossWrapper.Config(loss_fn=ScoreCenteringLoss.Config(global_vocab_size=...))),
# masked importance sampling instead of the default truncation at 2.0:
ScoreCenteringLoss.Config(ratio_band=(0.2, 5.0), global_vocab_size=...)

Problem

  1. The trainer scores each sampled token with its policy p. vLLM sampled it from a slightly different q (kernels, quantization, MoE routing, staleness).
  2. So each position's expected policy gradient has a term with no reward in it: E_q[A] * sum_v q_v * grad log p_v. It pulls p toward q (paper Eq. 3). Group-mean advantages don't remove it: at later positions E[A | prefix] != 0.
  3. Each weight sync feeds the pull back into vLLM, so it compounds. Paper, Qwen3-30B-A3B with an INT8 sampler and INT4 KV cache: score centering 30% accuracy, truncated IS 12%, the other methods below 5%. Under a mild FP8 sampler all of them tie (57-58%).
  4. The mismatch grows in async TorchTitan runs too. Qwen3.5-35B-A3B with this loss (truncated IS, k=32), bf16 generator, policy age 5-7: the mean log p - log q went from -0.003 (step 145) to -0.018 (steps 160-162), and the share of tokens with p / q > 2 from 0.02% (step 105) to 0.56% (steps 160+).

Solution

  1. Subtract each position's expected score from the token's score, over vLLM's top-k tokens H; the trainer models the tail (paper Eq. 12). The correction is exactly 0 when p == q:
    token_loss = -A * (w(p_y/q_y) * log p_y - sum_H detach(q_v * w(p_v/q_v) - alpha * p_v) * log p_v)
  2. ScoreCenteringLoss (torchtitan/rl/trainer/losses/score_centering.py). The token weight w(r) is truncated (max_ratio=2.0, the default and the paper's TIS cap) or masked (ratio_band=(lo, hi), which replaces the cap; the paper's MIS+SC).
  3. compute_topk_logprobs sits next to compute_logprobs, in the same "loss" compile region. Under TP it gets the logprobs of the k ids with three all-reduces, without gathering the vocab. In batch-invariant mode it gathers the vocab, like compute_logprobs, and vLLM's logprob patch calls the same function, so the trainer's and the generator's top-k logprobs match bitwise.
  4. Transport: SamplingConfig.num_topk_logprobs -> vLLM logprobs=k -> Completion -> RolloutTurn -> TrainingSample, which keeps one row per loss token. TrainingMicrobatch.to_input_dict scatters the rows into [T, k] on the device (masked_scatter_, no host sync).
  5. loss_kwarg_sharding gives a loss input with trailing dims the labels' token layout plus replicated trailing dims, so CP and SPMD typing accept [T, k]. Every model's preprocess_inputs uses it; a 1-D loss input gets the same layout as before.
  6. ScoreCenteringLoss logs loss/mismatch_kl/mean: the mean of exp(r) - 1 - r over loss tokens, with r = log p - log q. It is the k3 estimate of KL(generator || trainer). Unlike bit_wise/logprob_diff/mean, mismatches of opposite sign don't cancel.

Unchanged: DAPOLoss and GRPOLoss numerics (their two helpers become public: MAX_LOG_RATIO, normalize), _LossParallelCrossEntropy (its shard code moved to _local_vocab_shard, which the top-k path shares; only the error text changed), every recipe, and every path with num_topk_logprobs=0, except three things:

  • log_logprobs rollout dumps gain two null top-k keys per turn.
  • The Verifiers generation server rejects a request without num_topk_logprobs (HTTP 422), as it does for temperature, top_p and max_tokens. The rollouter always sends it.
  • SGLangEngine takes num_topk_logprobs and raises for k > 0: it returns no top-k logprobs. Untested: the only test that builds an SGLangEngine needs 2 GPUs.

Results

A Qwen3.8-27B SWE-rebench V2.1 run on 6 GB300 nodes, planned for 50 steps, trained with this code, ported onto an earlier main next to other changes: ScoreCenteringLoss(ratio_band=(0.2, 5.0)), num_topk_logprobs=128, Verifiers rollouts, top-k rows sent to the trainer in RDMA microbatches. It was stopped in step 3 because the controller host was running out of RAM (NOTE below). Step 1:

score_centering/{generator,trainer}_topk_mass/mean    0.9982 vs 0.9982
loss/mismatch_kl/mean                                  1.13e-3
loss/ratio_masked_frac                                 5.4e-5
score_centering/tail_masked_frac                       3.7e-4
score_centering/coefficient_l1/mean                    3.7e-4
top-k errors ("no generation", "share prompt length")  0
trainer peak reserved memory                           177.2 GiB (64.0% of a GB300), 0 allocation retries

Step 2: loss/mismatch_kl/mean 1.30e-3, trainer peak reserved 202.9 GiB (73.3%, now with Adam's states), 0 allocation retries.
GPU smoke at d5178ef, before the merge of main: Qwen3-0.6B alphabet_sort on 2 GPUs (trainer TP1 + generator TP1), 10 steps, up to 3 steps off-policy, one seed per arm:

                          validation reward (20 prompts)   mean log p - log q at step 6   max |log p - log q|
GRPOLoss (k=0)            0.179 -> 0.272                   -0.019                         8.0
ScoreCenteringLoss (k=32) 0.179 -> 0.368                   -0.035                         15.9

ScoreCenteringLoss: generator vs trainer top-k mass 0.9999997 vs 0.9999998; coefficient_l1 <= 0.0039; ratio_truncated_frac <= 0.27%

Both arms drift at the same steps (most at step 6), which follow the recipe's off-policy steps. At step 6 the score-centering arm drifts about 2x more. One possible cause: it has no PPO clip, so a step can move the policy further. One seed can't tell that from noise. 10 steps show the loss trains; they don't show it beats GRPO.

CPU unit tests at this head and on main c561820, same venv (torch 2.16.0.dev20261107, verifiers==0.4.0, torch_checkpointing at main's pin):

tests/rl/unit_tests/cpu   this PR 843 passed, 6 skipped                            main 824 passed, 6 skipped
tests/unit_tests/cpu      this PR 2074 passed, 7 failed, 5 skipped, 1 error        main 2073 passed, 7 failed, 5 skipped, 1 error
                          (the same 7 failures and 1 error on both, test by test; see Test plan)

test_score_centering.py   loss and grad == the authors' PyTorch reference (a cap that truncates token, top-k and tail
                          ratios; band (0.5, 4)); zero expected gradient under a constant advantage although q != p;
                          == REINFORCE when q == p, including logprobs bitwise equal to a band bound
test_loss.py              vocab-parallel top-k logprobs and grads == full vocab (TP=4, DP2xTP2, strict SPMD typecheck)
test_decoder_loss_kwargs  a [T, k] loss input is CP-sharded like the labels (CP=2, with and without load balancing)
test_batch_invariance     vLLM's logprob patch scores [N, K] ids in one compute_topk_logprobs call; its sampled
                          column == compute_logprobs bitwise

GPU (GB300) at an earlier head, vLLM batch-invariant mode on: -cross_entropy per column vs log_softmax(...).gather at [513, 151936], k=33: max diff 0.0. TestBitwiseParityVarlen (2 GPUs, the CI test) passes.

vs GRPOLoss (the normal cross-entropy path), CPU, T=512, V=8192, k=32:

top-k logprobs vs compute_logprobs at the same ids   eager and compiled: max diff 0.0
saved for backward                                   eager: GRPO 16.0 -> SC 32.2 MiB    "loss" region compiled: 16.0 -> 16.2 MiB

You may ask:

  • Why not on top of PPO-clip (DAPOLoss)? The paper tests score centering only with REINFORCE, truncated IS and masked IS. With a clip, the correction needs per-token clip weights over the whole top-k, an untested combination.
  • Why scatter in to_input_dict, not in the batcher or the loss? Dense [T, k] rows from the batcher would also ship every prompt and padding row. CP and ChunkedLossWrapper split loss inputs along T, so the loss must get [T, k].
  • Why must the batcher know k? An empty DP bin still needs [0, k] rows, so every rank calls the loss with the same arguments.
  • Why does ratio_band replace max_ratio, not a TruncatedIS.Config | MaskedIS.Config pair? Each class would be used once, and either way a user sets one field.
  • Why Verifiers support in this PR? The at-scale runs used Verifiers rollouts. Verifiers drops extra response fields, so the generation server records each generation's top-k, and trace_to_rollout_turns attaches the rows to the node with the same prompt length and completion tokens. A second generation with the same key in one trace gets HTTP 500, since its rows can't be told apart from the first one's.

NOTE:

  • The controller raises at startup for ScoreCenteringLoss without top-k, and for top-k with any other loss. Validation never asks for the top-k.
  • Transport is 8 * k bytes per generated token from vLLM, and per loss token to the trainer (256 B at k=32). The engine raises if vLLM's logprob rows are not [sampled, top-1, ..., top-k].
  • In eager the loss saves one more [T, V_local] fp32 buffer per chunk for backward than GRPOLoss. The "loss" region removes it (TODO in the code: one call for the label and the top-k).
  • max_logprobs now follows num_topk_logprobs; setting it in VLLMEngine.Config.extra_engine_args raises.
  • No CI entry runs ScoreCenteringLoss on GPUs yet. A GPU integration config follows once a recipe uses the loss.
  • A top-k problem ends the run today, with a TODO at each spot: a top-k row count that doesn't match the loss tokens raises out of the batcher's add_group, and an unexpected vLLM logprob layout fails every request on that generator. Neither has been seen.
  • Host RAM at k=128 stopped the run above. A rollout worker keeps each rollout's top-k rows until its group of rollouts ends. The 18 rollout workers on the controller host grew to 320 GiB about 2 steps in: ~4.5 KiB per generated token whose rollout group had not yet reached the controller, against the 1 KiB the rows hold at k=128 (int32 id + float32 logprob per entry). A CPU repro shows glibc keeping the freed rows: with M_MMAP_THRESHOLD at 256 KiB, so large arrays get their own mmap, the worker's memory follows the live rows. That fix is not in this PR (TODO at VerifiersGenerationMetadata.topk_by_generation). k=32 needs a quarter of the rows.
  • Conflicts with other open PRs; the second to land rebases. A draft that lets validation set top_p and top_k edits the same lines of Controller.validate and _parse_sampling_config. The fp8 KV cache drafts and the two CPU KV offload PRs edit the same tests in test_generator.py; the Mooncake one also edits vllm/engine.py.
  • An earlier cut of the same transport and loss trained Qwen3.5-35B-A3B in async multi-turn runs: truncated IS (k=32) and, for 150 steps, ratio_band=(0.2, 5.0) (k=128). Generator and trainer top-k mass agreed to ~5e-5 (0.99941 vs 0.99935 at k=32).

Follow up (each has a TODO in the code)

  • One call for the label and the top-k logprobs, so eager saves no extra [T, V_local] buffer.
  • Drop only the rollout whose top-k rows don't match its loss tokens (Batcher).
  • Fail only the request with an unexpected logprob layout (vllm/engine.py).
  • Let a loss config declare that it takes top-k rows, so the controller's check doesn't import ScoreCenteringLoss.
  • Give freed top-k rows back to the OS in rollout workers (M_MMAP_THRESHOLD; VerifiersGenerationMetadata).

Test plan

pip install -r torchtitan/rl/examples/verifiers/dapo_math/requirements.txt
pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu
pytest tests/rl/unit_tests/gpu -m "not multi_gpu"   # 1 GPU
  • CPU counts above. The 7 failures and the error also happen on main: Inductor can't compile flex_attention on this aarch64 CPU ("torch.compile on current platform is not supported for CPU": test_lora_forward, test_lora_head_only_matches_cross_entropy, 3 test_qwen3_5_mrope_positions tests), and test_quantization.py needs torchao, which this venv lacks.
  • 1 GPU (GB300): pytest tests/rl/unit_tests/gpu tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py tests/unit_tests/gpu/models/common/test_kda_attention.py -m "not multi_gpu": 37 passed, 3 failed, 3 skipped, the same tests as main. The 3 failures are main's: warpdrive GDN/KDA kernels fail to compile with nvidia-cutlass-dsl 4.7.1 (AttributeError: 'tuple' object has no attribute 'atom'). Skips: no dist_moe package, no local Qwen3.5-0.8B weights. test_sglang_bitwise_parity.py is a 2-GPU test, so the SGLangEngine change ran in no test here.
  • pre-commit on the changed files: clean, lychee included. Pyrefly, run from a checkout outside .worktrees/ (it skips dot folders): the same 1 error as main, in a file this PR does not touch.
  • Not run: the 2-GPU alphabet_sort smoke and the 2-GPU tests (this box has 1 GPU).

felipemello1 and others added 3 commits November 2, 2026 22:13
Score centering (arXiv 2609.20807) cancels the bias that a trainer/generator
mismatch adds to the policy gradient. Opt in with
SamplingConfig.num_topk_logprobs=k and ScoreCenteringLoss; k=0 (default)
changes nothing.

- Transport: vLLM logprobs=k (max_logprobs=k) -> Completion / RolloutTurn
  [num_tokens, k] -> TrainingSample and TrainingMicrobatch keep one row per
  loss token -> TrainingMicrobatch.to_input_dict scatters them to [T, k] on
  the trainer's device. Verifiers rollouts: the generation server records each
  generation's top-k, and trace_to_rollout_turns attaches it to the matching
  node by prompt length and completion tokens.
- ScoreCenteringLoss: REINFORCE with an optional truncated ratio
  (max_ratio=2.0) or masked ratio band, plus the score-centering correction
  over the generator's top-k. compute_topk_logprobs gathers the trainer's
  logprobs at the top-k ids without gathering the vocab under TP.
- The controller rejects ScoreCenteringLoss without top-k logprobs, and top-k
  logprobs with any other loss. Validation never requests the top-k.
…ess_inputs, public DAPO helpers

- loss_kwarg_sharding: a loss input with trailing dims (the [T, k] top-k rows) gets the labels'
  token layout plus replicated trailing dims, so SPMD typing and CP accept it. Every model's
  preprocess_inputs uses it; 1-D loss inputs keep their layout.
- compute_topk_logprobs: ValueError without global_vocab_size under TP; batch-invariant mode
  gathers the vocab, so the top-k matches vLLM's bitwise.
- DAPO's MAX_LOG_RATIO and normalize are public; ScoreCenteringLoss imports them.
- The vLLM engine raises if logprob rows are not [sampled, top-1, ..., top-k].
- SamplingConfig rejects num_topk_logprobs < 0; ScoreCenteringLoss rejects max_ratio < 1.
- Verifiers: pop every trace's generation metadata, not only the trainable one's.
- Tests: [T, k] kwarg in the CP=2 loss-kwargs test, top-k in the batch-invariance gather test; four
  tests that re-read config or repeated another test removed.
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 14m 17s —— View job


Request changes: silent Verifiers top-k collisions, loss config shape, and an overlap with #5474. See the review (submitted as a PR review with inline comments).

@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: Request changes -- The loss math and the transport hold up. Three things need another look first: the Verifiers path can silently attach the wrong top-k rows, the loss config uses two fields (plus an unused third mode) for one choice, and the PR conflicts with #5474.

What this PR does. When SamplingConfig.num_topk_logprobs=k > 0, vLLM returns the generator's top-k logprobs for each generated token. The rows travel through Completion -> RolloutTurn -> TrainingSample, one per loss token, and TrainingMicrobatch.to_input_dict scatters them to [T, k] on device. The new ScoreCenteringLoss subtracts the expected score over those k tokens (trainer-modeled tail) from REINFORCE / truncated IS / masked IS. A new vocab-parallel compute_topk_logprobs and a loss_kwarg_sharding helper (all 8 preprocess_inputs callsites updated) let a [T, k] loss input pass through TP, CP and SPMD typing.

Example. One position, k=2, max_ratio=None:

generator q: top-k [0.5, 0.3], tail 0.2      trainer p: same ids [0.4, 0.4], tail 0.2  -> rho = 1
coefficients = q_H - rho * p_H = [0.1, -0.1]
GRPO/DAPO (main): E_q[A * grad log p_y] includes E_q[A] * sum_v q_v grad log p_v, pulling p toward q
this PR:          token_loss adds + A * sum_H detach(coef) * log p_v, cancelling that pull; coef == 0 when p == q
k = 0 (default):  no change on any path except two null keys in `log_logprobs` dumps

I checked that the loss expands the tail model correctly (q_v = rho * p_v, sum_V p grad log p = 0), and that masked_scatter_ keeps rows aligned across multi-turn samples, padding and empty bins.

Must fix

  1. PR description -- "Summary (human-written)" is empty. The author needs to fill it in; agents don't.
  2. torchtitan/rl/examples/verifiers/generation_server.py:256 -- a key collision silently attaches another generation's top-k rows. Raise on collision (inline).
  3. torchtitan/rl/trainer/losses/score_centering.py:66 -- max_ratio and ratio_band are two fields for one choice, and the w=1 mode has no consumer and an unbounded alpha = rho (inline).
  4. torchtitan/rl/trainer/batcher.py:282 (and actors/monarch/batcher.py:35) -- num_topk_logprobs: int = 0 duplicates the config default. Make it required (inline).

Should consider

  • Overlap with #5474, which moves _normalize / _MAX_LOG_RATIO into losses/common.py, adds shared policy_metrics, and makes losses take **loss_inputs. That would remove the copied metric block in score_centering.py:232-249, the public renames in dapo.py, and the "other losses need k=0" half of the check in controller.py:393-404. Agree on a landing order instead of making these helpers public here.
  • torchtitan/components/loss.py:566 -- the vocab-parallel top-k path is missing the local-vocab-size check (inline).
  • torchtitan/rl/generator/vllm/batch_invariance.py:45 -- the per-column loop could call compute_topk_logprobs (inline).
  • torchtitan/rl/trainer/losses/score_centering.py:251 -- "head" vs "topk" naming in the metric keys (inline).
  • No recipe or integration config uses ScoreCenteringLoss, so the TP top-k all-reduces, CP [T, k] sharding and real-vLLM row parsing run only in CPU unit tests. When a recipe lands, turn the loss on in an existing RL integration entry (ideally TP>1) rather than adding a new entry.
  • tests/rl/unit_tests/cpu/test_rdma_microbatch.py -- the RDMA round trip already covers every dataclass field generically, so the new fixture fields guard nothing new. Drop them.

Questions

  • Should the Verifiers support land separately once trace tokens are confirmed to equal the request tokens (so the key can include the prompt)? It changes behavior for every Verifiers run, even at k=0 (it now pops every trace's metadata), and it touches _parse_sampling_config, which #5454 also rewrites.
Details
  • Numerics with k=0: the dapo.py changes are pure renames. loss_kwarg_sharding returns the labels' layout for 1-D kwargs, so DAPO and GRPO are unchanged.
  • Sampled token in the top-k: its token weight uses the softplus-CE logprob, while its head coefficient and band test use z - lse. The two can disagree right at a band edge. This is minor; the TODO at L151 covers why the calls stay separate.
  • Batch-invariant TP: the vocab is gathered twice (label path and top-k path). This is acknowledged in the same TODO.
  • Callsite audit: llama3, qwen3, gpt_oss and deepseek_v4 inherit Decoder.preprocess_inputs. Flux rejects loss kwargs.

Not verified: vLLM's [sampled, top-1..top-k] flat layout with processed_logprobs (the engine checks the sampled column but not the row width), and every GPU/TP path. A maintainer still needs to review, since the PR touches components/loss.py and models/common/.

Comment thread torchtitan/rl/trainer/batcher.py Resolved
Comment thread torchtitan/components/loss.py Resolved
…d vocab-shard check

- ScoreCenteringLoss: the w=1 mode is gone. max_ratio is a float (default 2.0, the paper's TIS
  cap), and a set ratio_band replaces it. Metric keys and locals say topk, not head.
- Verifiers generation server: a second generation in a session with the same (prompt length,
  completion) gets HTTP 500, since its top-k rows can't be told apart from the first one's.
- Batcher and its actor: num_topk_logprobs is required.
- _local_vocab_shard: the shard bounds, the local-size check and the empty-shard check, shared by
  _LossParallelCrossEntropy and _VocabParallelTopKLogprobs. Top-k ids are range-checked.
- vLLM batch-invariant logprob patch: one compute_topk_logprobs call instead of a compute_logprobs
  loop per column. Its sampled column equals compute_logprobs bitwise.
- test_vocab_parallel_topk_logprobs_parity: CPU generator, then move to the test device.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Pushed 938d255 for the review.

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 37s —— View job


Approve (please fill in the human-written Summary before merging). 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. 938d255 resolves the earlier must-fix items, and the new commit introduces no new problems.

What changed since the last review. ScoreCenteringLoss has one weighting choice: max_ratio: float = 2.0, which a set ratio_band replaces, and the unbounded w=1 mode is gone. The Verifiers server rejects colliding top-k keys. num_topk_logprobs is now required in both batchers. The vocab-shard bounds and checks live in a shared _local_vocab_shard. vLLM's batch-invariant logprob patch makes a single compute_topk_logprobs call.

Example (new docstring, verified by hand). max_ratio=2, q_topk=[0.1, 0.7], p_topk=[0.5, 0.3], both tails 0.2. That gives rho = alpha = 1, q * w = [0.2, 0.3] and coefficients [-0.3, 0.0]. Truncation removes 0.3 of exact IS's weight on token 0, and the correction adds it back. The coefficients are 0 when no top-k or tail ratio is truncated.

Earlier must-fix items

  • Summary (human-written): still open. The author has to write it.
  • generation_server.py:258 key collision: resolved. It now returns HTTP 500 before the metadata is written, and at k=0 nothing changes.
  • score_centering.py config shape: resolved. There is one active field and no cross-field check. The 2.0 default and the (0.5, 5.0) band now cite App. A.3.
  • batcher.py / actors/monarch/batcher.py default k: resolved.

Earlier should-consider items

  • loss.py top-k shard check: resolved through _local_vocab_shard, plus an _assert_async range check on the ids.
  • batch_invariance.py per-column loop: resolved. The generator now runs the same function as the trainer's top-k path, and the CPU test checks column 0 against compute_logprobs with torch.equal.
  • "head" -> "topk" metric keys and locals: resolved.
  • #5474 landing order, the RDMA fixture fields (.nbytes on every field), keeping Verifiers in this PR, and the integration-config follow-up: I accept the author's answers.

Must fix

  1. PR description: fill in "Summary (human-written)".
Details
  • Under a constant advantage, the drift cancellation still holds for both modes: sum_V q w(r) grad log p - [sum_H q w - alpha p] grad log p = alpha * sum_V p grad log p = 0, using the tail model q_v = rho * p_v.
  • A colliding generation's vLLM work is discarded, and Verifiers is expected to retry the 5xx. A generation that collides deterministically (a lone EOS at a confident position) fails the rollout loudly, which is the intended trade-off until the key includes the prompt.
  • The generator process never binds the "loss" local-compile region, so the patched vLLM path runs compute_topk_logprobs eagerly. Its batch_invariant=False therefore can't raise there.
  • With ratio_band set, the docstring says max_ratio is unused, which matches the suggestion in the earlier review.

Not verified: GPU bitwise parity of log_softmax + gather vs -cross_entropy under vLLM batch-invariant mode (the author reports max diff 0.0 on GB300), and that Verifiers retries 5xx. A maintainer still needs to review, since the PR touches components/loss.py and models/common/.

…tring

- ScoreCenteringLoss's docstring starts with a picture: the trainer's probabilities after one step
  under plain REINFORCE, truncated IS, masked IS and this loss.
- Then the loss as code, with the variable names of __call__, numbers for both weight modes and for
  a capped tail, and why the drift cancels, with the paper's equation numbers.
- The field docstrings and the inline comments use the same names. No code change.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Pushed b57373d, docstring and comments only (no code change):

  • ScoreCenteringLoss now shows the drift first: the trainer's probabilities after one step under plain REINFORCE, truncated IS, masked IS and this loss.
  • Then the loss as code with __call__'s variable names, numbers for both weight modes and for a capped tail, and why the drift cancels (paper Eq. 3, 5, 7, 10, 12), including that the tail model is an assumption.
  • The max_ratio / ratio_band docstrings and the inline comments use the same names.

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 24s —— View job


Approve (please fill in the human-written Summary before merging). 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. b57373d only changes docstrings and comments in score_centering.py, and I checked its numbers and derivation by hand. The one open item is still the human-written Summary.

What changed since the last review. The ScoreCenteringLoss docstring now opens with a one-step picture (3-token vocab, advantage 1, one SGD step on the logits with lr = 1). It then writes the loss with __call__'s variable names, works the coefficients for the cap, the band and a capped tail, and derives why the drift cancels under the tail model. The field docstrings and inline comments use the same names. No executable line changed.

Example (the docstring's picture, recomputed). q = [0.2, 0.7, 0.1], p = [0.6, 0.3, 0.1]. The logit step is sum_y q_y w_y (e_y - p):

plain REINFORCE   delta = [-0.40, 0.40, 0.00]  -> p = [0.42, 0.47, 0.11]
max_ratio=2       q*w = [0.4, 0.3, 0.1]        -> delta [-0.08, 0.06, 0.02] -> [0.57, 0.33, 0.10]
ratio_band=(.5,5) q*w = [0.6, 0.0, 0.1]        -> delta [0.18, -0.21, 0.03] -> [0.67, 0.23, 0.10]
correction        -(c - p*sum c): cap c=[-0.2, 0] -> [0.08, -0.06, -0.02]; band c=[0, -0.3] -> [-0.18, 0.21, -0.03]

Each correction cancels its mode's delta exactly, so "this loss" leaves p at [0.60, 0.30, 0.10] as drawn.

Must fix

  1. PR description: "Summary (human-written)" is still the template placeholder. The author has to write it.
Details
  • Capped-tail example: rho = 0.02 / 0.2 = 0.1, alpha = min(1, 2 * 0.1) = 0.2, top-k ratios 1.67 and 0.44 are below the cap, so c = [0.5, 0.3] - 0.2 * [0.5, 0.3] = [0.4, 0.24]. IS alone moves the logits by [0.08, 0.048] on the top-k and by -0.128 on the aggregate tail. The correction moves them by [-0.08, -0.048] and +0.128. This matches "IS alone lowers the tail's logit" and "lowering [the top-k] raises the tail".
  • Derivation: under the tail model q_v = rho * p_v, the tail terms are alpha * p_v * score_v. Since sum_V p score = 0, E_q[w * score] = sum_topk c_v * score_v = grad(correction). With c constant in y, E_q[A * (w * score_y - grad correction)] = Cov_q(A, w * score_y). This matches the docstring.
  • logit_correction_l1 comment: when the masked tail's alpha flips to 0 with top-k mass m -> 1, c is about p_topk, and both the top-k term p(1 - m) and the tail term (1 - m) * m go to 0, as the comment says.
  • The bit_wise/logprob_diff/mean comment (unclamped masked_log_ratio; k1 estimate of -KL(generator || trainer)) matches the code.
  • No non-ASCII characters in the file.

Not verified: the paper's equation and appendix numbers (Eq. 3, 5, 7, 10, 12; App. A.3, A.4). A maintainer still needs to review, since the PR touches components/loss.py and models/common/.

- After the picture, the docstring follows one sampled token from start to end: ratio,
  token_weight, topk_ratio, weighted_generator_topk_probs, rho, alpha, coefficients,
  correction and token_loss. Each step has a short reason, the code line and its value.
- Masked IS shows only the lines that change. A capped-tail case shows what alpha does.
- The derivation keeps the paper's equation numbers. No code change.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Pushed d7f79dd, docstring only (no code change). After the picture, the ScoreCenteringLoss docstring now follows one sampled token from start to end. Each step has a short reason, the code line and its value. Masked IS shows only the lines that change, and a capped-tail case shows what alpha does.

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 4s —— View job


Approve (please fill in the human-written Summary before merging). 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. d7f79dd changes only the ScoreCenteringLoss docstring. I recomputed every number in the new walkthrough and each one matches the code. The only open item is still the human-written Summary.

What changed since the last review. After the picture, the docstring now follows one sampled token through the loss. Each step shows the code variable, its formula and its value. The masked-IS case shows only the lines that change. The capped-tail case shows what alpha does. The derivation is now shorter and keeps the paper's equation numbers. No executable line changed, and no other file changed.

Example (the walkthrough, recomputed). q = [0.2, 0.7, 0.1], p = [0.6, 0.3, 0.1], token 0 sampled, A = 1:

max_ratio=2       ratio 3 -> token_weight 2; q*w = [0.4, 0.3]; rho = alpha = 1; c = [-0.2, 0.0]
                  grad(correction) on logits = c - p*sum(c) = [-0.08, 0.06, 0.02] == truncated-IS step
                  correction = -0.2*log 0.6 = 0.102; token_loss = -(2*log 0.6 - 0.102) = 1.124
ratio_band=(.5,5) token_weight 3; q*w = [0.6, 0.0]; c = [0.0, -0.3]
                  correction = -0.3*log 0.3 = 0.361; token_loss = -(3*log 0.6 - 0.361) = 1.894
capped tail       p_topk = [0.5, 0.3], q_topk = [0.3, 0.68]; min(p, 2q) = p; rho = 0.1, alpha = 0.2
                  c = [0.4, 0.24]; IS step [0.08, 0.048, -0.128] is cancelled by -grad(correction)

The docstring rounds to 0.10 / 1.12 / 0.36 / 1.89. The variable names (topk_ratio, trainer_topk_mass, weighted_generator_topk_probs, alpha) match __call__ and its inline comments (L225-257).

Must fix

  1. PR description: "Summary (human-written)" is still the template placeholder. The author has to write it.
Details
  • Tail statement (L63-65): with q_v = rho * p_v outside the top-k, each tail ratio is 1 / rho, so q_v * weight(1 / rho) = rho * min(1 / rho, C) * p_v = alpha * p_v. This matches the docstring and alpha = min(1, max_ratio * rho) in the code.
  • Masked case: token_weight = where(in_band, ratio, 0) gives 3 for ratio 3 in (0.5, 5), and the top-k ratio 3/7 < 0.5 is masked, which matches L88-89.
  • "That alone would move nothing" (exact IS): sum_v q_v (p_v / q_v) score_v = sum_v p_v score_v = 0.
  • The file is still ASCII only.

Not verified: the paper's equation and appendix numbers (Eq. 3, 5, 7, 10, 12; App. A.3). A maintainer still needs to review, since the PR touches components/loss.py and models/common/.

- One table maps each __call__ step to its value for truncated IS and masked IS, replacing the
  step-by-step prose and the separate masked-IS section (class docstring 943 -> 628 words).
- ratio_band and max_ratio field docstrings are 2 lines each. No code change.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Pushed d5178ef, docstring only (no code change). One table now maps each __call__ step to its value for truncated IS and masked IS, replacing the step-by-step prose. The class docstring goes from 943 to about 630 words, and ratio_band / max_ratio are 2 lines each.

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 56s —— View job


Approve (please fill in the human-written Summary before merging). 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. d5178ef changes only the ScoreCenteringLoss docstring. Every value in the new table matches the code, so the only open item is still the human-written Summary.

What changed since the last review. The step-by-step walkthrough and the separate masked-IS section are now one table. It has a row per __call__ step and a column each for truncated IS (max_ratio=2) and masked IS (ratio_band=(0.5, 5)). The capped-tail example and the derivation are shorter. The max_ratio and ratio_band field docstrings are 2 lines each. No executable line changed.

Example (the table, recomputed). q = [0.2, 0.7, 0.1], p = [0.6, 0.3, 0.1], token 0 sampled, A = 1:

                               truncated IS            masked IS
ratio / token_weight           3 / 2                   3 / 3
weighted_generator_topk_probs  [0.2*2, 0.7*3/7]=[0.4,0.3]  [0.2*3, 0]=[0.6,0.0]
rho / alpha                    1 / 1                   1 / 1
coefficients                   [-0.2, 0.0]             [0.0, -0.3]
correction                     -0.2*log 0.6 = 0.102    -0.3*log 0.3 = 0.361
token_loss                     -(2*log 0.6 - 0.102) = 1.124   -(3*log 0.6 - 0.361) = 1.894

The table rounds these to 0.10 / 0.36 / 1.12 / 1.89. In the capped-tail case the tail ratio is 0.2 / 0.02 = 10, rho = 0.1 and alpha = 0.2, which gives c = [0.4, 0.24], unchanged from the version I checked last time.

Must fix

  1. PR description: "Summary (human-written)" is still the template placeholder. The author has to write it.
Details
  • "alpha < 1 only when the tail's weight is capped or masked" holds for both modes. Truncated IS gives alpha = min(1, max_ratio * rho), which is below 1 exactly when the tail ratio 1 / rho is above the cap (L224). Masked IS gives alpha in {0, 1}, and alpha is 0 only when the tail ratio is outside the band (L213).
  • The table uses topk_ratio, which is not a local variable: the code computes topk_log_ratio (L205). The inline comments at L203 and L218 use the same name, so the docstring and the code still read consistently.
  • The ratio_band docstring no longer contrasts it with DAPOLoss.ratio_clip_*, but it still says "absolute bounds", which is enough.
  • The file is still ASCII only.

Not verified: the paper's equation and appendix numbers (Eq. 3, 5, 7, 10, 12; App. A.3). A maintainer still needs to review, since the PR touches components/loss.py and models/common/.

Conflicts resolved with main's code plus this PR's change:
- loss_kwarg_sharding: main moved DeepSeek-V3's MTPDecoder to
  models/common/mtp.py, so the change goes there; deepseek_v3/mtp.py
  keeps main's text. Model imports keep both sides.
- Controller: validation keeps main's temperature and asks for
  num_topk_logprobs=0.
- Verifiers: main already pops every trace's generation metadata, so the
  PR's pop is gone; its TODO on unpopped sessions joins main's
  retried-attempt TODO. num_topk_logprobs goes to the generation server
  like the other sampling fields. The server reads it with a default of 0
  (main dropped the `defaults` local the PR read).
- Batcher and sample builder: top-k fields next to main's vision fields.
- Tests: main's names (force_trainer_logprobs_for_batch_invariance,
  VerifiersRolloutWorker.trace_to_rollout_turns, OutstandingGeneration
  without metrics_prefix); num_topk_logprobs=0 in main's newer Batcher
  builds; the PR's batcher test turns off RDMA microbatches; main's
  deleted whole-rows test stays deleted.
The k3 estimate of KL(generator || trainer) over loss tokens, from the
same clamped log ratio as the loss: the mean of exp(r) - 1 - r. Unlike
bit_wise/logprob_diff/mean, mismatches of opposite sign don't cancel.
The Generator passes num_topk_logprobs to every engine, but SGLangEngine
lacked the argument, so every SGLang recipe failed at generator init with
a TypeError. It now accepts it and raises ValueError for a value > 0: it
returns no top-k logprobs. The GPU test that builds an SGLang engine
directly passes num_topk_logprobs=0, as the CPU tests do.
…emperature, top_p and max_tokens are

It defaulted to 0. A request that lost the key then returned no top-k rows,
and with ScoreCenteringLoss the batcher raised far from the cause. The
rollouter always sends it (Verifiers keeps 0: sampling.model_dump(exclude_none=True)),
so a missing key is now a 422 that names it. Test bodies send the key; the
required-fields test covers it.
…nd on the controller's loss check

- batcher.py: a top-k row count that doesn't match the loss tokens raises out
  of add_group and ends the run; the TODO says to drop only that rollout.
- vllm/engine.py: an unexpected logprob layout raises inside the engine step
  and fails every request on that generator; the TODO says to fail only that
  request.
- controller.py: the top-k check imports ScoreCenteringLoss; the TODO says to
  let a loss config declare that it takes top-k rows.
…ver; controller TODO wording

- generation_server.py: glibc keeps freed top-k arrays, so at k=128 a rollout
  worker held ~4.5 KiB per in-flight token, 1 KiB of which is rows. The TODO
  names the fix a CPU repro supports (M_MMAP_THRESHOLD in rollout workers).
- controller.py: the top-k check's TODO says "Not done yet".
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 26s —— View job


Approve (please fill in the human-written Summary before merging). 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. I reviewed every file again at 432a3e7, including the commits since my last review (mismatch_kl metric, SGLang raise, required num_topk_logprobs in the Verifiers server, the TODOs, two merges of main). They add no correctness problems. The only must-fix is still the human-written Summary.

What this PR does. With SamplingConfig.num_topk_logprobs=k > 0, vLLM returns its top-k logprobs for each generated token. They travel Completion -> RolloutTurn -> TrainingSample as one row per loss token, and TrainingMicrobatch.to_input_dict scatters them to [T, k] on device. ScoreCenteringLoss (truncated or masked IS) subtracts the expected score over those k tokens, with the trainer modeling the tail, which cancels the drift that a generator/trainer mismatch adds to the gradient. compute_topk_logprobs and loss_kwarg_sharding carry [T, k] through TP, CP and SPMD typing. At k=0 nothing changes, except two null keys in log_logprobs dumps.

Example. A two-turn rollout, k=2:

turn 0: prompt [1, 2], completion [4, 5]  rows [[4, 9], [5, 8]]
turn 1: prompt [.., 9], completion [7]    rows [[7, 3]]
TrainingSample: tokens [1,2,4,5,9,7]  loss_mask [F,F,T,T,F,T]  rows [[4,9],[5,8],[7,3]]
microbatch (shifted): [[4,9],[5,8],[0,0],[7,3], 0 rows for padding]  -> ScoreCenteringLoss
A sample whose row count != loss_mask[1:].sum() -> ValueError in _pack_training_samples

Must fix

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

Should consider

  • torchtitan/rl/trainer/losses/score_centering.py:258 -- loss/mismatch_kl/mean measures the mismatch, not the loss, and only this loss logs it (inline).
  • torchtitan/rl/examples/verifiers/generation_server.py:301 -- the handler's error table doesn't list the new 500 (inline).
Details
  • Callsite audit after the merges: every preprocess_inputs that adds loss kwargs uses loss_kwarg_sharding. That is decoder, mtp, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5 and the transformers backend. deepseek_v4 and qwen3_8_flash_next call super(). No dict.fromkeys(loss_kwargs, ...) remains.
  • Row alignment: the default rollouter and Verifiers are the only places that build a RolloutTurn. rollout_to_training_samples sets loss_mask True for every completion token and appends that turn's rows, so the rows match loss_mask[1:]. A sample with no valid loss token is dropped (_has_valid_loss_token) before packing, so the [0, k] seed never meets a None row array.
  • _finished_request: a zero-token completion has no rows, as does a request with k=0 (validation), so len(token_logprobs) > num_tokens holds only for top-k requests.
  • mismatch_kl uses the clamped log_ratio (|r| <= 10) and is 0 off the mask, since expm1(0) - 0 = 0.
  • SGLang's k>0 check is in the engine constructor, like its vision and SP checks next to it.
  • Overlap: #6302 (draft, a stack that restructures batcher.py / training_sample_builder.py) already plans for score centering at k=32, so whichever PR lands second rebases. #6106 (your own draft) also edits the generation server's session metadata.
  • Host RAM at k=128 (the run stopped in step 3) has a TODO at VerifiersGenerationMetadata.topk_by_generation, and its fix is unverified in a run. That is fine for an opt-in feature, but recipes should start at k=32 until it is fixed.

Not verified: GPU paths (TP top-k all-reduces, vLLM's flat logprob layout, batch-invariant bitwise parity), which I can't run here. A maintainer still needs to review, since the PR touches components/loss.py and models/common/.

Comment on lines +256 to +261
# Mean of exp(r) - 1 - r over the same tokens, r = log_ratio: the k3 estimate of
# KL(generator || trainer). Never negative: mismatches of opposite sign don't cancel.
"loss/mismatch_kl/mean": normalize(
(torch.expm1(log_ratio) - log_ratio).float().sum(),
global_loss_token_counts,
),

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 metric measures the trainer/generator mismatch, not the loss. Its sibling, bit_wise/logprob_diff/mean, sits under bit_wise/, two lines up. It also doesn't depend on the loss: DAPOLoss and GRPOLoss compute the same log_ratio, but only this loss logs it. So the k=0 GRPO arm of a comparison (like the smoke in the description) has no mismatch_kl curve to set beside this one.

Metric keys are hard to rename once dashboards use them. Consider bit_wise/mismatch_kl/mean, and either log it from DAPO too or leave that to the shared policy_metrics in #5474.

Comment on lines +294 to +301
key = (len(prompt_token_ids), tuple(completion.token_ids))
if key in topk_by_generation:
return web.json_response(
{
"error": f"session {session_id}: two generations share prompt length "
f"{key[0]} and completion tokens, so their top-k rows can't be told apart"
},
status=500,

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 error table in this handler's docstring (L194) still says 500 means "generate_fn raised, or the completion's token ids and logprobs differ in length". Add the top-k key collision there, so whoever reads a Verifiers 500 can find this cause. The same table's 422 line also covers a request without num_topk_logprobs now, which "a malformed body" already describes.

@tianyu-l

Copy link
Copy Markdown
Contributor

closing in favor of #6376; adding you as co-author

@tianyu-l tianyu-l closed this Nov 25, 2026
tianyu-l added a commit that referenced this pull request Nov 25, 2026
## 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
The trainer scores each token under `softmax(logits / T)`, the
distribution the generator sampled from, and `DAPOLoss`/`GRPOLoss` use
the generator's logprob as the old policy: the importance ratio is `p /
q`. SGLang's `SGLANG_RETURN_ORIGINAL_LOGPROB=1` (documented by other RL
frameworks for their own needs) makes SGLang's sampler return
`log_softmax(logits)`, before temperature. Nothing in torchtitan checks
it, so with the variable set every SGLang-generated ratio is silently
wrong whenever `T != 1`.

**Example.** `SGLangEngine`, `SamplingConfig(temperature=0.8)`, a token
with logits `[2.0, 1.0, 0.0]`, sampled token 0:

```
q the trainer expects     = softmax([2, 1, 0] / 0.8)[0] = 0.73
q SGLang returns (env=1)  = softmax([2, 1, 0])[0]       = 0.67
main:     ratio p/q is off by 10% on this token; every token is off, no error
this PR:  ValueError at SGLangEngine init: unset SGLANG_RETURN_ORIGINAL_LOGPROB
```

## What changed
- `SGLangEngine.__init__` raises `ValueError` if
`SGLANG_RETURN_ORIGINAL_LOGPROB` is set. It reads
`sglang.srt.layers.sampler.SGLANG_RETURN_ORIGINAL_LOGPROB`, the module
constant SGLang's sampler itself branches on, so the check can't
disagree with SGLang's parsing of the variable.

## Alternatives considered
- Recompute the returned logprobs from `logits / T` (as the
batch-invariant `TrainerLogprobsSampler` does): extra work on every
decode step to support a setting nobody needs.
- Check at config time: the variable is read in the generator processes,
which may have a different environment than the controller.

## Testing
- No new test: the check reads SGLang's own constant, so a test would
only re-read an environment variable. Verified the import resolves
against the SGLang commit the README pins (`.venv-sglang`).
- `pytest tests/rl/unit_tests/cpu`: 741 passed, 7 skipped (GB300, CPU
only).

## Known issues / follow-ups
First PR of the score centering stack (arXiv 2609.20807, takes over
#5760): score centering also reads SGLang's top-k logprobs, which this
variable would turn pre-temperature too. Training with temperature <= 0
is handled separately by #6356.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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