Skip to content

fix(LOO-Norm-Advantage): Fix spike in LOO normed advantage. - #4158

Merged
terrykong merged 5 commits into
mainfrom
cye/adv-loo-norm-bugfix
Sep 21, 2026
Merged

terrykong merged 5 commits into
mainfrom
cye/adv-loo-norm-bugfix

Conversation

@cspades

@cspades cspades commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

With leave_one_out_baseline=True and normalize_rewards=True, it is possible to get an advantage explosion with a reward distribution like [y x x x x ... ] where x != y, which is caused by numerical discrepancies between the mean of the square and the square of the mean when computing the standard deviation:

Rewards              = [0, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95]
mean                 = 0.9499999
E[x²]                = 0.90250003
mean²                = 0.90249985
variance             = (7/6) × 1.7881393e-7
                     = 2.0861626e-7
std                  = 0.0004567453

normalized advantage (of 0) = -0.9499999 / (0.0004567453 + 1e-6)
                     = -2075.39

This is not expected, because the idea behind GRPO is that with a trivial reward distribution (leaving out the current sample, so including all the other rewards), you get NO advantage, and a trivial reward distribution should produce std = 0, not std = 0.0004567453. This suggests that the incorrect answer is incredibly wrong after normalization, when it is only really significantly wrong (i.e. the raw difference against the mean is enough of a disadvantage).

Note that this explosion isn't observed if LOO=False, since every reward - baseline = 0 for trivial non-LOO distributions. So we just get 0 advantage in that case.

You could argue that with a single outlier reward, it should be harshly punished, but I don't think it should be punished with respect to the inverse of a squared FP32 rounding error. The raw / un-normalized error should be sufficient disadvantage and isn't a function of numerical precision.

We fix this by extending the normalization mask normalize_mask = (std > 0) & ~is_trivial_distribution so that the trivial reward distribution for the sample y that produces an extremely small but non-zero std skips normalization similar to the std == 0 case, which intuitively guards against precisely the same case.

Before this fix, using vLLM or Megatron-LLM on a very "easy" dataset like CLEVR where it's very common for the pre-trained model to get correct rollouts except for a single incorrect generation, we get exorbitant disadvantage that damages training loss, gradients, etc.:

Screenshot 2026-09-16 at 3 48 36 PM

After this fix, we go back to normalcy:

Screenshot 2026-09-16 at 4 21 03 PM

Issues

List issues that this PR closes (syntax):

Usage

  • You can potentially add a usage example below
# Add a code snippet demonstrating how to use this

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

  • ...

@cspades
cspades requested review from a team as code owners September 16, 2026 23:33
@copy-pr-bot

copy-pr-bot Bot commented Sep 16, 2026

Copy link
Copy Markdown

Auto-sync is disabled for ready for review pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@cspades cspades changed the title Fix advantage spike loophole with LOO and normalization. bug(LOO-Norm-Advantage): Fix advantage spike loophole with LOO and normalization. Sep 16, 2026
@cspades cspades changed the title bug(LOO-Norm-Advantage): Fix advantage spike loophole with LOO and normalization. fix(LOO-Norm-Advantage): Fix advantage spike loophole with LOO and normalization. Sep 16, 2026
@cspades cspades changed the title fix(LOO-Norm-Advantage): Fix advantage spike loophole with LOO and normalization. fix(LOO-Norm-Advantage): Fix spike in LOO normed advantage. Sep 16, 2026
@cspades cspades self-assigned this Sep 16, 2026
@cspades cspades added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) bug Something isn't working accuracy labels Sep 16, 2026
Comment thread tests/unit/algorithms/test_utils.py Resolved
Comment thread nemo_rl/algorithms/grpo.py Resolved
@cspades

cspades commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 986ef03

terrykong added a commit to terrykong/gh-pages-poc that referenced this pull request Sep 17, 2026
One-page explainer for NVIDIA-NeMo/RL#4158: why a group where seven of
eight rollouts scored the same gave the odd rollout an advantage of
-2075 instead of -0.95, and how the fix skips normalization when a
rollout's comparison set is all one value.

Signed-off-by: Terry Kong <[email protected]>
@cspades
cspades force-pushed the cye/adv-loo-norm-bugfix branch from 986ef03 to 60ff122 Compare September 17, 2026 16:05
@cspades

cspades commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 60ff122

@jayl940712

Copy link
Copy Markdown

Potentially a duplicate with #4161

@cspades

cspades commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor Author

FYI seems like we only need to update the golden value for a test case in a single PPO test: run_test fast uv run --no-sync bash ./tests/functional/ppo_non_colocated.sh

    │ FAIL       │ max(data["train/critic/grad_norm"]) < 350                             │ 560.0089721679688            │ max(data["train/critic/grad_norm"]) < 350 (condition evaluated to False)                             │

🤔 why would the gradient norm go up after my change?

I think this test is flaky, rerunning in the next update...

@cspades

cspades commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Potentially a duplicate with #4161

@jayl940712 Their fix is simple/clean but I'm not sure setting an arbitrary 1e-3 floor (which BTW, removes the point of ... + eps in the denominator) would be the right approach. This part of RL isn't expensive so I think we should just be exact and identify trivial reward distributions exactly without putting a non-zero lower bound on std.

@cspades
cspades force-pushed the cye/adv-loo-norm-bugfix branch from 60ff122 to 9a17004 Compare September 17, 2026 17:24
@cspades

cspades commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 9a17004

Comment thread nemo_rl/algorithms/grpo.py Resolved
@jayl940712

Copy link
Copy Markdown

Potentially a duplicate with #4161

@jayl940712 Their fix is simple/clean but I'm not sure setting an arbitrary 1e-3 floor (which BTW, removes the point of ... + eps in the denominator) would be the right approach. This part of RL isn't expensive so I think we should just be exact and identify trivial reward distributions exactly without putting a non-zero lower bound on std.

Yes agreed. This PR is more thorough

@cspades
cspades force-pushed the cye/adv-loo-norm-bugfix branch from 9a17004 to 70b70e7 Compare September 17, 2026 22:08
@cspades

cspades commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 70b70e7

terrykong added a commit to terrykong/gh-pages-poc that referenced this pull request Sep 19, 2026
Second page for NVIDIA-NeMo/RL#4158: why the same question ('are these
rewards all the same?') needs a per-rollout answer for normalization and
a per-group answer for dynamic sampling.

The first attempt in the PR reused the per-rollout leave-one-out mask for
both. A reviewer showed that splits groups: for [0.0, 0.95 x7] it drops
only the losing rollout and keeps seven identical winners, whose
advantages then recompute to 0.0 -- the group teaches nothing. The author
added calculate_is_trivial_prompt_distribution for the group-level answer.

Both cases verified against the real functions at 70b70e7. Adds the chain
nav to both pages so either one finds the other.

Signed-off-by: Terry Kong <[email protected]>

@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 — the fix is correct and needed, and the worked example in the description holds up exactly. In float32: mean 0.9499999285, E[x^2] 0.9025000334, mean^2 0.9024998546, difference 1.788139343e-07, variance 2.086162567e-07, std 0.0004567452997, advantage -2075.389893. Running the real function on the merge base vs this branch gives -2075.3899 and -0.95.

The separate whole-group mask is the right shape, and the round it went through was worth it. Two tidier-looking alternatives are both worse, which is worth recording so nobody reaches for them later:

  • Forcing std to 0 where the per-rollout flag is True. The filter is per row, so on [0.0, 0.95 x7] that drops rollout 1 by itself and leaves seven identical winners whose advantages recompute to 0.0.
  • Computing the variance accurately instead of E[x^2] - mean^2. On this PR's own input a two-pass variance gives std 6.44e-08, under the 1e-6 epsilon, so the advantage becomes about -892,538 — roughly 430x the original bug. torch.var does not use the E[x^2] - mean^2 form at all; swapping it in makes this worse, not better.

A brute-force sweep over 200,000 random prompt groups (sizes 2, 3, 4, 5, 8; rewards from {0, 0.123, 1/3, 0.5, 0.95, 1.0, 7.0}; each sample invalidated with probability 0.25) found no input where the per-rollout flag is True, std > 0, and the peer set holds more than one distinct value. Two of us ran it with different seeds: 340 and 365 such cases, max std 1.67e-04 and 1.06e-04, peer-set sizes {3, 5, 6} both times, every one all-identical. The flag never switches off normalization for a group with real variance.

It also fixes more than the PR says. The whole-group mask repairs a group split that happens on main today, with no rounding involved: for [1, 0, 0, 0] and [1, 1, 1, 0], the odd rollout's leave-one-out std is exactly 0.0 (0 and 1 are exact in float32) and the old std != 0 filter drops it alone. I ported #3469's test onto this branch and ran it both ways:

                           merge base 702cd79    this branch 70b70e7
single-success [1,0,0,0]        FAILED                PASSED
single-failure [1,1,1,0]        FAILED                PASSED
balanced       [1,1,0,0]        PASSED                PASSED   (control)

That is worth a line in the description, and it means #3469 can be closed once its test lands here.

No blockers — the 2-tuple stub that would have failed the algorithms lane is fixed. What is left is coverage and documentation:

  • The exact 0/1 shapes above have no test; #3469's already exists and passes here.
  • The valid_mask term in the uniqueness check is untested, and single_controller.py is the only caller that exercises it.
  • GDPOAdvantageEstimator got the same change but no test turns leave-one-out on for it.
  • The std != 0.0 fallback in dynamic_sampling is unreachable in production, and four tests still take it — grpo_sync.py already raises instead of falling back, so there is a pattern to copy.
  • Nothing in docs/ describes the skip; there is no advantage-estimation section to amend.
  • Adjacent, pre-existing: ppo.py accepts use_dynamic_sampling, prints it in the run summary, and never calls the filter — its dynamic_sampling has zero callers.

One cosmetic, optional: the last 30 scopes on main are all lowercase and module-shaped (fix(vllm), fix(megatron), fix(nemo-gym)). Something like fix(grpo): skip advantage normalization when the leave-one-out reward set is all one value would match.

Reviewed at 70b70e7. This review was done by a team of agents.

Generated by Claude Code

Comment thread nemo_rl/algorithms/grpo.py Resolved
Comment thread nemo_rl/algorithms/grpo_sync.py Resolved
Comment thread nemo_rl/algorithms/utils.py Resolved
Comment thread nemo_rl/algorithms/utils.py Resolved
Comment thread tests/unit/algorithms/test_utils.py Resolved
Comment thread nemo_rl/algorithms/utils.py Resolved
Comment thread nemo_rl/algorithms/grpo.py Resolved
Comment thread tests/unit/algorithms/test_grpo.py Resolved
Comment thread nemo_rl/algorithms/grpo.py Resolved
@cspades

cspades commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on Terry’s review summary: the PR now includes the README return-shape fixes, expanded trivial-distribution documentation, valid-mask coverage, GDPO leave-one-out coverage, the required whole-group mask in both GRPO sampling paths, removal of the unreachable GRPO std fallback, and the end-to-end exact-reward regressions for [1,0,0,0], [1,1,1,0], and the balanced control. Focused validation is 16 algorithm tests plus 6 sync data-plane tests passing; Ruff, formatting, and diff checks also pass.

Decisions on the optional/adjacent items: leave the pre-existing sq_baseline cleanup out, keep the current commit title, and only align the dormant PPO dynamic_sampling helper with the whole-group mask without claiming or wiring PPO support. The PPO silent-no-op configuration remains follow-up work. The imported end-to-end test subsumes #3469; I will coordinate closing that PR after this lands.

…ribution to determine whether we want to drop a sample. Check if the full distribution is trivial instead.

Signed-off-by: Cory Ye <[email protected]>
@cspades
cspades force-pushed the cye/adv-loo-norm-bugfix branch from 70b70e7 to 6a95890 Compare September 19, 2026 23:39
@cspades
cspades requested review from a team as code owners September 19, 2026 23:39
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Sep 19, 2026
@cspades

cspades commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 6a95890

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

Thanks for addressing all the comments. Let's merge it!

@terrykong
terrykong enabled auto-merge (squash) September 21, 2026 16:21
@terrykong
terrykong merged commit 8535cae into main Sep 21, 2026
92 checks passed
@terrykong
terrykong deleted the cye/adv-loo-norm-bugfix branch September 21, 2026 16:22
@yfw yfw mentioned this pull request Sep 22, 2026
4 tasks done
jinglinglingling added a commit to jinglinglingling/RL that referenced this pull request Nov 25, 2026
Port of jinx's E34 changes onto upstream forest training (8784ab90,
94174865, 35a742f4, aa8e8da7, 9cf82ca9):

- E34's prompt_mean loss (each comparison group weighs 1/G, shared over
  its eligible tokens) is upstream's loss_fn.normalization=group_token_mean.
  Forest rows now use it: the advantage stage groups every segment of every
  owner in a dispatch group, like the GRPO baseline, and leaves the group
  size check to build_logical_owner_batch, which counts owners rather than
  rows. With complete dynamic-sampling steps the denominator (groups with
  token mass) equals num_prompts_per_step, so the objective matches E34.
- async_rl.log_group_rewards: one GROUP_REWARDS line per prompt group.

Not ported because upstream already covers them: dispatch-group baseline
pooling (20e29644), max_groups_per_chunk (7c98adda, now
max_groups_for_streaming_train), std floor (502853df, NVIDIA-NeMo#4158), load_rng
(d9e897c2), all_owners baseline (masked_reward_policy=include).

Signed-off-by: Linglin Jing <[email protected]>
jinglinglingling added a commit to jinglinglingling/RL that referenced this pull request Nov 26, 2026
Port of jinx's E34 changes onto upstream forest training (8784ab90,
94174865, 35a742f4, aa8e8da7, 9cf82ca9):

- E34's prompt_mean loss (each comparison group weighs 1/G, shared over
  its eligible tokens) is upstream's loss_fn.normalization=group_token_mean.
  Forest rows now use it: the advantage stage groups every segment of every
  owner in a dispatch group, like the GRPO baseline, and leaves the group
  size check to build_logical_owner_batch, which counts owners rather than
  rows. With complete dynamic-sampling steps the denominator (groups with
  token mass) equals num_prompts_per_step, so the objective matches E34.
- async_rl.log_group_rewards: one GROUP_REWARDS line per prompt group.

Not ported because upstream already covers them: dispatch-group baseline
pooling (20e29644), max_groups_per_chunk (7c98adda, now
max_groups_for_streaming_train), std floor (502853df, NVIDIA-NeMo#4158), load_rng
(d9e897c2), all_owners baseline (masked_reward_policy=include).

Signed-off-by: Linglin Jing <[email protected]>
jinglinglingling added a commit to jinglinglingling/RL that referenced this pull request Nov 26, 2026
Port of jinx's E34 changes onto upstream forest training (8784ab90,
94174865, 35a742f4, aa8e8da7, 9cf82ca9):

- E34's prompt_mean loss (each comparison group weighs 1/G, shared over
  its eligible tokens) is upstream's loss_fn.normalization=group_token_mean.
  Forest rows now use it: the advantage stage groups every segment of every
  owner in a dispatch group, like the GRPO baseline, and leaves the group
  size check to build_logical_owner_batch, which counts owners rather than
  rows. With complete dynamic-sampling steps the denominator (groups with
  token mass) equals num_prompts_per_step, so the objective matches E34.
- async_rl.log_group_rewards: one GROUP_REWARDS line per prompt group.

Not ported because upstream already covers them: dispatch-group baseline
pooling (20e29644), max_groups_per_chunk (7c98adda, now
max_groups_for_streaming_train), std floor (502853df, NVIDIA-NeMo#4158), load_rng
(d9e897c2), all_owners baseline (masked_reward_policy=include).

Signed-off-by: Linglin Jing <[email protected]>
jinglinglingling added a commit to jinglinglingling/RL that referenced this pull request Nov 26, 2026
Port of jinx's E34 changes onto upstream forest training (8784ab90,
94174865, 35a742f4, aa8e8da7, 9cf82ca9):

- E34's prompt_mean loss (each comparison group weighs 1/G, shared over
  its eligible tokens) is upstream's loss_fn.normalization=group_token_mean.
  Forest rows now use it: the advantage stage groups every segment of every
  owner in a dispatch group, like the GRPO baseline, and leaves the group
  size check to build_logical_owner_batch, which counts owners rather than
  rows. With complete dynamic-sampling steps the denominator (groups with
  token mass) equals num_prompts_per_step, so the objective matches E34.
- async_rl.log_group_rewards: one GROUP_REWARDS line per prompt group.

Not ported because upstream already covers them: dispatch-group baseline
pooling (20e29644), max_groups_per_chunk (7c98adda, now
max_groups_for_streaming_train), std floor (502853df, NVIDIA-NeMo#4158), load_rng
(d9e897c2), all_owners baseline (masked_reward_policy=include).

Signed-off-by: Linglin Jing <[email protected]>
jinglinglingling added a commit to jinglinglingling/RL that referenced this pull request Nov 28, 2026
Port of jinx's E34 changes onto upstream forest training (8784ab90,
94174865, 35a742f4, aa8e8da7, 9cf82ca9):

- E34's prompt_mean loss (each comparison group weighs 1/G, shared over
  its eligible tokens) is upstream's loss_fn.normalization=group_token_mean.
  Forest rows now use it: the advantage stage groups every segment of every
  owner in a dispatch group, like the GRPO baseline, and leaves the group
  size check to build_logical_owner_batch, which counts owners rather than
  rows. With complete dynamic-sampling steps the denominator (groups with
  token mass) equals num_prompts_per_step, so the objective matches E34.
- async_rl.log_group_rewards: one GROUP_REWARDS line per prompt group.

Not ported because upstream already covers them: dispatch-group baseline
pooling (20e29644), max_groups_per_chunk (7c98adda, now
max_groups_for_streaming_train), std floor (502853df, NVIDIA-NeMo#4158), load_rng
(d9e897c2), all_owners baseline (masked_reward_policy=include).

Signed-off-by: Linglin Jing <[email protected]>
jinglinglingling added a commit to jinglinglingling/RL that referenced this pull request Nov 28, 2026
Port of jinx's E34 changes onto upstream forest training (8784ab90,
94174865, 35a742f4, aa8e8da7, 9cf82ca9):

- E34's prompt_mean loss (each comparison group weighs 1/G, shared over
  its eligible tokens) is upstream's loss_fn.normalization=group_token_mean.
  Forest rows now use it: the advantage stage groups every segment of every
  owner in a dispatch group, like the GRPO baseline, and leaves the group
  size check to build_logical_owner_batch, which counts owners rather than
  rows. With complete dynamic-sampling steps the denominator (groups with
  token mass) equals num_prompts_per_step, so the objective matches E34.
- async_rl.log_group_rewards: one GROUP_REWARDS line per prompt group.

Not ported because upstream already covers them: dispatch-group baseline
pooling (20e29644), max_groups_per_chunk (7c98adda, now
max_groups_for_streaming_train), std floor (502853df, NVIDIA-NeMo#4158), load_rng
(d9e897c2), all_owners baseline (masked_reward_policy=include).

Signed-off-by: Linglin Jing <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

accuracy bug Something isn't working 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.

4 participants