Skip to content

refactor(loss): unify normalization and streaming reduction - #4946

Merged
terrykong merged 15 commits into
NVIDIA-NeMo:mainfrom
u-brixton:loss-normalization-reducers
Nov 20, 2026
Merged

terrykong merged 15 commits into
NVIDIA-NeMo:mainfrom
u-brixton:loss-normalization-reducers

Conversation

@u-brixton

@u-brixton u-brixton commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Give global-token and response-mean policy losses one explicit normalization selector and named reducers, so additional averaging modes can reuse the streaming worker.

loss_fn.normalization selects global_token_mean or sequence_mean. The legacy token_level_loss flag still works when the new selector is unset but is deprecated (FutureWarning); supplying both non-null selectors is an error. Shared base configs leave both selectors unset; recipes that set the legacy flag explicitly keep working and will be migrated in a follow-up PR.

Each reducer owns the reduction of every loss term (actor, KL, score centering, OPD-full) and its denominator counting; its loss_divisor() is the single denominator for the gradient and for the logged loss and KL. Streaming workers accumulate counts across train_microbatch chunks and DP ranks and normalize gradients once at update completion, while token diagnostics and detached MTP retain their token denominator. Synchronous train() paths keep their token or sequence counts.

On the SingleController Megatron streaming path, active router auxiliary and z-losses are rejected under sequence averaging because their mixed gradients cannot receive a separate token denominator. Such runs previously trained with a mismatched denominator; they now fail at split-step setup. Draft-model and detached-MTP corrections under sequence_mean are covered by mock tests only.

Resuming in the same checkpoint_dir under a different normalization fails at startup, because buffered rollouts were prepared for the original one. Starting a new run from a checkpoint's weights is unaffected.

Group-token averaging is supplied by the dependent PR #4947.

The reducer interface follows Teodor Poncu's MFN loss-averaging design, adapted to NeMo-RL's training interfaces.

Usage

loss_fn:
  token_level_loss: null  # Clear an inherited legacy selector, if present.
  normalization: sequence_mean

Validation

Validation covers the combined #4946 + #4947 stack:

  • CPU unit suites for reducers, loss terms, normalization config, streaming-worker state, controller setup and checkpointing: 1262 passed on this PR and 1301 with feat(loss): add equal-group token normalization #4947, 0 failed (CUDA-only tests skipped).
  • Real-model GPU split-vs-sync parity, DP2 and TP2, for global_token_mean and sequence_mean, with each step split into two train_microbatch chunks: loss, gradient norms and metrics matched over two optimizer steps. Router auxiliary-loss guard tests passed.
  • Every loss term (actor, KL, score centering, OPD-full) matches an independent oracle and the previous formula, including dropped and fractional sample masks.
  • End-to-end group_token_mean training: four optimizer steps with Qwen3-0.6B, Megatron DP2, and sequence packing. Every step had nonzero finite gradients and mixed rewards; two steps accumulated across multiple streaming chunks.
  • Ruff and formatting checks and the recipe config minimize check passed; pyrefly reports no new findings relative to main.
  • Ran the complete unit and functional matrix (52 lanes) on four-GPU GB300 nodes with FAST=0, upstream skips retained, and assertions and thresholds unchanged.

Full-matrix outcome: 46 of 52 lanes pass. The six remaining failures reproduce identically on the upstream base in the same environment:

  • Two Automodel unit shards: the vLLM-vs-HF fp8 logprob check exceeds its 1.08 tolerance (1.082 and 1.122), with identical values on base.
  • One MXFP8 functional lane: the Megatron refit probability-mismatch assertion fails with identical values on base.
  • One TRT-LLM unit shard: the HTTP server parity test errors with "tokenizer died" on base too.
  • One SingleController functional lane: the router-failover test lacks the same two router/fleet metrics on base.
  • One functional lane: a research test times out at Ray node startup on base too.

The GRPO NIXL lane needed CUDA transports enabled in UCX. The SGLang fault-tolerance chaos test is intermittent on both base and PR (Ray GCS loss after the injected kill) and passed on rerun.

The upstream actor-support and reference-KL mask separation is preserved.

Before your PR is "Ready for review"

  • Read and followed the contributor guidelines; commits are signed off.
  • Added focused config, numerical, and worker coverage.
  • Did you run the unit tests and functional tests locally? See the completed matrix and recorded failures above.
  • Updated normalization documentation and exemplar configs.

@copy-pr-bot

copy-pr-bot Bot commented Oct 27, 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 Oct 27, 2026
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 5624775

@u-brixton
u-brixton marked this pull request as ready for review October 27, 2026 21:47
@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from 5624775 to c47eeb2 Compare October 27, 2026 21:49

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

Overall: this is a parity-preserving refactor and nothing here blocks merge. #4947 is stacked on it.

Three asks for the PR description rather than the code:

  • Say that the router-auxiliary guard is a behaviour change: a config that previously ran now fails hard at setup.
  • Say that the shipped recipes keep using the token_level_loss alias on purpose, so readers do not open 24 migration PRs.
  • Say that the synchronous (non-streaming) trainers do not carry the third count, so sequence_mean parity there rests on the single-chunk path and is not tested.

Inline comments: 5 fixes (one real bug in the warning category, the rest tests and design), 6 nits.

Comment thread nemo_rl/algorithms/loss/wrapper.py Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved

@u-brixton u-brixton 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.

Thank you for the review!

Addressed review comments and rebased on latest main.
Logged loss and KL now also use the same divisor as gradient, GPU parity tests cover both global_token_mean and sequence_mean with 2 chunks per step. Also added a startup check that rejects resuming with a different normalization.

Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from c47eeb2 to 668d521 Compare November 4, 2026 18:20
u-brixton added a commit to u-brixton/RL that referenced this pull request Nov 4, 2026
Apply the reviewer's suggested code from the NVIDIA-NeMo#4946 review:
- emit FutureWarning (shown by default) instead of DeprecationWarning for
  the token_level_loss alias, and match it in the config test;
- forbid any warning when the alias is unset in that test;
- StreamingObjectiveLoss: docstring, __getattr__ guard for the loss_fn
  probe during deepcopy/unpickle, and positional-argument forwarding;
- document the ObjectiveReduction ClassVars and the
  global_objective_denominator argument;
- pin the router auxiliary-loss guard to the Megatron-LM source it mirrors;
- CPU tests for denominator forwarding through StreamingObjectiveLoss,
  get_objective_reduction precedence and local_counts without token_mask.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
@u-brixton u-brixton added the CI:L1 Run doctests, unit tests, and functional tests label Nov 4, 2026
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 668d521

@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from 668d521 to f969bbb Compare November 5, 2026 07:22
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test f969bbb

@u-brixton
u-brixton requested a review from mehraakash November 5, 2026 10:16
@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
@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from f969bbb to 2349a9b Compare November 9, 2026 18:19
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 2349a9b

copy-pr-bot Bot pushed a commit that referenced this pull request Nov 9, 2026
Apply the reviewer's suggested code from the #4946 review:
- emit FutureWarning (shown by default) instead of DeprecationWarning for
  the token_level_loss alias, and match it in the config test;
- forbid any warning when the alias is unset in that test;
- StreamingObjectiveLoss: docstring, __getattr__ guard for the loss_fn
  probe during deepcopy/unpickle, and positional-argument forwarding;
- document the ObjectiveReduction ClassVars and the
  global_objective_denominator argument;
- pin the router auxiliary-loss guard to the Megatron-LM source it mirrors;
- CPU tests for denominator forwarding through StreamingObjectiveLoss,
  get_objective_reduction precedence and local_counts without token_mask.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 2349a9b

@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from 2349a9b to 88af029 Compare November 11, 2026 16:11
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 88af029

copy-pr-bot Bot pushed a commit that referenced this pull request Nov 11, 2026
Apply the reviewer's suggested code from the #4946 review:
- emit FutureWarning (shown by default) instead of DeprecationWarning for
  the token_level_loss alias, and match it in the config test;
- forbid any warning when the alias is unset in that test;
- StreamingObjectiveLoss: docstring, __getattr__ guard for the loss_fn
  probe during deepcopy/unpickle, and positional-argument forwarding;
- document the ObjectiveReduction ClassVars and the
  global_objective_denominator argument;
- pin the router auxiliary-loss guard to the Megatron-LM source it mirrors;
- CPU tests for denominator forwarding through StreamingObjectiveLoss,
  get_objective_reduction precedence and local_counts without token_mask.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
u-brixton added a commit to u-brixton/RL that referenced this pull request Nov 11, 2026
Apply the reviewer's suggested code from the NVIDIA-NeMo#4946 review:
- emit FutureWarning (shown by default) instead of DeprecationWarning for
  the token_level_loss alias, and match it in the config test;
- forbid any warning when the alias is unset in that test;
- StreamingObjectiveLoss: docstring, __getattr__ guard for the loss_fn
  probe during deepcopy/unpickle, and positional-argument forwarding;
- document the ObjectiveReduction ClassVars and the
  global_objective_denominator argument;
- pin the router auxiliary-loss guard to the Megatron-LM source it mirrors;
- CPU tests for denominator forwarding through StreamingObjectiveLoss,
  get_objective_reduction precedence and local_counts without token_mask.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from 88af029 to 8b6820f Compare November 17, 2026 20:39
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 8b6820f

copy-pr-bot Bot pushed a commit that referenced this pull request Nov 17, 2026
Apply the reviewer's suggested code from the #4946 review:
- emit FutureWarning (shown by default) instead of DeprecationWarning for
  the token_level_loss alias, and match it in the config test;
- forbid any warning when the alias is unset in that test;
- StreamingObjectiveLoss: docstring, __getattr__ guard for the loss_fn
  probe during deepcopy/unpickle, and positional-argument forwarding;
- document the ObjectiveReduction ClassVars and the
  global_objective_denominator argument;
- pin the router auxiliary-loss guard to the Megatron-LM source it mirrors;
- CPU tests for denominator forwarding through StreamingObjectiveLoss,
  get_objective_reduction precedence and local_counts without token_mask.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
Comment thread docs/guides/grpo.md Resolved
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 9e0c176

@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test e1bd8f9

@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from e1bd8f9 to 6972df5 Compare November 18, 2026 21:24
@u-brixton u-brixton added CI:L1 Run doctests, unit tests, and functional tests and removed CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) labels Nov 18, 2026
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 6972df5

u-brixton and others added 15 commits November 19, 2026 07:33
Apply the reviewer's suggested code from the NVIDIA-NeMo#4946 review:
- emit FutureWarning (shown by default) instead of DeprecationWarning for
  the token_level_loss alias, and match it in the config test;
- forbid any warning when the alias is unset in that test;
- StreamingObjectiveLoss: docstring, __getattr__ guard for the loss_fn
  probe during deepcopy/unpickle, and positional-argument forwarding;
- document the ObjectiveReduction ClassVars and the
  global_objective_denominator argument;
- pin the router auxiliary-loss guard to the Megatron-LM source it mirrors;
- CPU tests for denominator forwarding through StreamingObjectiveLoss,
  get_objective_reduction precedence and local_counts without token_mask.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
…reduction

The OPD-full helper and the score-centering correction picked their
denominator from loss_type, bypassing the configured reduction. Both now
call objective_reduction.reduce with the same divisor and per-response
weights as the actor objective, and _opd_full_call receives the streaming
global_objective_denominator. The explicit-denominator metric pop now runs
after the opd_full metric table is built so it applies to both branches.

global_token_mean and sequence_mean results are unchanged.

Signed-off-by: Renat Zayashnikov <[email protected]>
Build a two-group batch with unequal response lengths and check that
ClippedPGLossFn's value and gradients equal a hand-written oracle for each
normalization with no optional term, the reference KL penalty, score
centering and opd_full (with and without KL). The same cases pin the
global_token_mean and sequence_mean results to the pre-refactor
loss_type-branched formula. New loss terms should be added to this file.

Signed-off-by: Renat Zayashnikov <[email protected]>
Make global_valid_seqs/global_valid_toks keyword-only in
StreamingObjectiveLoss.__call__, so a positional caller gets a TypeError
instead of a KeyError. Every caller already passes them by keyword.

Pin the __getattr__ guard: copy.deepcopy and pickle probe attributes
before __init__ runs, which used to recurse through the loss_fn lookup.
Also run the streaming-vs-full equivalence test with an
explicit-denominator reduction, so it fails if the wrapper does not
forward the denominator.

Signed-off-by: Renat Zayashnikov <[email protected]>
…steps

Parametrize test_split_train_matches_sync_train over global_token_mean and
sequence_mean, and dispatch each split step as two half-batch
train_microbatch calls so cross-chunk accumulation of the objective and its
denominator is exercised. GPU test; not run locally.

Signed-off-by: Renat Zayashnikov <[email protected]>
Cover every normalization/token_level_loss pair in the conflict check,
including agreeing pairs (the strict one-selector rule is kept during the
deprecation window), and assert the error tells users to set
token_level_loss=null.

Signed-off-by: Renat Zayashnikov <[email protected]>
Describe the arguments of the shared reduction entry point and state that
every gradient-normalized loss term must go through it.

Signed-off-by: Renat Zayashnikov <[email protected]>
validate_forest_objective rejected configs with 'not loss.token_level_loss',
which is now true for the default (token_level_loss unset), so every Forest
config failed at startup after rebasing on main. Compare the resolved
normalization instead and name the selector the user actually set.

Signed-off-by: Renat Zayashnikov <[email protected]>
Express the GSPO golden case with normalization=sequence_mean instead of
the deprecated token_level_loss=False. The pinned golden source predates
the normalization field, so the generator maps it back to the legacy
alias there; loss, gradients and metrics are unchanged and the committed
golden JSON is not regenerated.

Signed-off-by: Renat Zayashnikov <[email protected]>
Add MetricNormalizer.LOSS_DIVISOR and advertise it for ClippedPGLossFn's
loss and kl_penalty entries (main and opd_full tables), so the logged
objective is divided by exactly the divisor the gradient used instead of a
separately maintained label. This removes the metric_normalizer ClassVar
from the objective reductions and the requires_explicit_denominator pop of
the loss/KL entries.

The Megatron split-step finish resolves LOSS_DIVISOR through the step's
objective reduction (metric_normalizer_scales); survivor rescaling applies
the gradient's factor. Logged values are unchanged for global_token_mean
and sequence_mean.

Signed-off-by: Renat Zayashnikov <[email protected]>
Rows in a restored data-plane snapshot were prepared for the loss
normalization they were written under, so resuming the same
checkpoint_dir must keep it. Record the resolved loss_fn normalization
in the data-plane checkpoint metadata and reject a restore whose current
normalization differs. Initializing from a checkpoint's weights in a new
checkpoint_dir restores no rows and is unaffected. Checkpoints written
before the field existed are accepted only for the two original modes,
global_token_mean and sequence_mean.

Signed-off-by: Renat Zayashnikov <[email protected]>
@u-brixton
u-brixton force-pushed the loss-normalization-reducers branch from 6972df5 to d01c03a Compare November 19, 2026 15:35
@u-brixton u-brixton 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 19, 2026
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test d01c03a

@terrykong
terrykong merged commit 190092a into NVIDIA-NeMo:main Nov 20, 2026
98 checks passed
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