Skip to content

feat(sc): support in-loss seq-logprob filtering - #5080

Merged
terrykong merged 7 commits into
mainfrom
sc-seq-logprob-in-loss
Nov 6, 2026
Merged

terrykong merged 7 commits into
mainfrom
sc-seq-logprob-in-loss

Conversation

@snivertynv

@snivertynv snivertynv commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

loss_fn.seq_logprob_error_in_loss evaluates grpo.seq_logprob_error_threshold inside the training loss, so the separate policy-logprob forward can be skipped when force_on_policy_ratio is set. It was supported by the non-streaming GRPO trainers but rejected by SingleController. This PR enables it for SingleController GRPO.

Changes

  • logprob_passes_required: skip the policy-logprob pass when the threshold is evaluated in the loss. The rule now lives in one function, loss.utils.skips_policy_logprob_pass, called by both SingleController and the regular trainer (opd._skip_prev_logprobs).
  • validate_single_controller_config: replace the blanket rejection with the existing GRPO validator (_validate_seq_logprob_error_in_loss), and reject PPO and token_capture.forest_training. With forest training the loss would filter individual rows, while SingleController masks whole logical owners.
  • setup.py: pass seq_logprob_error_threshold to the SingleController ClippedPGLossFn.
  • MegatronPolicyWorker.finish_train_step: with in-loss filtering, divide the accumulated gradients by the survivor counts the loss reports (seq_logprob_error_valid_{seqs,tokens}, summed over chunks and reduced over DP) instead of the pre-filter mask counts. A step with no surviving tokens raises before any gradient scaling or optimizer step. The survivor-count sums and the empty-step error are shared with the regular trainer's path; each path keeps its own reduce.
  • rescale_loss_metrics (regular trainer): a metric missing from the loss's metric_normalizations now raises instead of being logged with a guessed denominator. Every metric ClippedPGLossFn emits is listed, so no logged value changes.
  • advantage_stage.py: comment update only.
  • Docs: grpo.md and cispo.md describe SingleController support and which rows vote in the advantage baseline under masked_reward_policy: exclude.

Design notes

Advantage baselines are unchanged

The non-streaming trainers compute advantages before the logprob pass, so rows later rejected by the threshold still vote in their group's baseline. With the policy-logprob pass skipped, SingleController's final_sample_mask has no logprob-error component, so its baseline participation already matches the non-streaming trainers under both masked_reward_policy values. No change to the advantage stage is needed. In particular, the participation mask must not be dropped (valid_mask=None): that would let token-capture placeholders and dataset-weight-0 rows vote, and under exclude also mask_sample and truncated rows.

Gradient normalization

The split path backpropagates an unnormalized sum per chunk (N=1) and divides by N in finish_train_step. With N set to the global survivor-token count K, the update is S/K. That equals the non-streaming path's S/G × G/K rescale and the result of filtering before training.

All-rejected steps

As in the non-streaming trainers, a step where every sequence is rejected raises RuntimeError in finish_train_step before any update. SingleController policy workers have no Ray retries, and the train pump does not catch trainer errors, so the run ends with that message rather than retrying.

Interaction with ready_first

ready_first currently rejects force_on_policy_ratio=true unless use_cispo=true, which limits in-loss filtering with that sampler to CISPO. #5079 relaxes this for GRPO.

Validation

Multi-node SingleController GRPO on an MoE model, ready_first at lag 1, 512 prompts × 16 generations per step. Two arms identical except seq_logprob_error_in_loss; both with force_on_policy_ratio=true. The runs used GRPO (not CISPO) with #5079's ready_first change applied on top of this branch. Policy layout: PP=1, TP=4, CP=4 with sequence parallelism, EP=16, sequence packing on. Steps 2–14, one seed per arm:

Metric Separate pass In-loss Δ
reward 0.854 0.836 −2.2% (step-to-step stdev ≈ 0.09)
loss 0.0845 0.0880 +4.3% (stdev ≈ 0.03)
grad_norm 0.0295 0.0284 −3.8%
approx_entropy 0.777 0.774 −0.4%
sequences dropped / step (of 8192) 2.8 3.1 +0.2
step time 354 s 284 s −20%
policy training 257.0 s 257.7 s +0.3%
separate logprob pass 74.3 s 0 −100%
trained tokens / s 138.7k 169.4k +22%

Learning metrics stay within one step-to-step standard deviation. Steps were training-bound, so the removed logprob pass shows up end to end. When steps are generation-bound, the pass is already hidden and there is little step-time gain.

Tests

  • tests/unit/algorithms/test_single_forward_grpo.py: split-API gradients and metrics (N=1 chunk sums ÷ survivors) match filtering before training, across chunkings, KL on/off and both metric levels; rescale_loss_metrics rejects an unlisted metric; skips_policy_logprob_pass truth table.
  • tests/unit/models/policy/test_megatron_split_parity.py: on a real model with DP=2 and PP=2, both the regular trainer and the split API with in-loss filtering match dropping the rejected rows before training (loss and grad norm over two optimizer steps), and their metrics match each other.
  • tests/unit/models/policy/test_megatron_split_state.py: finish_train_step divides by survivor counts summed over chunks; an all-rejected step raises before scaling, optimizer or scheduler.
  • tests/unit/single_controller/test_resiliency_config.py: accepted for GRPO with no policy-logprob pass; rejected for PPO, forest training, and a missing threshold.
  • tests/unit/single_controller/test_single_controller_actor.py: advantage participation in in-loss mode matches the non-streaming trainers under exclude and include; no policy-logprob columns are read.

@snivertynv snivertynv self-assigned this Nov 4, 2026
@snivertynv snivertynv added the CI:L1 Run doctests, unit tests, and functional tests label Nov 4, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 4, 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 github-actions Bot added the Documentation Improvements or additions to documentation label Nov 4, 2026
@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test 3977c06

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 4, 2026 15:07
@snivertynv snivertynv changed the title feat(sc): support loss_fn.seq_logprob_error_in_loss on SingleController feat(sc): support in-loss seq-logprob filtering Nov 4, 2026
@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test 1b143c8

@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test 8cb3b94

@terrykong terrykong added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L1 Run doctests, unit tests, and functional tests labels Nov 5, 2026
@snivertynv
snivertynv force-pushed the sc-seq-logprob-in-loss branch from 0573f23 to 741c193 Compare November 5, 2026 22:37
@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test 741c193

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. Reusing the GRPO validator instead of copying it, and the two-line change to logprob_passes_required, keep the new path small. A 20% cut in step time with learning metrics inside one step-to-step standard deviation is a clear win. We found no correctness bug in the gradient or metric math: SingleController ends up at S/K, the same as the regular trainer.

  1. (C2) The new exclude sentence in grpo.md says only SingleController drops rejected rows from the baseline; the regular trainer does too.
  2. (C4) Low priority: share the survivor-count code with the regular trainer's path.
  3. (C5) Low priority: decide "skip the separate policy-logprob forward?" in one function that both trainers call.
  4. (C6) Make a metric missing from metric_normalizations an error in rescale_loss_metrics instead of guessing a factor, and drop gradient_factor.

Question on the validation run: this branch rejects ready_first with force_on_policy_ratio=true unless use_cispo=true (config.py#L1743-L1750). Did the runs use CISPO, or the follow-up PR (#5079?)? Could you also fill in the "<link PR 2>" placeholder, and share the parallel layout (pipeline parallel > 1? context parallel? sequence packing?)? The pipeline-stage part of the new reduce is only mocked in unit tests.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5080-sc-in-loss-filter.html

Generated by Claude Code

Comment thread docs/guides/grpo.md Resolved
Comment thread nemo_rl/algorithms/loss/utils.py Resolved
Evaluate grpo.seq_logprob_error_threshold inside the training loss on the
SingleController path, which removes the separate policy-logprob forward
when force_on_policy_ratio is set.

- Skip the policy-logprob pass in logprob_passes_required when the
  threshold is evaluated in the loss.
- Replace the SingleController rejection with the existing GRPO
  validation; reject PPO and token_capture.forest_training (the loss
  filters physical rows, forest training masks whole owners).
- Pass seq_logprob_error_threshold to the SingleController loss.
- finish_train_step divides the accumulated gradients by the survivor
  counts the loss reports instead of the pre-filter mask counts, and
  refuses an optimizer step with no surviving tokens.

Advantage baselines are unchanged: with the policy-logprob pass skipped,
final_sample_mask carries no logprob-error component, so participation
matches the non-streaming trainers under both masked_reward_policy values.

Signed-off-by: Sriharsha Niverty <[email protected]>
rescale_loss_metrics left metrics absent from the loss's
metric_normalizations unchanged, while the SingleController split path
divides them by the gradient denominator. With in-loss sequence filtering
that denominator is the survivor count, so the two trainers would log
different values for the same undeclared metric.

Rescale undeclared metrics by the gradient factor (the token factor, since
in-loss filtering requires token-level loss) and keep keys containing
_min or _max unchanged, matching the split path. Every metric
ClippedPGLossFn emits today is declared, so no logged value changes.

Signed-off-by: Sriharsha Niverty <[email protected]>
Signed-off-by: Sriharsha Niverty <[email protected]>
_validate_seq_logprob_error_in_loss is shared by the GRPO and
SingleController trainers, whose MasterConfig classes are unrelated.
Annotate the parameter as Any, as the shared opd helpers do, so pyrefly
accepts the SingleController call.

Signed-off-by: Sriharsha Niverty <[email protected]>
- rescale_loss_metrics raises for a metric missing from the loss's
  metric_normalizations instead of guessing a denominator; drop
  gradient_factor.
- Move the "skip the policy-logprob pass?" rule into
  loss.utils.skips_policy_logprob_pass, used by both trainers.
- Share the survivor-count sums and the empty-update error between the
  regular and SingleController paths in the Megatron worker.
- Docs: under masked_reward_policy=exclude, the separate-pass filter drops
  rejected rows from the baseline in every trainer.

Signed-off-by: Sriharsha Niverty <[email protected]>
Runs both trainers' in-loss path on a real model and checks loss and grad norm against dropping the rejected rows before training, and the regular and split-API metrics against each other.

Signed-off-by: Sriharsha Niverty <[email protected]>
@snivertynv
snivertynv force-pushed the sc-seq-logprob-in-loss branch from 741c193 to f803768 Compare November 6, 2026 09:36
@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test f803768

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the quick fixes. C2, C4, C5 and C6 are all fixed in 130752f and resolved. The new DP=2 / PP=2 test in 454ed41 covers the pipeline-stage reduce that was only mocked before.

C7 · 1 action item.
TL;DR — the PR description still has the <link PR 2> placeholder, and the validation question from the last review is open.

Fixed: the pipeline-stage part, through the new PP=2 test.

Still open:

  • The description says "<link PR 2> relaxes this for GRPO". Please put in the real PR (#5079?), since the description becomes the squash commit message.
  • This branch rejects ready_first with force_on_policy_ratio=true unless use_cispo=true (config.py#L1760-L1767), but the validation table uses ready_first with force_on_policy_ratio=true. Please add one line to the Validation section saying whether the runs used CISPO or #5079 on top of this branch, plus the parallel layout (PP, CP, sequence packing).

Original ask: #5080 (review)

Generated by Claude Code

@mehraakash mehraakash 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; no correctness bug found. Five agents checked the SingleController normalization against the regular trainer and it matches: each chunk backpropagates an unnormalized survivor sum, finish_train_step divides by the DP-reduced survivor token count, so the optimizer sees S/K exactly as the regular path's S/G × G/K. The per-chunk metrics are broadcast from the last pipeline stage before the finish-time reduce, so the DP-only all-reduce is the right group, and the CP/TP handling is the one the regular trainer already uses. The PR body's baseline-participation argument holds, and every trainer that can read loss_fn.seq_logprob_error_in_loss either rejects it or normalizes over survivors, so the "Megatron GRPO" wording in the docs is accurate. Re-verified at 454ed41 after the rebase; 69 CPU tests pass there. The finish_train_step tests and the new DP=2/PP=2 parity test need GPUs and were not run here.

terrykong's four asks are fixed in 130752f and resolved; we checked each at the new head and agree. One inline comment from us: the new forest-rejection test passes even with the forest check removed.

Two low notes, no inline comment because the files are outside the diff. The PPO rejection message at nemo_rl/algorithms/ppo.py L384-L388 still says "Use the non-streaming GRPO trainer", and examples/configs/ppo_math_1B.yaml L97 and tests/unit/reference_configs/ppo_math_1B_megatron.yaml L90 still say "Only supported by non-streaming Megatron GRPO"; all three now contradict the comment this PR updated in loss_functions.py. Suggested wording: "Use a GRPO trainer (legacy or SingleController)." and "# Only supported by Megatron GRPO trainers." Pattern only: the forest rejection at config.py L1584-L1588 could be one entry in validate_forest_objective's unsupported table (L980-L1004), which already lists every other loss_fn knob forest training rejects; if it moves, the test needs token_capture.enabled=True and a match on seq_logprob_error_in_loss, as in the inline comment.

One question. #5095 (detached MTP heads, based on this branch) shows as merged into sc-seq-logprob-in-loss at 22:12 UTC yesterday, but the branch was force-pushed afterwards and that commit is in neither the current head nor main; will it return as a separate PR against main?

Generated by Claude Code

@snivertynv

Copy link
Copy Markdown
Contributor Author

Thanks for the quick fixes. C2, C4, C5 and C6 are all fixed in 130752f and resolved. The new DP=2 / PP=2 test in 454ed41 covers the pipeline-stage reduce that was only mocked before.

C7 · 1 action item. TL;DR — the PR description still has the <link PR 2> placeholder, and the validation question from the last review is open.

Fixed: the pipeline-stage part, through the new PP=2 test.

Still open:

Original ask: #5080 (review)

Generated by Claude Code

Thanks. Updated the description: the placeholder now points to #5079, and the Validation section states the runs used GRPO (not CISPO) with #5079's ready_first change applied on top of this branch, with PP=1, TP=4, CP=4 + sequence parallel, EP=16

List loss_fn.seq_logprob_error_in_loss with the other settings forest training rejects, and make the test use a legal forest config so only that rejection can satisfy it. Update PPO's rejection message and config comments now that SingleController GRPO supports the mode.

Signed-off-by: Sriharsha Niverty <[email protected]>
@snivertynv

Copy link
Copy Markdown
Contributor Author

Verdict: approve; no correctness bug found. Five agents checked the SingleController normalization against the regular trainer and it matches: each chunk backpropagates an unnormalized survivor sum, finish_train_step divides by the DP-reduced survivor token count, so the optimizer sees S/K exactly as the regular path's S/G × G/K. The per-chunk metrics are broadcast from the last pipeline stage before the finish-time reduce, so the DP-only all-reduce is the right group, and the CP/TP handling is the one the regular trainer already uses. The PR body's baseline-participation argument holds, and every trainer that can read loss_fn.seq_logprob_error_in_loss either rejects it or normalizes over survivors, so the "Megatron GRPO" wording in the docs is accurate. Re-verified at 454ed41 after the rebase; 69 CPU tests pass there. The finish_train_step tests and the new DP=2/PP=2 parity test need GPUs and were not run here.

terrykong's four asks are fixed in 130752f and resolved; we checked each at the new head and agree. One inline comment from us: the new forest-rejection test passes even with the forest check removed.

Two low notes, no inline comment because the files are outside the diff. The PPO rejection message at nemo_rl/algorithms/ppo.py L384-L388 still says "Use the non-streaming GRPO trainer", and examples/configs/ppo_math_1B.yaml L97 and tests/unit/reference_configs/ppo_math_1B_megatron.yaml L90 still say "Only supported by non-streaming Megatron GRPO"; all three now contradict the comment this PR updated in loss_functions.py. Suggested wording: "Use a GRPO trainer (legacy or SingleController)." and "# Only supported by Megatron GRPO trainers." Pattern only: the forest rejection at config.py L1584-L1588 could be one entry in validate_forest_objective's unsupported table (L980-L1004), which already lists every other loss_fn knob forest training rejects; if it moves, the test needs token_capture.enabled=True and a match on seq_logprob_error_in_loss, as in the inline comment.

One question. #5095 (detached MTP heads, based on this branch) shows as merged into sc-seq-logprob-in-loss at 22:12 UTC yesterday, but the branch was force-pushed afterwards and that commit is in neither the current head nor main; will it return as a separate PR against main?

Generated by Claude Code

Thanks. Feedback addressed in 092f5f7

On #5095, I merged it into this branch by mistake (it was stacked with this branch as its base), which also broke DCO here, so I force-pushed to undo it. The detached-MTP change is on sc-inloss-mtp, rebased onto this branch, and will come back as a new PR. It stays stacked here for review and gets retargeted to main once this PR merges.

@snivertynv

Copy link
Copy Markdown
Contributor Author

/ok to test 092f5f7

@terrykong
terrykong enabled auto-merge (squash) November 6, 2026 18:35
@terrykong
terrykong merged commit 897c5a1 into main Nov 6, 2026
96 checks passed
@terrykong
terrykong deleted the sc-seq-logprob-in-loss branch November 6, 2026 20:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants