Skip to content

fix(grpo): exclude masked rows from the GRPO baseline/std - #4490

Closed
linj-glitch wants to merge 5 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/grpo-baseline-valid-mask
Closed

linj-glitch wants to merge 5 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/grpo-baseline-valid-mask

Conversation

@linj-glitch

@linj-glitch linj-glitch commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

In grpo_train and async_grpo_train, rows with mask_sample or loss_multiplier == 0 no longer vote in their group's baseline/std, in the dynamic-sampling uniform-group check, or in the env_baseline kept for the pct_* diagnostics, and the baseline_reward/pct_* diagnostics and baseline histogram count the same rows. Statistical participation is binary; training loss weights are untouched. The SingleController path already passes a real validity mask.

Issues

None.

Usage

No new configuration.

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 (unit tests, CPU; see Validation)
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs. (No change needed: docs/guides/grpo.md already documents the truncated-row rule this PR preserves, and there is no user-facing option.)

Additional Information

Root cause

Both legacy loops passed torch.ones_like(rewards) as the valid mask to calculate_baseline_and_std_per_prompt and calculate_trivial_reward_distributions, and called adv_estimator.compute_advantage(...) without valid_mask, although the GRPO, GDPO and Reinforce++ estimators accept one and the SingleController advantage_stage passes its final sample mask. _apply_mask_sample_filter zeroes the loss weight of masked rows, but their rewards still entered the per-prompt statistics.

Since #4553/#4620, main has a fourth all-ones site: the env_baseline computed from env_reward when grpo.length_penalty rewrites total_reward.

How it manifests

  • A masked row (for example an infrastructure failure flagged by the environment) usually carries a synthetic reward. It shifts the baseline, and so the advantage, of every real sibling in the group.
  • With dynamic sampling, a group whose only reward variance comes from a masked row looks non-uniform and is kept for training although its real rollouts all have the same reward.
  • The baseline_reward/pct_* diagnostics read the env baseline, so the same synthetic reward also distorted those metrics. Once the mask is passed, a masked row still has a baseline entry of its own; under the leave-one-out baseline it is sum(valid rewards) / (n_valid - 1), which is neither 0 nor 1, so counting it reports a pure group as "mixed" ([1, 1, 1, masked] gave pct_1 75 / pct_mixed 25 instead of 100 / 0).

Fix

_baseline_valid_mask(repeated_batch, rewards) returns a binary [B] mask: 0 for rows flagged mask_sample and for rows that already carry loss_multiplier == 0, 1 otherwise. The mask is passed to every statistics site in the two loops:

  • grpo_train: the dynamic-sampling calculate_trivial_reward_distributions call, both calculate_baseline_and_std_per_prompt calls (GPU and CPU branches), the env_baseline call, and compute_advantage(valid_mask=...) (recomputed on the batch after dynamic-sampling filtering).
  • async_grpo_train: compute_advantage(valid_mask=...).
  • _log_mixed_rewards_and_advantages_information takes an optional valid_mask; grpo_train passes the same mask, so the pct_* diagnostics and the train/baseline_reward/histogram cover the rows that voted. A batch in which no row voted reports 0 for all three percentages instead of NaN. The TransferQueue caller (grpo_sync.py) does not pass a mask and keeps its all-rows behaviour.

Estimators that do not group (raw reward, GAE, OPD) accept and ignore extra kwargs.

The two rules, stated explicitly

  1. Participation is binary. calculate_baseline_and_std_per_prompt multiplies rewards by the mask and divides by its sum, so a fractional mask would mis-weight the group. A nonzero fractional loss_multiplier therefore keeps the row voting with full weight; the fraction stays a training loss weight only, and repeated_batch is never modified by the helper.
  2. Truncated rollouts keep voting under overlong_filtering. The mask is taken before overlong filtering rewrites loss_multiplier, so a truncated but otherwise real rollout still counts toward its group's baseline/std. This is the documented behaviour of these loops (docs/guides/grpo.md, Overlong Filtering: "Truncated samples contribute 0 to the gradient update while remaining in the batch for reward baseline calculations"). For the same reason, rows that compute_and_apply_seq_logprob_error_masking masks later in the step (seq_logprob_error_threshold) also keep voting: that masking runs after the mask is taken. The SingleController advantage_stage (single_controller_utils/advantage_stage.py) folds truncated and the seq-logprob-error mask into its valid_mask (final_sample_mask), so the two paths differ on those two row classes today (unchanged by this PR; main already let them vote). A mask_sample row's reward is typically a placeholder (e.g. an infrastructure failure), not a measurement of the policy, which is why it is treated differently from a truncated row here; whether ordinary masked rewards should vote is what feat(grpo): configurable masked-reward participation across the four trainers #4160 makes configurable.

Behaviour change

Only batches containing masked or zero-weight rows change. With env.should_mask_flagged_samples: false, mask_sample is not carried in the batch, so only rows with loss_multiplier == 0 are excluded.

Scope, dependencies and stacking

Tests (tests/unit/algorithms/test_grpo.py)

  • TestBaselineValidMask (6): tensor and list flags; missing keys keep every row; fractional nonzero weights (1.0, 0.5, 0.25, 1e-6) vote while 0.0 does not, the mask is binary and loss_multiplier is unchanged; the truncated-row rule is enforced by call order (truncated rows vote before the overlong rewrite and would not afterwards); a group whose only variance is a masked row is uniform with the mask and non-uniform without it.
  • test_grpo_train_dynamic_sampling_std_excludes_masked_rows: the trivial-group check inside grpo_train sees [1, 1, 1, 0] and reports the group as trivial.
  • test_grpo_train_every_baseline_site_excludes_masked_rows: in one grpo_train step with env_reward present and dynamic sampling on, the trivial check, the CPU baseline/std and the env_baseline calls all receive [1, 1, 1, 0], and the real rows' env baseline is 0 (it would be > 0 with an all-ones mask). Counterfactual verified: reverting only the env_baseline line makes this test fail.
  • test_grpo_train_dynamic_sampling_recomputes_valid_mask_on_assembled_batch: cached+current dynamic-sampling batch (2 prompts x 3 generations, two generation batches): compute_advantage receives the recomputed mask [1, 1, 0, 1, 1, 1] for the assembled [group 1 | group 2] batch, not the last generation batch's all-ones mask. Counterfactual verified: a stale pre-filter mask at the recompute site makes this test fail.
  • test_log_mixed_rewards_pct_diagnostics_* (3): the leave-one-out artifact ([1, 1, 1, 0] with mask [1, 1, 1, 0] gives baseline [1, 1, 1, 1.5]) is dropped from pct_* and the histogram (100 / 0 with the mask, 75 / 25 without); the env_baseline path uses the same population; a batch with no voting row reports 0, not NaN.
  • test_grpo_train_pct_diagnostics_exclude_masked_rows: one grpo_train step with [1, 1, 1, masked] and use_leave_one_out_baseline: true: the logging call receives valid_mask == [1, 1, 1, 0], pct_1 == 100, pct_mixed == 0, and the histogram carries the three real rows. Counterfactual verified: ignoring the mask inside the diagnostics makes this test (and the three unit tests) fail.
  • test_grpo_train_passes_baseline_valid_mask_to_advantage_estimator[{valid, fractional_loss_multiplier, mask_sample, zero_loss_multiplier} x {grpo_train, async_grpo_train}] (8): compute_advantage receives the expected valid_mask, and the sample_mask forwarded to policy.train keeps the original loss weight (0.5 stays 0.5).
  • test_grpo_train_truncated_rows_vote_in_baseline_but_not_in_loss[grpo_train, async_grpo_train] (2): with overlong_filtering=True, a truncated row reaches compute_advantage with valid_mask == 1 while policy.train receives sample_mask == 0.

The sync/async driver tests follow the capture pattern of tests/unit/algorithms/test_grpo_group_identity.py; tests/unit/algorithms/test_advantage_validity.py already pins the estimator side ([1, 3, 2, 0] with mask [1, 1, 1, 0] gives baseline 2).

Self-review

A team self-review of the revised branch confirmed 5 findings, all addressed here: the helper docstring named only one of the two SingleController valid_mask divergences (two reviewers, one docstring edit, 6a989fdb7); the pct_* diagnostics still counted the masked row's leave-one-out artifact (ab61559bd, with tests); the post-dynamic-sampling mask recompute had no test where the assembled batch differs from the last generation batch (a2c4296b5); and this description did not disclose that stacked #4160 flips the default back to include (description only, see Scope). No blocking defect was found.

Validation

Environment: Python 3.13.14, torch 2.13.0+cu130, Ray 2.58.0, 1x NVIDIA L4 (shared host), no Megatron-Core / Megatron-Bridge / TransformerEngine installed. Native invocation from tests/ with the repository conftest. On this shared host the conftest's init_ray() (address="auto") found multiple active Ray instances from other sessions, so pytest was launched through a small wrapper that starts one dedicated Ray head and hands its address to the same conftest via RAY_ADDRESS; no test, fixture or source was changed for that.

# revised head before self-review (7edc196b2)
pytest unit/algorithms/test_grpo.py -k 'BaselineValidMask or baseline_valid_mask or dynamic_sampling_std_excludes_masked \
  or every_baseline_site or truncated_rows_vote' -p no:cacheprovider -o addopts='-rA -q --tb=short'
                                                                           -> 18 passed, 218 deselected (exit 0)
pytest unit/algorithms/test_grpo.py unit/algorithms/test_advantage_validity.py unit/algorithms/test_grpo_group_identity.py \
  -p no:cacheprovider -o addopts='-rA -q --tb=short'                       -> 254 passed, 0 failed, 0 skipped (exit 0)

# counterfactual (env_baseline site temporarily reverted to torch.ones_like(rewards), then restored)
pytest unit/algorithms/test_grpo.py -k every_baseline_site                 -> 1 failed (exit 1), as intended

# final head (a2c4296b5), after the self-review fixes
pytest unit/algorithms/test_grpo.py -k 'BaselineValidMask or baseline_valid_mask or dynamic_sampling_std_excludes_masked \
  or every_baseline_site or truncated_rows_vote or recomputes_valid_mask or pct_diagnostics' \
  -p no:cacheprovider -o addopts='-rA -q --tb=short'                       -> 23 passed, 218 deselected (exit 0)
pytest unit/algorithms/test_grpo.py unit/algorithms/test_advantage_validity.py unit/algorithms/test_grpo_group_identity.py \
  -p no:cacheprovider -o addopts='-rA -q --tb=short'                       -> 259 passed, 0 failed, 0 skipped in 25.0 s (exit 0):
                                                                              test_grpo.py 241, test_advantage_validity.py 8, test_grpo_group_identity.py 10

# counterfactual (valid_mask temporarily ignored inside _log_mixed_rewards_and_advantages_information, then restored)
pytest unit/algorithms/test_grpo.py -k pct_diagnostics                     -> 4 failed (exit 1), as intended
# counterfactual (recompute site handed the stale pre-filter mask via monkeypatch; worktree untouched)
pytest <scratch>/test_4490_fixer_counterfactual_recompute.py              -> stale mask detected (AssertionError raised, call pattern [real, real, stale]); 2 passed (exit 0)

SKIP=pyrefly-typecheck pre-commit run --files nemo_rl/algorithms/grpo.py tests/unit/algorithms/test_grpo.py  -> all hooks Passed
pyrefly check                                                              -> errors shown: 0 (same as main)

Remaining gaps

  • The GPU branch (grpo.calculate_advantages_on_gpu: true) is not exercised by a unit test; it passes valid_mask.cuda(device_id), the same tensor as the CPU branch.
  • No training run; this is a CPU unit-test change set. Tests marked mcore cannot run in this environment.
  • TransferQueue path (grpo_sync.py) and the SingleController rule for truncated and seq-logprob-error-masked rows are intentionally out of scope (see above).

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 5, 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.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor

We hit the same defect on our fork and arrived at the same fix: a valid_mask derived from the environment mask, passed to calculate_baseline_and_std_per_prompt, the triviality check, and compute_advantage on the dataflow and async paths, so a masked placeholder reward stops voting in its siblings' baseline and standard deviation. Rather than open a competing PR we will adopt this one's shape once it lands. Three notes from our port that may be useful here:

  • main now has a fourth torch.ones_like(rewards) site since feat(grpo): per-prompt-group length penalties for NeMo-Gym GRPO rollouts #4553: the env_baseline block at nemo_rl/algorithms/grpo.py:3507, next to the three at :3461, :3477, :3495.
  • The single-controller mask (single_controller_utils/advantage_stage.py:348-349) also drops truncated rows under overlong_filtering, so a port that reuses final_sample_mask and one that masks only environment-masked rows will not match exactly on truncated samples; worth stating which rule this PR intends.
  • tests/unit/algorithms/test_advantage_validity.py:35 already pins the estimator ([1, 3, 2, 0] with mask [1, 1, 1, 0] gives a baseline of 2). What was untested on our side was the wiring; tests/unit/algorithms/test_grpo_group_identity.py:184-203 drives both grpo_train and async_grpo_train and captures the compute_advantage arguments, which made a good template for asserting that the mask reaches every call site.

Related: #4435 (first-class mask_sample reader) is what makes a nested-only environment set the flag this mask reads.

linj-glitch and others added 5 commits October 12, 2026 23:35
grpo_train and async_grpo_train computed the per-prompt baseline/std with
an all-ones valid mask and called adv_estimator.compute_advantage without
valid_mask. Rows the environment flags with mask_sample, and rows that
already carry loss_multiplier == 0, therefore still voted in their
siblings' baseline, and in the dynamic-sampling std / trivial-group check,
so a group whose only reward variance came from a masked row was kept as
if it had signal.

Add _baseline_valid_mask, taken before overlong filtering rewrites
loss_multiplier (truncated rollouts keep voting as before), and pass it to
the dynamic-sampling baseline/std, calculate_trivial_reward_distributions,
and compute_advantage(valid_mask=...) in both loops. This matches the
SingleController path, which already passes its final sample mask as
valid_mask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
main grew a fourth all-ones valid-mask site after NVIDIA-NeMo#4553/NVIDIA-NeMo#4620: the
env_baseline that grpo.length_penalty keeps for the pct_* diagnostics.
Pass the same participation mask there, so a masked row's env reward
does not vote in its siblings' env baseline either.

State the two rules the mask follows in the helper docstring and at
both call sites. Participation is binary: a nonzero fractional
loss_multiplier still counts as one vote, and the training loss
weights are never changed. Truncated rollouts keep voting under
overlong_filtering because the mask is taken before that rewrite,
which is what docs/guides/grpo.md documents for these loops; the
SingleController advantage_stage folds truncated rows into its
valid_mask instead, and reconciling the two is left to the
configurable policy work rather than decided here.

Tests: fractional-nonzero versus zero loss weight, the truncated-row
call-order rule, one driver test asserting the trivial check, the
baseline/std and the env baseline all receive the mask (and that the
env baseline of the real rows ignores the masked reward), a fractional
case for the sync/async forwarding test plus an assertion that the
forwarded sample_mask keeps the original weight, and a sync/async test
that a truncated row votes in the baseline while overlong filtering
removes it from the loss.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
The _baseline_valid_mask docstring said these loops differ from the
SingleController advantage_stage only on truncated rows. They also
differ on rows masked by seq_logprob_error_threshold: in grpo_train and
async_grpo_train the mask is taken before
compute_and_apply_seq_logprob_error_masking rewrites sample_mask, so
those rows keep voting here, while advantage_stage reassigns
final_sample_mask from the masked sample_mask before passing it as
valid_mask. State both row classes and drop the process sentence about
reconciling them, which belongs in the PR discussion, not in source.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
The previous commit passes the participation mask to every baseline
call, so a masked row no longer votes in its siblings' baseline. Its
own baseline entry, however, is still written: under the leave-one-out
baseline calculate_baseline_and_std_per_prompt gives it
sum(valid rewards) / (n_valid - 1), a value that is neither 0 nor 1
unless the valid mean is 0. _log_mixed_rewards_and_advantages_information
averaged pct_0/pct_1 over every row, so that entry was reported as a
"mixed" group: one group of four with rewards [1, 1, 1, masked] logged
pct_1 75 / pct_mixed 25 instead of 100 / 0, and the baseline histogram
carried the same synthetic value.

Give the function an optional valid_mask, restrict the histogram and
the pct_* population to the rows that voted, and report 0 for all
three when no row voted instead of NaN. grpo_train passes the same
baseline_valid_mask it handed to compute_advantage; the TransferQueue
caller in grpo_sync.py is unchanged and keeps the all-rows behaviour
until that path carries a mask.

Tests: the LOO artifact and the 75/25 -> 100/0 correction on the
function, the env-baseline (grpo.length_penalty) path through the same
mask, the no-voting-row case, and one grpo_train driver test capturing
the call with valid_mask [1, 1, 1, 0] and pct_1 100 / pct_mixed 0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
grpo_train recomputes baseline_valid_mask on the batch that dynamic
sampling assembled (cache + current batch, sliced), because that batch
can differ from the last generation batch. No test exercised that
line: the single-step driver forces use_dynamic_sampling off, and the
two dynamic-sampling drivers raise before the recompute, so a
regression that reused the pre-filter mask or hoisted the recompute
above dynamic_sampling would have passed every test.

Drive two generation batches of 2 prompts x 3 generations. Batch 1
drops its trivial group and caches a group with one masked row; batch
2 completes the step with two clean groups. compute_advantage must see
valid_mask [1, 1, 0, 1, 1, 1] for the assembled [group 1 | group 2]
batch, whereas the last generation batch's own mask is all ones. The
stale-mask counterfactual fails this test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 13, 2026
Two defects in how grpo.masked_reward_policy separates the advantage
statistics from the training loss, found in the review of NVIDIA-NeMo#4160:

1. Fractional loss weights reached the statistics (BF-4160-1). Under
   `exclude` the estimator and the pre-logprob sites received the loss
   weights themselves as `valid_mask`, but calculate_baseline_and_std_per_prompt
   and the GDPO/Reinforce++ normalizations count rows: two valid rows with
   rewards [0, 1] and weights [.5, .5] produced baselines [0, 1] and zero
   advantages. Participation is now binary everywhere (`_binary_participation`):
   a nonzero weight votes with full weight and stays a training weight only.
   One mask feeds every statistics site of each trainer: the legacy loops'
   dynamic-sampling admission, baseline/std, env_baseline and
   compute_advantage; the TransferQueue driver's baseline/std, env_baseline
   (previously still all-ones) and admission through one
   `statistics_valid_mask`; and the SingleController stage, which binarizes
   the raw sample mask (include) or the final sample mask (exclude), so
   token-capture placeholders never vote under either policy.

2. Statistics rows lost their logprobs under top-k/top-p filtering
   (root-4160-kl). The workers zero every logprob outside
   token_mask * sample_mask, for the policy and the reference pass alike, and
   the drivers handed them the loss weights. A loss-masked row that votes
   under `include` therefore reached Reinforce++'s KL-in-reward with a zero
   KL term and shifted the batch normalization of the trainable rows. The
   policy and reference logprob passes now receive the statistics
   participation mask (`_logprob_sample_mask`): the sync loop's logprob_data,
   an async-loop view of train_data, and the TransferQueue actor's bulk
   `sample_mask`, which only the worker logprob passes read (the driver
   writes the final training mask back after advantages). The training
   sample_mask is unchanged; under `exclude` both masks select the same rows.

The `exclude` policy also folds truncated rows in under overlong_filtering at
the pre-logprob sites, so one population serves admission, baseline and
estimator; `include` keeps them voting, as docs/guides/grpo.md describes.

Tests: TestStatisticsParticipation (binary helper, both policies, fractional
baseline [.5, .5]); fractional rows in the legacy/TQ admission test, the
fractional-weight step with independent expected advantages; the logprob
passes receive the statistics mask; an include + KL-in-reward + top-k step
whose fake policy applies mask_filtered_logprobs_outside_tokens and whose
unmasked-row advantages match an independent reference; the estimator-side
worker-filter regression in test_advantage_validity.py; SC binary
participation with a placeholder row. The NVIDIA-NeMo#4490 driver tests are
parametrized over the policy, and the TQ dynamic-sampling test rows now
carry the GROUP_ID_TAG that main's NVIDIA-NeMo#3882 requires.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 13, 2026
… population

NVIDIA-NeMo#4490 restricts the baseline histogram and the baseline_reward/pct_*
diagnostics of grpo_train to the rows that voted in the baseline and left
the TransferQueue driver on the all-rows behaviour "until that path
carries a mask". Both trainers carry one on this branch: hand
_log_mixed_rewards_and_advantages_information the same mask that
compute_advantage receives (_advantage_valid_mask: every row under
include, the binary final loss mask under exclude) in grpo_train_sync, as
grpo_train does after the restack, so the two trainers report the same
diagnostics for the same policy.

Under include nothing changes (the mask is all ones). Under exclude a
non-voting row's leave-one-out entry, which is neither 0 nor 1, no longer
makes an all-correct group look mixed in the TransferQueue trainer
either. The GRPO guide states the population of these diagnostics.

Tests: test_tq_pct_diagnostics_use_the_statistics_mask[exclude, include]
drives the real actor payload through grpo_train_sync with the
leave-one-out baseline and asserts the mask, the three percentages and
the histogram (exclude: [1, 1, 1, 0], pct_1 100; include: all ones,
pct_1 25 / pct_mixed 75). The restacked grpo_train tests from NVIDIA-NeMo#4490 run
under both policies.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 13, 2026
The straggler cutoff needs the iterator returned by
RolloutCollectionHelper.run_examples to have an async aclose(), which
NVIDIA-NeMo/Gym#4029 adds. The pinned Gym (17abf2dd) returns a plain map,
so with it the actor warns once and runs uncut; the pin follows once the
Gym change is on main. Also spells out what cancellation does on the Gym
side, the per-actor scope under sharding, the receipt-mode fallback, and
how cut rows are treated statistically: zero loss, excluded from the
rollout-level statistics over model outputs, but a reward of 0 that still
enters the group baseline/std on current main until the masked-reward
participation policy (NVIDIA-NeMo#4490 / NVIDIA-NeMo#4160) lands. The timing replay is an
estimate of wall time saved, not a convergence result.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 13, 2026
…olicy notes

NeMo RL calls run_examples without Gym's max_resident_tasks, so the cutoff
always acts on in-flight /run requests; drop the claim that unadmitted rows
never start and say that max_resident_rollout_tasks does not bound this path.
Describe the sharded roll-up (num_cut summed, flags any-shard, per-event
values per shard) and that the block stays in every shard's config. Hedge the
masked-reward note to what RL NVIDIA-NeMo#4490 does today (legacy grpo.py only; the
data-plane trainer still needs the same valid mask) with NVIDIA-NeMo#4160 tracking the
policy. Point at the in-repo interop test, and list the cutoff among the
SingleController guide's unsupported features.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch
linj-glitch force-pushed the linj/grpo-baseline-valid-mask branch from 3c54d75 to a2c4296 Compare October 13, 2026 16:37
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 13, 2026
…he baseline

The _mark_unusable_rollout docstring promised that the placeholder is masked
from loss and baseline. Zero loss holds on every path, but only the
single-controller advantage stage passes sample_mask into the baseline's
valid mask; the batched GRPO and grpo_sync paths call
calculate_baseline_and_std_per_prompt with an all-ones valid mask, so the
placeholder's reward still enters its siblings' leave-one-out baseline
(tracked in NVIDIA-NeMo#4160 / NVIDIA-NeMo#4490). Say exactly that in the docstring and the design
doc, and note in _run_rollouts why a mixed group's placeholder may carry a
prompt_ids_for_adv row cut at the real prompt's length (the SC baseline keys
on GROUP_ID_TAG, so prompt ids are not a grouping key).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch
linj-glitch marked this pull request as ready for review October 13, 2026 16:39
@linj-glitch

Copy link
Copy Markdown
Contributor Author

Dependents: #4160 (configurable masked-reward participation) is stacked on this branch and should merge after it.

@linj-glitch

Copy link
Copy Markdown
Contributor Author

/ok to test a2c4296

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

LGTM on the code — 1 action item (maintainer), 1 question (maintainers), no inline comments.

Thanks for the careful write-up: the counterfactual tests per statistics site and the explicit truncated-row rule made this easy to verify. A team review (RL expert, bug finder, test reviewer, design reviewer, comment reviewer, devil's advocate) found no blocking defect:

  • Mask shape/device/presence of mask_sample and loss_multiplier at both call sites, dynamic-sampling row alignment for the recompute at grpo.py#L3676, row alignment of baseline_for_log / env_baseline_for_log with the recomputed mask, the async path, and estimator kwargs compatibility all check out.
  • Groups left with ≤1 voting row hit the existing guard in calculate_baseline_and_std_per_prompt (baseline := reward, advantage 0), and the two-valid-row leave-one-out case collapses to an unnormalized advantage exactly as the pre-existing n=2 path does — no NaN/inf reaches training.
  • The helper's shape stacks onto #4160 unchanged (its diff wraps _baseline_valid_mask rather than forking it), so no config seam is needed here.
  • All asserted values in the new tests were hand-checked against the helpers; the match= strings are regex-safe; the file runs in the Algorithms L0 shard.

Static review only: this review node has no GPU and torch does not import, so pytest and pyrefly were not executed here. Pinned ruff check / import-sort / format are clean on both files, and CI's Lint check passed at this head.

AI-1 — CI label (maintainer)

The PR has no CI:* label, so the run triggered by /ok to test a2c4296b executed Lint only and "CI quality check (No tests run: Label CI:L*)" failed. Baseline/advantage statistics can affect convergence, which the cicd guide maps to CI:L2. Could a maintainer attach CI:L2 and re-post /ok to test a2c4296b52568a0c4ee1682f77db52353e5d2bf2 (the trigger is sha-specific)?

Question — merge order vs. #4160

Building on the Scope note in the description: #4160's review asks for masked_reward_policy: include as the default, so merging this PR first moves the legacy loops include → exclude → include for ordinary mask_sample rows (the branch at grpo.py#L2591-L2595). Maintainers, please choose explicitly: accept the interim exclude default on main, or take the author's offer to land these commits inside #4160. One consideration for that choice: #4160's include default re-admits ordinary masked rows to the dynamic-sampling trivial check, so this PR's headline dynamic-sampling fix persists only for placeholder (loss_multiplier == 0) rows once #4160 lands.

Context — no action. The loss_multiplier == 0 branch also catches dataset-time prompt truncation (e.g. processors.py#L128), which is per-prompt and therefore covers whole groups. Those groups never trained before or after this change, so the effect is limited to dynamic-sampling slot occupancy and the pct_* / histogram population; a sentence in "Behaviour change" would be welcome but is not required.

Generated by Claude Code

@linj-glitch linj-glitch added the CI:L2 Run doctests, unit tests, functional tests, and convergence tests label Oct 15, 2026
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

@terrykong , #4490 is unchanged since my review and looks good on the code. Before I approve, can you confirm the landing plan with #4160: merge #4490 first and accept the temporary exclusion of masked rewards, or land the combined change through #4160?

linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 19, 2026
…he baseline

The _mark_unusable_rollout docstring promised that the placeholder is masked
from loss and baseline. Zero loss holds on every path, but only the
single-controller advantage stage passes sample_mask into the baseline's
valid mask; the batched GRPO and grpo_sync paths call
calculate_baseline_and_std_per_prompt with an all-ones valid mask, so the
placeholder's reward still enters its siblings' leave-one-out baseline
(tracked in NVIDIA-NeMo#4160 / NVIDIA-NeMo#4490). Say exactly that in the docstring and the design
doc, and note in _run_rollouts why a mixed group's placeholder may carry a
prompt_ids_for_adv row cut at the real prompt's length (the SC baseline keys
on GROUP_ID_TAG, so prompt ids are not a grouping key).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 23, 2026
Two defects in how grpo.masked_reward_policy separates the advantage
statistics from the training loss, found in the review of NVIDIA-NeMo#4160:

1. Fractional loss weights reached the statistics (BF-4160-1). Under
   `exclude` the estimator and the pre-logprob sites received the loss
   weights themselves as `valid_mask`, but calculate_baseline_and_std_per_prompt
   and the GDPO/Reinforce++ normalizations count rows: two valid rows with
   rewards [0, 1] and weights [.5, .5] produced baselines [0, 1] and zero
   advantages. Participation is now binary everywhere (`_binary_participation`):
   a nonzero weight votes with full weight and stays a training weight only.
   One mask feeds every statistics site of each trainer: the legacy loops'
   dynamic-sampling admission, baseline/std, env_baseline and
   compute_advantage; the TransferQueue driver's baseline/std, env_baseline
   (previously still all-ones) and admission through one
   `statistics_valid_mask`; and the SingleController stage, which binarizes
   the raw sample mask (include) or the final sample mask (exclude), so
   token-capture placeholders never vote under either policy.

2. Statistics rows lost their logprobs under top-k/top-p filtering
   (root-4160-kl). The workers zero every logprob outside
   token_mask * sample_mask, for the policy and the reference pass alike, and
   the drivers handed them the loss weights. A loss-masked row that votes
   under `include` therefore reached Reinforce++'s KL-in-reward with a zero
   KL term and shifted the batch normalization of the trainable rows. The
   policy and reference logprob passes now receive the statistics
   participation mask (`_logprob_sample_mask`): the sync loop's logprob_data,
   an async-loop view of train_data, and the TransferQueue actor's bulk
   `sample_mask`, which only the worker logprob passes read (the driver
   writes the final training mask back after advantages). The training
   sample_mask is unchanged; under `exclude` both masks select the same rows.

The `exclude` policy also folds truncated rows in under overlong_filtering at
the pre-logprob sites, so one population serves admission, baseline and
estimator; `include` keeps them voting, as docs/guides/grpo.md describes.

Tests: TestStatisticsParticipation (binary helper, both policies, fractional
baseline [.5, .5]); fractional rows in the legacy/TQ admission test, the
fractional-weight step with independent expected advantages; the logprob
passes receive the statistics mask; an include + KL-in-reward + top-k step
whose fake policy applies mask_filtered_logprobs_outside_tokens and whose
unmasked-row advantages match an independent reference; the estimator-side
worker-filter regression in test_advantage_validity.py; SC binary
participation with a placeholder row. The NVIDIA-NeMo#4490 driver tests are
parametrized over the policy, and the TQ dynamic-sampling test rows now
carry the GROUP_ID_TAG that main's NVIDIA-NeMo#3882 requires.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 23, 2026
… population

NVIDIA-NeMo#4490 restricts the baseline histogram and the baseline_reward/pct_*
diagnostics of grpo_train to the rows that voted in the baseline and left
the TransferQueue driver on the all-rows behaviour "until that path
carries a mask". Both trainers carry one on this branch: hand
_log_mixed_rewards_and_advantages_information the same mask that
compute_advantage receives (_advantage_valid_mask: every row under
include, the binary final loss mask under exclude) in grpo_train_sync, as
grpo_train does after the restack, so the two trainers report the same
diagnostics for the same policy.

Under include nothing changes (the mask is all ones). Under exclude a
non-voting row's leave-one-out entry, which is neither 0 nor 1, no longer
makes an all-correct group look mixed in the TransferQueue trainer
either. The GRPO guide states the population of these diagnostics.

Tests: test_tq_pct_diagnostics_use_the_statistics_mask[exclude, include]
drives the real actor payload through grpo_train_sync with the
leave-one-out baseline and asserts the mask, the three percentages and
the histogram (exclude: [1, 1, 1, 0], pct_1 100; include: all ones,
pct_1 25 / pct_mixed 75). The restacked grpo_train tests from NVIDIA-NeMo#4490 run
under both policies.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to linj-glitch/RL that referenced this pull request Oct 24, 2026
…he baseline

The _mark_unusable_rollout docstring promised that the placeholder is masked
from loss and baseline. Zero loss holds on every path, but only the
single-controller advantage stage passes sample_mask into the baseline's
valid mask; the batched GRPO and grpo_sync paths call
calculate_baseline_and_std_per_prompt with an all-ones valid mask, so the
placeholder's reward still enters its siblings' leave-one-out baseline
(tracked in NVIDIA-NeMo#4160 / NVIDIA-NeMo#4490). Say exactly that in the docstring and the design
doc, and note in _run_rollouts why a mixed group's placeholder may carry a
prompt_ids_for_adv row cut at the real prompt's length (the SC baseline keys
on GROUP_ID_TAG, so prompt ids are not a grouping key).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch

Copy link
Copy Markdown
Contributor Author

Closing as incorporated into merged #4160 (67bc3495). Independently checked stable patch IDs for all five commits here against their #4160 counterparts: 5969a554→e85f0ce0, 7edc196b→7ce2fb75, 6a989fdb→9a3ad0dd, ab61559b→ccc549cc, and a2c4296b→c308f799; all match. The complete #4160 branch diff also matches its squash commit.

#4160 includes and extends these changes with configurable include/exclude masked-reward behavior and an include default, so the final behavior deliberately differs from this PR's original unconditional exclusion. No unique patch remains to merge from this branch.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants