Skip to content

feat(loss): add score centering with sampler top-k capture - #4818

Merged
terrykong merged 26 commits into
NVIDIA-NeMo:mainfrom
guyueh1:codex/score-centering
Nov 1, 2026
Merged

terrykong merged 26 commits into
NVIDIA-NeMo:mainfrom
guyueh1:codex/score-centering

Conversation

@guyueh1

@guyueh1 guyueh1 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Adds optional score centering to the clipped PPO/GRPO policy-gradient loss. The sampler head retains its original probability mass; the unobserved tail is modeled as a rescaled current-policy distribution. The feature is off by default.

The shared utility adds the correction to the existing clipped objective. Original capture/loss commits fd46816 and 3e63b6d retain Tugrul Konuk's authorship. Broader IS handling, packed gathering, and probability validation are adapted from Oleg Rybakov's implementation.

Behavior and configuration

  • Supports IS off, untruncated token-level IS, TIS, and ICEPOP. Untruncated IS gives a zero correction; ICEPOP rejection of the sampled token leaves the candidate correction active.
  • Neutralizes masked logprobs and advantages, detaches sampler inputs and centering coefficients, and preserves PPO clipping.
  • Supports ordinary gathering and internal Megatron packing with sequence_packing.fuse_loss=true. Packs candidate IDs together, performs full-vocabulary normalized gathering under TP, and reconstructs padded sequences under CP.
  • Validates candidate IDs, count, finite/representable logprobs, duplicates, and probability mass. Preserves finite logprobs without flooring or renormalization.
  • Enables collection with loss_fn.score_centering=true, token_capture.enabled=true, and policy.generation.top_logprobs=K. Setup automatically raises vLLM's max_logprobs cap and preserves explicit -1. The old token_capture.top_logprobs setting has moved to generation configuration.
  • Rejects unsupported trainer layouts at startup: Automodel TP/CP > 1 and Megatron fused linear logprobs. Supports both token- and sequence-normalized losses with token-level importance ratios.

Request and transport

Gym explicitly sends logprobs=true, top_logprobs=K; normal vLLM request resolution supplies SamplingParams. Standalone request, validation, and extraction functions provide an extension interface returning CPU sampler IDs and logprobs.

Engine output → CPU int32 IDs/float32 logprobs → per-call staging → CPU finalizer → canonical rollout columns → policy leader fetch/broadcast → differentiable trainer logprobs at sampler IDs → loss.

Tokens, media, and sampler tensors share a staging write. Failures return capture_failed with best-effort partial-row cleanup. Captured top-k fields are stripped before HTTP serialization. Uncaptured calls to the policy server also request K and return their top-k values over HTTP. Top-k extraction runs in a worker thread to avoid blocking the serving event loop.

Pins merged Gym #4930 at d8f4db463ef04a40b8a1db7088f69247dcbcebb7. No unmerged Gym dependency remains.

Documentation and tests

See docs/guides/score-centering.md for mathematics, configuration, transport, extension points, limits, and costs.

  • The two-GPU Qwen3-0.6B SingleController smoke runs three steps for each IS mode, with fused packing for TIS/ICEPOP. It checks finite loss/gradients/head mass, valid tokens, finalizer activity, and capture health. It is registered in both fast and full SC3 functional plans.
  • The distributed L1 entrypoint covers packed/unpacked TP=2/CP=2 backward with four visible GPUs. CPU Gloo tests additionally cover TP=2/CP=1, TP=1/CP=2, and TP=2/CP=2.
  • Regression tests cover text-only calls during media capture, configuration rejection, both loss normalizations, and full setup wiring to partitions, workers, Gym, and finalizers.

Validation

Previous head f0d9860 passed CI run 40089875747, attempt 2, including H100 and GB200 score-centering functional smokes for all four IS modes. The unit distributed jobs passed their two-GPU cases; the four-GPU cases were skipped there.

For the review fixes and merged Gym pin:

  • 43 focused CPU pytest cases pass with heavyweight imports isolated; additional constant-advantage gradient checks pass for all four IS modes and both loss normalizations.
  • Real spawned CPU Gloo value/gradient checks pass for TP/CP = 2/1, 1/2, and 2/2.
  • Capture/staging checks pass against the real merged Gym lifecycle, including the text-only media-capture regression and failure propagation.
  • 34 source-isolated validator cases and 12 actual setup-cap cases pass, including K=128 and unlimited cap.
  • The actual serving mixin dispatches top-k extraction off the event-loop thread.
  • Lockfile check resolves 574 packages against merged Gym; formatting, linting, config minimization, and diff checks pass. Full project typechecking and GPU/Ray integration are delegated to CI.
  • OPD loss classes and teacher/student top-k helpers are unchanged.

Remaining limits and evidence

SingleController + Gym + vLLM token capture is required. Sequence-level IS, seq-mask-tis, Automodel distributed logits, externally prepacked inputs, full-vocabulary OPD, and fused linear logprobs remain unsupported. Sampling must be unfiltered with positive finite temperature; non-unit temperatures require processed logprobs. Raw/default logprobs are accepted at temperature 1 and assume no other processor changes the distribution. Logits-return modes and explicit logprob_token_ids are rejected.

K scales CPU work, storage, transport, broadcast, and trainer communication linearly. Sampler arrays alone cost 8*T*K bytes before copies/padding/trainer outputs.

Still outstanding: real K=0/32/128 step-time, throughput, peak-memory and long-output latency comparisons, convergence A/B for the four IS modes with nontrivial importance ratios, and the GPU four-rank TP=2/CP=2 backward run. The smoke establishes integration and finiteness, not convergence or large-K performance.

@guyueh1 guyueh1 added the CI:L2 Run doctests, unit tests, functional tests, and convergence tests label Oct 20, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 20, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: a9ea725 (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 22, 2026
@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: e4de1cc (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@guyueh1
guyueh1 marked this pull request as ready for review October 22, 2026 17:27
@guyueh1

guyueh1 commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Comparison with ertkonuk / Tugrul Konuk's original two commits: fd4681687 — sampler top-k capture and 3e63b6d — score-centering loss. The current PR revision is f52f93fb7.

The original commits already provide the SingleController/V2 token-capture path, CPU/data-plane transport, ordinary TP/CP trainer gathering, and an additive score-centering correction. This PR retains those foundations and extends them:

Area Original two commits Current PR
Loss objective and organization Adds the correction to the existing clipped policy-gradient loss; estimator lives in the loss implementation. Preserves that clipped PPO/GRPO objective and extracts compute_score_centering_term as a shared utility. The correction remains additive; the actor objective is preserved.
Importance sampling with score centering IS off and token-level TIS only. IS off, untruncated token-level IS, TIS, and ICEPOP, adapting Oleg's broader head/tail weighting. Untruncated IS gives a zero correction. An ICEPOP rejection of the sampled token does not suppress the correction over other candidates.
Packed loss preparation Top-k gathering is added only to ordinary prepare_loss_input. With sequence_packing.fuse_loss=true, packed preparation omits trainer top-k logprobs and the loss assertion fails. Adds gathering to prepare_packed_loss_input: shifts/packs candidate IDs per sequence, gathers full-vocabulary normalized logprobs under TP, and reconstructs each padded sequence under CP. Internal fused packing is supported; externally prepacked inputs are explicitly rejected. Adapted from Oleg's packed gather.
HTTP request versus engine request Captured HTTP requests advertise top_logprobs=0; a custom to_sampling_params override raises the engine's logprobs count to K. HTTP explicitly advertises logprobs=true, top_logprobs=K. Normal vLLM parameter resolution supplies the engine count; the custom override is removed. The worker validates consistency. Arrays are still staged and stripped before HTTP serialization. Requires companion Gym #4930.
Sampler extension interface Top-k-specific request manipulation and extraction are embedded in serving/response code. Standalone build_score_centering_request_overrides, validate_score_centering_request, and extract_score_centering_samples isolate collection behavior. Extraction returns CPU (sampler_ids, sampler_logprobs) tensors with stable shape/dtypes. Top-k is still the only implemented strategy.
Probability validation Checks candidate count and floors very negative sampler logprobs to -9999. Adapts Oleg's stricter checks: row/candidate counts, valid int32-compatible IDs, finite float32-representable logprobs, positive-logprob tolerance, unique selected IDs, and head-mass tolerance. Finite sampler logprobs are preserved without flooring or renormalization.
Masked-position safety Correction exponentiation occurs before the final masked reduction. Neutralizes masked logprobs/advantages before exponentiation and reduction, preventing ignored NaN/Inf values from contaminating the loss and gradients. Sampler inputs, centering coefficients, and advantages are detached.
Score-centering tensor names generation_topk_ids, generation_topk_logprobs, and trainer input next_token_topk_logprobs. sampler_topk_token_ids, sampler_topk_logprobs, and policy_logprobs_at_sampler_topk distinguish sampler data from current-policy values. Existing OPD teacher/student names and helpers remain unchanged.
Documentation and tests Unit coverage for capture/staging, drift cancellation, and ordinary trainer gathering. Adds a user guide, broader gradient/masking/probability tests, and packed preparation/TP/CP tests. Adds an L1 functional smoke adapted from the existing token-capture test: three steps each for off/untruncated IS/TIS/ICEPOP, with fused packing for TIS and ICEPOP.

Validation at this revision: 34 focused CPU cases pass with heavyweight runtime imports isolated; real two-process Gloo checks pass for packed TP values/gradients and CP forward reconstruction, including actual packed-loss preparation. Functional-launch configurations and metric checks are validated, but the GPU smoke, CP backward, full Ray/vLLM integration, and convergence have not run locally. Full typechecking remains blocked by the uninitialized Automodel submodule.

Remaining limits: sequence-level IS / seq-mask-tis, externally prepacked inputs, Automodel CP sharder / DTensor logits, full-vocabulary OPD, and fused linear logprobs remain unsupported with score centering. The rollout integration still requires vLLM token capture. Data-plane storage/transport still grow linearly with K; large-K performance has not been benchmarked.

@guyueh1 guyueh1 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the thorough work and validation notes on this feature. Highlights:

  • Please rebase: the PR is currently CONFLICTING with main.
  • Merge order: the Gym pin depends on draft Gym#4930 (see inline comment).
  • Test collection: test_score_centering.py under tests/unit/models/generation/ is not collected by any L0 shard.
  • Positives: the sampler adapter is a clean seam shared by Gym/vLLM/the worker, compute_score_centering_term is a pure, well-tested function, column plumbing follows the OPD/routed-experts pattern, and config validation is centralized. The estimator math (head + modeled tail, TIS/ICEPOP handling, sign, position alignment) checked out by hand; nothing was run (no GPU).
  • Lint: ruff/ruff-format/taplo pass; pyrefly was not verified on this host.

Generated by Claude Code

Comment thread 3rdparty/Gym-workspace/Gym Resolved
Comment thread nemo_rl/algorithms/loss/loss_input.py Resolved
Comment thread nemo_rl/algorithms/loss/loss_input.py Resolved
Comment thread pyrefly.toml Resolved
ertkonuk and others added 11 commits October 22, 2026 11:31
token_capture.top_logprobs=K keeps the top-K log-probs of every generated
token on captured calls: the request class raises SamplingParams.logprobs
to K while the response stays cut at top_logprobs=0, the worker writes the
two columns onto the call's staging row after the digest-covered put, and
the finalizer carries them token-aligned into the training rows as
generation_topk_ids / generation_topk_logprobs. Off by default (0).

Signed-off-by: Tugrul Konuk <[email protected]>
loss_fn.score_centering adds, per token, A * sum_v sg(c_v) log p_v over
the sampler's captured top-k ids (Marek and Ryabinin, arXiv:2609.20807,
Eq. 14, tail modeled as rho * p). Its gradient is the sampler-expected
score, in closed form for token-level "tis" weights, so the update stops
drifting toward the sampler. The head log-probs come from
ChunkedDistributedGatherLogprob (fp32 backward, TP + CP). Off by default.

Signed-off-by: Tugrul Konuk <[email protected]>
Adapt head/tail importance weighting, internal packed TP/CP gathering and
strict sampler probability validation from Oleg's c8f508bba implementation.
Preserve the clipped actor objective, token-capture transport, sampler adapter,
and existing OPD names and behavior. Add gradient, masking, probability and
packed preparation coverage, and expand the functional smoke to all IS modes.

Co-authored-by: Oleg Rybakov <[email protected]>
Signed-off-by: Guyue Huang <[email protected]>
@guyueh1
guyueh1 force-pushed the codex/score-centering branch from 0134154 to 0be7831 Compare October 22, 2026 18:41
@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 0be7831 (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 0dc043c (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@guyueh1

guyueh1 commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0dc043c

@copy-pr-bot

copy-pr-bot Bot commented Oct 22, 2026

Copy link
Copy Markdown

/ok to test 0dc043c

@guyueh1, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@guyueh1

guyueh1 commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0dc043c

@copy-pr-bot

copy-pr-bot Bot commented Oct 22, 2026

Copy link
Copy Markdown

/ok to test 0dc043c

@guyueh1, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@guyueh1

guyueh1 commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0dc043c

@guyueh1

guyueh1 commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test d05ecfc

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: d05ecfc (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@guyueh1

guyueh1 commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test c9d5fbe

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: c9d5fbe (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@guyueh1

guyueh1 commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 276e93a

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 276e93a (PR #4818 from codex/score-centering)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@guyueh1

guyueh1 commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 39c2642

subhankar-ghosh added a commit to subhankar-ghosh/Nemo-RL that referenced this pull request Oct 30, 2026
…dy-first

Applies the net diff of guyueh1/NeMo-RL pr/codex/score-centering (276e93a)
against its upstream base dd2e251, without merging upstream main.

Conflicts resolved:
- vllm/utils.py: drop the PR-side PrefixSplice import (unused here; it
  comes from an upstream commit we do not carry).
- tests/unit/data_plane/test_tq_token_sink.py: import only
  SAMPLER_TOPK_FIELDS (ROUTED_EXPERTS_FIELD unused in our test).
- tests/unit/single_controller/test_setup.py: keep our first_step_partial
  tests and the PR's score-centering tests; drop TestAdaptiveLossRestore
  (adaptive-ppo-clip is not in our base).

Not taken: the Gym submodule bump to NVIDIA-NeMo/Gym d8f4db46 (we stay on
subhankar-ghosh/Gym dabstep-patches; Gym NVIDIA-NeMo#4930 must be ported there) and the
matching uv.lock nemo-gym metadata line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@guyueh1

guyueh1 commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ee7f18f

@terrykong
terrykong enabled auto-merge (squash) October 31, 2026 23:32
@terrykong
terrykong merged commit 6e68b17 into NVIDIA-NeMo:main Nov 1, 2026
211 of 214 checks passed
jthomson04 added a commit to jthomson04/RL that referenced this pull request Nov 1, 2026
Resolves conflicts with NVIDIA-NeMo#4818 (score centering): keep both
chat_generation_tokens and attach_sampler_topk_logprobs_to_chat_response_choices
in vllm/utils.py, and add test_score_centering.py to the L0 vLLM shards
while keeping test_swe1_dynamo_config.py out (it moved to NVIDIA-NeMo#4979).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
isomap added a commit to isomap/RL that referenced this pull request Nov 3, 2026
The zero-tail branch set rho = 0 whenever the trainer tail was below 1e-6,
including unfiltered capture, where a tiny trainer tail can still carry a
large sampler tail. With a top-2 head, p = [0.6, 0.3999991, 9e-7] and
q = [0.5, 0.3, 0.2], IS-off centering then left an expected tail-logit
gradient of about 0.2 instead of the clamped estimate's 0.02.

Only replay, where the trainer renormalizes over the sampler's support and
the head holds all of p, has no tail. compute_score_centering_term now takes
sampler_replay and zeroes rho only then; unfiltered capture is back to
NVIDIA-NeMo#4818's estimate. ClippedPGLossFn derives the flag from policy_support_mask,
which only filtering supplies, and filtered score centering always replays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hayate Iso <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L2 Run doctests, unit tests, functional tests, and convergence tests Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants