Skip to content

feat(loss): add equal-group token normalization - #4947

Merged
terrykong merged 12 commits into
NVIDIA-NeMo:mainfrom
u-brixton:group-token-mean
Nov 20, 2026
Merged

terrykong merged 12 commits into
NVIDIA-NeMo:mainfrom
u-brixton:group-token-mean

Conversation

@u-brixton

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

Copy link
Copy Markdown
Contributor

What does this PR do?

Add equal prompt-group token averaging to SingleController Megatron GRPO: take the token mean within each prompt group, then give each nonempty group equal weight.

This PR builds on #4946, now merged into main. The Files changed tab shows the group-normalization layer.

Normalization Averaging
global_token_mean One token mean across the whole batch.
sequence_mean Token mean per response, then mean over responses.
group_token_mean Token mean across each prompt group's responses, then mean over groups.

The group reducer prepares one FP32 inverse group-token weight per response after masks are finalized, while groups are complete. Setup and training use its declared data-plane field; packing preserves the weights. The shared streaming worker recovers the group denominator across chunks and DP ranks without group-specific worker code.

Valid zero-advantage tokens remain in the denominator; importance-weight rejection does not renormalize it. Logged loss and KL divide by the group count, the same divisor as the gradient; token diagnostics and detached MTP retain their token denominator. Group averaging is SingleController GRPO only and rejects unsupported trainers and backends (including PPO), OPD, sequence-level importance ratios, positive-example NLL, in-loss sequence filtering, and active attached MTP/router auxiliary losses whose gradients cannot use the group denominator.

Group-weight preparation follows Afonso Marques's approach in MFN of calculating weights before packing, adapted to NeMo-RL's explicit masks and streaming updates.

Usage

On a SingleController GRPO recipe with Megatron:

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

Validation

Validation covers the combined #4946 + #4947 stack:

  • CPU unit suites for reducers, group weights, loss terms, streaming-worker state, advantage preparation, resiliency and controller behavior: 1301 passed, 0 failed (CUDA-only tests skipped).
  • Real-model GPU parity for streaming group_token_mean (DP2, each step split into two train_microbatch chunks) against an exact synchronous oracle: global_token_mean on masks scaled by each group's inverse token mass. Cases: equal-length groups, and ragged groups with a dropped row and sequence packing; the ragged case also checks that plain global_token_mean falls outside the tolerance.
  • Every loss term matches an independent oracle under group_token_mean, including dropped and fractional sample masks; each group guard has a test.
  • 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.
  • Paired 300-step training runs on a small base math model (2 seeds per token-mean arm, plus sequence_mean); curves and table are in this review thread.
  • 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.

Before your PR is "Ready for review"

  • Read and followed the contributor guidelines; commits are signed off.
  • Added focused numerical, packing, controller, and worker coverage.
  • Did you run the unit tests and functional tests locally? See the completed matrix and recorded failures above.
  • Documented the formula, configuration, and supported training paths.

@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
u-brixton marked this pull request as ready for review October 27, 2026 21:47

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

Review of the incremental layer over #4946 (this PR is stacked on it; diff reviewed = pr-4946-head..7d470da6). No correctness issues found in the group-token-mean path. The comments below are test-coverage and documentation asks, plus a request for before/after curves against global_token_mean.

Comment thread docs/guides/grpo.md Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread nemo_rl/algorithms/loss/utils.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!

Iterated on review comments, attached curves for the small comparison run, GPU parity test now also covers prompt groups with uneven response lengths

Comment thread examples/configs/ppo_math_1B.yaml Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread nemo_rl/algorithms/loss/interfaces.py Resolved
Comment thread docs/guides/grpo.md Resolved
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#4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
@u-brixton u-brixton added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 4, 2026
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 435d24a

u-brixton added a commit to u-brixton/RL that referenced this pull request Nov 5, 2026
Apply the reviewer's suggested code from the NVIDIA-NeMo#4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

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 196395b

@u-brixton
u-brixton requested a review from mehraakash November 5, 2026 10:16
@terrykong terrykong added CI:L1 Run doctests, unit tests, and functional tests CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) CI:L1 Run doctests, unit tests, and functional tests labels Nov 5, 2026
u-brixton added a commit to u-brixton/RL that referenced this pull request Nov 9, 2026
Apply the reviewer's suggested code from the NVIDIA-NeMo#4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

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 4849a5a

1 similar comment
@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 4849a5a

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#4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

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 dee9aaf

@u-brixton

Copy link
Copy Markdown
Contributor Author

/ok to test 1c4f8ba

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#4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
copy-pr-bot Bot pushed a commit that referenced this pull request Nov 18, 2026
Apply the reviewer's suggested code from the #4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
@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 0acc8ab

copy-pr-bot Bot pushed a commit that referenced this pull request Nov 18, 2026
Apply the reviewer's suggested code from the #4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
@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 61f6ec7

mehraakash
mehraakash previously approved these changes Nov 19, 2026

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

Re-checked all earlier threads at 61f6ec7: every fix is in, CI is green. Approving. Please rebase for the conflict in tests/unit/single_controller/test_resiliency_config.py before merging.

u-brixton and others added 12 commits November 20, 2026 10:39
Signed-off-by: Renat Zayashnikov <[email protected]>
Apply the reviewer's suggested code from the NVIDIA-NeMo#4947 review:
- full docstring for group_token_mean_weights;
- explain why GroupTokenMeanReduction inherits metric_normalizer=TOKENS;
- Literal types for the validate_setup trainer/algorithm parameters;
- state in ppo_math_1B.yaml that group_token_mean is GRPO-only;
- note why validate_loss_options also runs at config time;
- assert in the advantage-stage test that mask_sample reached the row;
- CPU tests for the explicit-denominator requirement, malformed row
  weights, the loss/KL metric pop, group_token_mean_weights input checks,
  validate_setup rejections, and reducer column registration in the
  controller train fields and the partition warmup.

Signed-off-by: Renat Zayashnikov <[email protected]>
Co-authored-by: Akash Mehra <[email protected]>
The helper's only production caller is GroupTokenMeanReduction.prepare_batch,
and it depends on nothing in loss/utils.py. Defining it next to the
reduction removes the call-time import that existed only to break the
utils -> interfaces import cycle.

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

AdvantageStageConfig gained a required objective_reduction field with
group_token_mean; the logical-advantage tests added on main after this
branch was first written construct the config directly and need it.

Signed-off-by: Renat Zayashnikov <[email protected]>
Add docstrings to validate_setup, validate_loss_options and prepare_batch;
the validate_setup wording follows the reviewer's suggestion.

Signed-off-by: Renat Zayashnikov <[email protected]>
Extend the reduction-consistency test with group_token_mean: every term,
including the score-centering correction, must equal the sum of per-token
values weighted by 1/T_g of their prompt group divided by the number of
groups with positive token mass. The denominator comes from the
reduction's own local_counts, as the split worker would all-reduce it.
Also check that OPD-full is rejected under group_token_mean.

Signed-off-by: Renat Zayashnikov <[email protected]>
Compare a streaming group_token_mean run (DP2, two train_microbatch chunks
per step) with a sync train() oracle: global_token_mean on a token_mask
scaled per row by its 1/T_g group weight. The global token mass is then the
group count and the objective is exactly the group token mean; with equal
group masses it is plain global_token_mean.

Parametrize over response lengths. "equal" uses fixed-length rows without
packing. "ragged" uses unequal group masses, a sample_mask=0 row and
sequence packing on the split run, and checks against CPU-recomputed
step-0 losses that plain global_token_mean is far outside the parity
tolerance. Groups interleave rows so each spans both chunks.

A CPU test checks the oracle: on group-scaled masks global_token_mean
matches group_token_mean in loss and gradient.

Signed-off-by: Renat Zayashnikov <[email protected]>
Keep validate_loss_options in both places: ClippedPGLossFn.__init__ covers
every construction path, and the SingleController config validation fails
before the Ray cluster starts. Say so at the loss-side call too.

Signed-off-by: Renat Zayashnikov <[email protected]>
GroupTokenMeanReduction overrode every GlobalTokenMeanReduction method and
only inherited its ClassVars. Derive it from ObjectiveReduction, write the
ClassVars out (TOKEN_LEVEL legacy loss_type, not token normalized, explicit
denominator, row-weight extra field) and inline the weighted masked_mean.

With loss/KL advertised as LOSS_DIVISOR, the group's logged loss and KL are
divided by the global group count, so the comment about the inherited
metric normalizer is obsolete. The table test now checks the LOSS_DIVISOR
entries and that rescaling streamed sums by them matches the synchronous
metrics.

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

Copy link
Copy Markdown
Contributor Author

/ok to test 818d7bf

@terrykong
terrykong enabled auto-merge (squash) November 20, 2026 19:43
@terrykong
terrykong merged commit 767fcfb into NVIDIA-NeMo:main Nov 20, 2026
96 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