Skip to content

feat(grpo): configurable masked-reward participation across the four trainers - #4160

Merged
yfw merged 23 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/legacy-grpo-valid-mask
Oct 27, 2026
Merged

yfw merged 23 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/legacy-grpo-valid-mask

Conversation

@linj-glitch

@linj-glitch linj-glitch commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds grpo.masked_reward_policy: include|exclude across legacy synchronous GRPO, asynchronous GRPO, TransferQueue, and SingleController, with a binary statistics mask separate from training loss weights and real policy log probabilities for Reinforce++ KL statistics under top-k/top-p filtering.

The default is include, as requested in the post-training review; exclude remains available. Under include, every row with a nonzero dataset weight votes: environment-masked, truncated and sequence-logprob-error rows included. Rows the dataset marked with loss_multiplier == 0 (prompts that did not fit the sequence limit) and SingleController token-capture placeholders never vote on any trainer, so Reinforce++'s batch normalization keeps main's population plus the masked rewards, and legacy/TransferQueue GRPO and GDPO statistics are unchanged from main. SingleController's ordinary masked rows now vote in baseline/std only, because that trainer does not support dynamic sampling.

Relative to main, the default therefore expands SingleController's baseline population and Reinforce++'s normalization by the masked rewards, zeroes TransferQueue environment-masked loss weights, and keeps statistics rows' policy logprobs real under top-k/top-p filtering; reward diagnostics and dynamic-sampling admission, where supported, follow the selected statistics mask. The TransferQueue actor now also forwards env.should_mask_flagged_samples to the Gym rollout, as the other trainers do.

This branch is stacked on #4490, whose five commits sit below its own and are part of this diff until #4490 merges; since the repository squash-merges, landing this PR lands the combined change and #4490 can then be closed (related: #4061).

Local validation on the rebased head: tests/unit/algorithms/test_grpo.py and the single-controller, advantage-estimator, advantage-validity, sync-rollout-actor and config-v2 suites pass (483 and 287 tests), changed-file pre-commit passes, and pyrefly check shows zero errors. The paired experiment configs now enable overlong_filtering so a same-seed include/exclude comparison produces non-voting rows; that run (reward curves, reference KL, num_mask_sample_filtered, step time) remains outstanding and needs a GPU box with Automodel installed, or a maintainer waiver.

@linj-glitch
linj-glitch requested review from a team as code owners September 17, 2026 00:56
@copy-pr-bot

copy-pr-bot Bot commented Sep 17, 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.

@linj-glitch

Copy link
Copy Markdown
Contributor Author

@terrykong @yuki-97 @yfw could you take a look when you have a moment? You reviewed or merged most of the recent grpo.py changes, and @yfw the async-loop fixes in particular. This one is small: the legacy grpo_train / async_grpo_train loops now pass the final sample_mask as valid_mask to the advantage estimator, the same contract the SingleController already uses, so mask_sample / overlong / seq-logprob-error rows stop voting in their siblings' baseline. 208 tests in the touched suites pass locally.

@yuhezhang-ai

Copy link
Copy Markdown
Contributor

@linj-glitch thanks for merging #2 into this branch!

One thing to watch when you merge main (28 commits behind, two small conflicts in grpo_sync.py and test_grpo.py): #4158 moved dynamic-sampling admission from std != 0 to calculate_trivial_reward_distributions(...), which is called with an all-ones valid mask in both the legacy loop and grpo_sync.py. After the merge, masked_reward_policy no longer affects which groups dynamic sampling keeps, so under the default exclude a group whose only reward variance comes from a masked row gets admitted again. test_dynamic_sampling_uses_masked_reward_policy still asserts through the old std path, so it will keep passing.

Fix is small: pass the same _dynamic_sampling_valid_mask(...) to calculate_trivial_reward_distributions at both call sites, and update the test to assert through the trivial-distribution path. The function already accepts a valid mask, and it treats groups with at most one valid reward as trivial, which matches the #4061 rule.

Could you help merge main and make that change? Happy to send it as another PR into your branch if easier. It would also be worth updating the PR title and body, since they still describe the original two-file change and the branch now adds grpo.masked_reward_policy across four trainers plus docs and paired experiment configs. After that it needs a maintainer to add CI:L2.

@linj-glitch linj-glitch changed the title fix(grpo): legacy loops exclude loss-masked rows from the group baseline / std feat(grpo): configure masked reward participation in advantage statistics Sep 22, 2026
@ananthsub

Copy link
Copy Markdown
Contributor

/ok to test f13dcd9

@ananthsub ananthsub added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Sep 22, 2026
pull Bot pushed a commit to Stars1233/Gym that referenced this pull request Sep 23, 2026
)

This follows merged NVIDIA-NeMo#2814, which established group, attempt, and member
identities. It addresses NVIDIA-NeMo#3181's immediate timeout and failure-cleanup
requirements.

- **While collecting answers:** enforce a finite deadline. If a member
never arrives, fail the group and release waiting requests without
publishing partial rewards.
- **Once all answers are available:** retry transient judge HTTP
failures, including interrupted response bodies, within a bounded budget
using the same answers.
- **If judging ultimately fails:** preserve each generated answer and
return an explicitly masked failure. The zero reward is a placeholder,
excluded from Gym evaluation metrics by default.
- **On failure, cancellation, or shutdown:** release waiters and clean
up pending work.

### Recovery and compatibility

A judge failure returns HTTP 200 with `mask_sample: true`,
`failure_kind: judge_failed`, a bounded `failure_reason`, and the
existing failure-sidecar tags. The shared judge failsafe also preserves
`instance_config.mask_sample: true` for older RL consumers. This shared
response fix applies to every environment using `judge_failsafe`.

The existing evaluation opt-in `count_failure_classes_as_zero:
[judge_failed]` still includes selected failures as zeros. Only the
metric-input copy is unmasked; saved failure records and training masks
remain unchanged. Online and offline aggregation apply the same policy,
including when every rollout fails. With the opt-in, an
all-`judge_failed` run reports `mean/reward: 0.0`; without eligible
counted failures or successful results, collection still raises. The
main rollout JSONL never receives synthetic successes.

**A masked HTTP 200 result does not automatically make RL retry the
group.** It is a completed, unusable result for the current RL caller.
If the caller chooses replacement:

- **Explicit-ID groups:** advance the shared group-attempt number for
every member and submit a complete replacement group.
- **Legacy groups without an ID:** failed groups retain a failure
record. Reusing their task/prompt key returns failure with migration
guidance; recovery requires a fresh explicit group ID for the complete
group. This prevents delayed old members from joining a replacement.
Successful legacy groups still allow sequential new evaluations.

The judge-request default is now **1,800 seconds**, matching the overall
evaluation budget. This allows substantially more room for long
generations and queueing than the previous 300-second default;
deployments must still size both limits for their workload.

**Required RL coordination:** before NeMo RL adopts this Gym revision,
coordinate with [RL NVIDIA-NeMo#4160](NVIDIA-NeMo/RL#4160)
/ [NVIDIA-NeMo#4061](NVIDIA-NeMo/RL#4061). Reading the
mask alone is insufficient: TransferQueue must preserve it in the
training loss mask, and unavailable judge rewards must be excluded from
group statistics. NVIDIA-NeMo#4160 includes these fixes with `masked_reward_policy:
exclude` as the default. Top-level field ingestion remains separate
migration work, so the nested compatibility field remains. Before
updating RL's Gym revision, validate a real failed Gym response through
RL's loss mask and group statistics. Gym can merge first if RL keeps its
existing Gym revision until those fixes are available.

GenRM-specific usage and recovery documentation is now in the
[resources-server
README](https://github.com/NVIDIA-NeMo/Gym/blob/yuhez/3181-genrm-cohort-lifecycle/resources_servers/genrm_compare/README.md#genrm-comparison-groups),
rather than a new Fern site page.

Closes NVIDIA-NeMo#3181.

<details>
<summary>Validation</summary>

Current code: `6a7f30b707aee62c46478d757005f3fcc9fabe0d`, incorporating
main at `d4c0f86c7`. The latest fix is `059adb409`.

- **5,110 core, GenRM, and OSWorld dependency-policy tests passed** on
Python 3.13.14: `python -m pytest tests/unit_tests
resources_servers/genrm_compare/tests
responses_api_agents/osworld_agent/tests/test_dependency_policy.py -m
'not sandbox' -q --tb=short`. There were 103 skips, 673 sandbox tests
deselected, and 184 passing subtests. Sandbox tests were not run
locally.
- The all-failure regression checks one and four masked judge failures,
zero counting enabled/disabled, an unrelated counted class, and deferred
aggregation. Four cases fail on the preceding code and pass with this
fix; default and wrong-class error behavior remains intact. Existing
mixed-success tests remain covered.
- Actual TCP collector → SimpleAgent → GenRM tests check both collection
timeout and judge outage, with zero counting on/off. Online and offline
metrics match, the failure sidecar remains byte-for-byte unchanged, and
the main/merged rollout JSONL stays empty.
- Final all-files pre-commit, whitespace checks, and DCO sign-off
passed. [Exact-head
CI](https://github.com/NVIDIA-NeMo/Gym/actions/runs/35867697700) passed,
including core and all eight server shards. The preceding run passed
core and seven server shards but failed OSWorld dependency resolution;
merged NVIDIA-NeMo#3649 fixes that NumPy metadata conflict and is included in this
head. [Previous-head
CI](https://github.com/NVIDIA-NeMo/Gym/actions/runs/35681811360) passed
on `be7e6353d`, including core and all eight server shards.
- No new model run for the latest collector aggregation fix: it changes
metric eligibility, not policy generation or judging. The earlier
real-model evidence below is from `be7e6353d`.
- **Real-model functional validation passed:** Slurm job **19084624**,
exit 0 in **14m58s**, on `be7e6353d`. Gym's native CLI/HTTP path used
Qwen3-0.6B policy and Qwen3-Nemotron-235B-A22B-GenRM-2603 on eight
H100s. Eight policy generations and four completed real judge calls were
captured.
- The run preserved four masked failure answers during an injected judge
outage, then scored a caller-coordinated complete replacement attempt.
Four HTTP 503s and four interrupted HTTP response bodies recovered
within the retry budget without extra policy generation. A second
collector resume made no further model calls. Failed legacy groups
rejected delayed members, explicit zero-count aggregation preserved
saved masks, and rewards exactly matched the captured judgments. Saved
artifacts were independently inspected.
- The model run enabled `CUDA_LAUNCH_BLOCKING=1` for diagnostics after
an earlier CUDA failure. That failure did not recur; this does not
establish its root cause. The run's functional assertions passed before
the separate launcher teardown issue described below.
- No full RL training, checkpoint restart, or comparative throughput
claim.

</details>

<details>
<summary>Limits and follow-ups</summary>

The caller coordinates complete replacement attempts. There is no
partial scoring, automatic group scheduling, durable answer reuse, or
change to generation/judge overlap. Legacy identities cannot isolate
overlapping runs or provide completed replay. Explicit-ID replay and
failure records are process-local and bounded by retention; eviction or
restart is not a recovery protocol.

Ordinary individual reverification is unsupported. The existing
`judge_failed_only` guard bypass does not create groups or advance
attempts: retained failures remain failures until the caller supplies a
complete replacement with the required identity.

Active-group memory limits, retention optimization, caller-minted group
identities, durable outcomes, richer telemetry, and improvements to
retry backoff remain follow-up work. The inherited judge-failed-only
mode-guard bypass needs a separate compatibility change; documenting it
does not make individual GenRM reverification supported.

A Ray teardown abort was previously reproduced on both main and an
earlier PR head; its native cause remains undiagnosed. In the passing
job 19084624, the Gym launcher again exited with SIGABRT after the
functional assertions completed. The harness stopped the remaining owned
children and recorded no survivors; the separate policy server exited
normally and Slurm released the allocation. This validates the GenRM
failure/recovery behavior, not a clean Ray launcher shutdown.

</details>

### Related PRs: what is covered and what could follow

Built on NVIDIA-NeMo#2814 (Anish Mahishi), with deadline and cleanup requirements
from NVIDIA-NeMo#2385 (Teodor-Dumitru Ene) and NVIDIA-NeMo#2903 (Jiacheng Xu). Contributor
credit remains in commit trailers.

**NVIDIA-NeMo#2385:** the timeout requirement is covered. Its partial-scoring
policy is not adopted: if A/B/C arrive but D is missing, this PR fails
the incomplete group. Whole-group failure is allowed by NVIDIA-NeMo#3181. Close
NVIDIA-NeMo#2385 as superseded if that policy is accepted; otherwise retain/rework
partial scoring as separate follow-up work with explicit missing-member
and training/metric semantics.

**NVIDIA-NeMo#2903:** together, NVIDIA-NeMo#2814 and this PR cover request deduplication,
duplicate-disconnect safety, and failure cleanup. Three policy
differences remain:

- NVIDIA-NeMo#2903 permits a fresh group under the same identity after failure.
Here, replacement requires a newer shared explicit attempt, or a fresh
explicit ID when migrating a failed legacy group.
- NVIDIA-NeMo#2903 keeps completed rewards for the server's lifetime, including
legacy groups. Here, completed replay is bounded and restricted to
identical responses in explicit-ID groups; legacy groups have no
completed replay.
- NVIDIA-NeMo#2903 starts comparing available answer pairs while other answers are
still generating. Here, we preserve NVIDIA-NeMo#2814's wait-for-all schedule. Each
judge call needs only two answers, so early judging remains a possible
optimization; it does not require partial reward publication, and its
performance benefit has not been benchmarked.

After this PR merges, maintainers can close NVIDIA-NeMo#2903 as superseded if these
choices are accepted, tracking desired early judging or broader
replay/retry behavior separately. Alternatively, rework the existing PR
against current main to focus on the remaining scope. Closing either
older PR means its core problem is addressed and remaining choices are
accepted or tracked, not that every proposed behavior was merged.

---------

Signed-off-by: Yuhe Zhang <[email protected]>
Co-authored-by: Anish Mahishi <[email protected]>
Co-authored-by: Jiacheng Xu <[email protected]>
Co-authored-by: Teodor-Dumitru Ene <[email protected]>
@linj-glitch
linj-glitch marked this pull request as draft October 5, 2026 06:10

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

Could we make masked_reward_policy: include the default? The post-training team wants masked rewards to participate in advantage estimation by default, while keeping exclude available as an explicit option. Please update the configs, docs, and tests accordingly. Unusable token-capture placeholders should remain excluded under both settings.

There’s also a correctness issue with include when using Reinforce++ with KL in reward and top-k/top-p filtering. The workers zero out loss-masked rows’ policy log probabilities, but their reference log probabilities remain real. Including those rows in normalization therefore introduces incorrect KL penalties and changes the advantages of the unmasked responses.

Could you preserve the log probabilities needed for statistics separately from the training loss mask, and add a regression test covering the worker masking step through advantage calculation? The current estimator tests supply log probabilities directly, so they miss this interaction.

@linj-glitch
linj-glitch force-pushed the linj/legacy-grpo-valid-mask branch from f13dcd9 to 0a1db40 Compare October 8, 2026 00:15
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
Adopt the post-training team's request (NVIDIA-NeMo#4160 review 5432593408): masked
rewards participate in the advantage statistics by default, `exclude` stays
an explicit option, and token-capture placeholders stay excluded under both.
This is a policy decision, not a finding that `exclude` is numerically wrong;
no controlled convergence comparison between the two settings exists, and the
paired experiment configs are the way to run one.

The default is applied in one place each: GRPOConfig, the grpo_math_1B
exemplar and its reference copy for the v1/v2 migration check, the paired
experiment configs (both now set the key explicitly), the GRPO guide (new
section text and the overlong-filtering sentence, which described the
include behaviour), and the estimator module docstring. With `include` the
legacy and TransferQueue loops keep every row voting as earlier releases
did; what changes for them is the real-logprob rule for statistics rows and
the Reinforce++/GDPO normalization population, both documented in the guide.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch
linj-glitch force-pushed the linj/legacy-grpo-valid-mask branch from 0a1db40 to 3a6cf3d Compare October 13, 2026 16:36
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 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 changed the title feat(grpo): configure masked reward participation in advantage statistics feat(grpo): configurable masked-reward participation across the four trainers Oct 13, 2026
linj-glitch and others added 7 commits October 23, 2026 12:34
The guide said the default matches the all-rows behaviour of earlier
releases. That holds for the legacy and TransferQueue loops, whose baseline
sites passed `torch.ones_like` on main, but SingleController's advantage
stage already passed `valid_mask=final_sample_mask`, so mask_sample,
truncated and seq-logprob-error rows did not vote there before and do under
`include` now. State both.

Also name the second kind of data-plane `sample_mask == 0` row that
SingleController excludes under both policies (datums carrying a
dataset-level `loss_multiplier` of 0, written by the data plane next to the
token-capture placeholders), note that the legacy and TransferQueue loops let
those rows vote under `include`, and record that the TransferQueue trainer
now applies `mask_sample` to the loss weights and reports
`num_mask_sample_filtered`, which it never did before this branch.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…al test

test_grpo_train_fractional_loss_weights_vote_fully_in_statistics iterated
over the recorded pre-filter valid masks without checking that anything was
recorded. For async_grpo_train the list is always empty: the async loop has
no pre-logprob baseline/std call and the estimator binds its own copy of
calculate_baseline_and_std_per_prompt, so the loop proved nothing there.
Pin the count (one call for the sync loop, none for the async loop) and
describe it in the comment.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
Two sites this branch changes in the TransferQueue driver had no test of
their own. The actor's bulk `sample_mask` column now carries the statistics
participation mask for the worker logprob passes, but the only TQ end-to-end
test ran with `use_kl_in_reward=False` and all-zero fake logprobs, so the
chain "TQ column -> worker filter -> prev_logprobs read back -> estimator"
was never exercised. The env_baseline site switched from `torch.ones_like`
to `statistics_valid_mask`, but no TQ test supplied `env_reward`.

test_tq_include_kl_in_reward_sees_real_logprobs_of_masked_rows runs the real
actor under include + Reinforce++ KL-in-reward + top_k, filters the policy
logprobs with the fetched column exactly as the workers do (the reference
pass is never filtered), and checks the trainable rows against an
independent reference; the loss-weights counterfactual zeroes the masked
row's policy logprobs and moves them. test_tq_env_baseline_site_uses_the_
statistics_mask records both driver-side baseline calls and asserts one mask
and the expected env baseline under each policy. The shared actor/driver
scaffolding lives in two helpers.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
… 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]>
Under `include` the legacy sync and async loops and the TransferQueue
driver let every row vote, so a prompt the dataset could not fit into the
sequence limit (cut to a few tokens, `loss_multiplier == 0` before any
rollout) entered the advantage statistics. For GRPO and GDPO this was
harmless, because a dataset weight is shared by the whole prompt group,
but Reinforce++'s token-level batch normalization counted those rows'
response tokens: with one trainable group of rewards [1, 0] (2 tokens
each) and one over-length group [0, 0] (8 tokens each) the trainable rows
got [2.24, -2.24] instead of main's [1, -1]. SingleController, which reads
the dataset weight from its data-plane sample_mask, was already right.

Take the `include` population from the dataset weight instead of all ones
(`_include_valid_mask`): `_dynamic_sampling_valid_mask` runs before the
in-trainer filters, so it reads `loss_multiplier` directly; the three
drivers snapshot the column before the overlong and mask_sample filters
rewrite it (every filter clones before assigning) and hand it to
`_advantage_valid_mask` / `_logprob_sample_mask`. Masked rewards (env
flags, truncated and seq-logprob-error rows) keep voting under `include`;
`exclude` is unchanged. A pre-existing zero weight is therefore trivial
for dynamic sampling under both policies, and the pct_* diagnostics and
the TQ actor's logprob mask follow the same population.

Docs: the `include` bullet and the placeholder paragraph of the GRPO
guide, the estimator module docstring and the SingleController comment
now say that dataset-zero-weight rows never vote on any trainer.

Tests: `test_trainers_never_let_over_length_prompts_vote` drives the
example above through the sync and async loops and the TransferQueue
driver (two prompt groups; the async replay stub returns one trajectory
per group) and `test_advantage_stage_over_length_prompts_never_vote` pins
the SingleController stage to the same normalization mask and [1, -1];
`TestStatisticsParticipation` covers the helper, and the existing
dynamic-sampling and TQ masked-reward tests expect the pre-existing
zero-weight row to stay out under `include`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
`SyncRolloutActor.rollout_to_tq` never passed `mask_env_flagged_samples`
to `run_nemo_gym_rollout_sync`, whose default is True, so Gym's
`mask_sample` flags always reached the TransferQueue trainer even when the
user set `env.should_mask_flagged_samples: false`. On main this was
inert, because the TQ driver never read `mask_sample`; this branch
carries the flag into driver_carry and zeroes the flagged rows' loss
weight (and, under `exclude`, drops them from the statistics and the
worker logprob mask), so a user who turned the flag off still lost those
rows from training. The legacy loop, the async collector and
SingleController all forward `should_mask_flagged_samples(cfg.env)`; do
the same here.

Test: `test_tq_forwards_should_mask_flagged_samples` runs the real actor
with a stubbed Gym rollout under both flag values and both policies and
checks the forwarded argument, the actor's logprob mask, the written-back
loss mask and `num_mask_sample_filtered` (1 with the flag on, 0 off), so
an actor that always passed False would fail as well.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
… configs

Both experiment configs only set `grpo.masked_reward_policy` on top of
grpo_math_1B.yaml, which never puts a non-voting row inside a trainable
group: the math environment sets no `mask_sample`, overlong filtering and
the seq-logprob-error threshold are off, top-p/top-k are off, and the only
zero-weight rows are over-length prompts whose whole group shares the
weight. The include/exclude comparison they exist for would therefore have
trained identically under both policies. Turn on `overlong_filtering` in
both files, so truncated rollouts (frequent at a 512-token budget) vote
only under `include`; the pair still differs in the policy key alone.

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

Copy link
Copy Markdown
Contributor Author

/ok to test 1429122

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

One remaining concern: include currently treats an invalid environment reward like a valid reward from a loss-filtered attempt.

Gym’s mask_sample contract explicitly says the reward is not a valid measurement. For example, OSWorld returns reward=0, mask_sample=True when evaluation raises. With rewards [1,1,0], where the third is invalid, the current include path gives the valid siblings advantages [0.5,0.5] rather than [0,0] (LOO, normalization off). The evaluator failure therefore changes their training signal despite its own loss being masked.

Could we always exclude environment-masked rewards from statistics when should_mask_flagged_samples is enabled, while keeping include available for valid rewards from overlong or sequence-error-filtered attempts? This requires no new field. Please add a regression showing that perturbing an environment-invalid reward cannot change valid siblings’ advantages under either policy. This behavior predates the PR in legacy GRPO, but is newly introduced into SingleController here.

@yfw

yfw commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

@aroshanghias-nvd Thanks, agreed: an environment-masked reward isn't a valid measurement and shouldn't move its valid siblings' advantages.

This PR is intentionally scoped to make all four trainers match the existing legacy GRPO behavior (include as the default), so we'd like to keep it as is and fix this in a follow-up PR across all four trainers:

  • Environment-masked (mask_sample) rows won't count toward the baseline/std by default, except for failure_kinds attributable to the policy (e.g. agent timeouts).
  • Trainer-filtered rows (overlong filtering, seq-logprob errors) keep following masked_reward_policy.
  • It will include the regression you suggested: perturbing an environment-invalid reward can't change valid siblings' advantages.

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]>
@yfw
yfw merged commit 67bc349 into NVIDIA-NeMo:main Oct 27, 2026
305 of 309 checks passed
ZhiyuLi-Nvidia added a commit that referenced this pull request Oct 28, 2026
…bject.__new__

The #4160 tests in test_grpo.py build SyncRolloutActor without __init__, so
rollout_to_tq hit AttributeError on the new per_token_multimodal_fields
attribute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zhiyu Li <[email protected]>
yfw added a commit that referenced this pull request Oct 28, 2026
exclude_infra stays available as an opt-in value; the default stays include,
as in #4160. Update the config default, the example and reference configs,
the GRPO guide and the default test.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
pjin-nvidia added a commit that referenced this pull request Oct 30, 2026
…ics-20260930

Conflicts:
- grpo.py: keep _apply_async_sample_masks beside the #4160 participation
  helpers, and capture dataset_loss_multiplier before calling it (the
  helper clones loss_multiplier, so the reference stays the dataset weight).
- single_controller.py: take main's _advantage_stage, whose body #4326
  moved into AdvantageComputer.run, and drop the unused helper import.
- test_grpo.py: keep both sides' imports and test classes.

Move the SingleController port with the code it changed:
- advantage_stage.py: apply _apply_async_sample_masks in
  AdvantageComputer.run, fold the logprob-error count into
  num_masked_seqs_total, and return the counts as
  AdvantageOutcome.sample_mask_metrics.
- single_controller.py: _absorb_advantage_outcome appends them to
  _step_log_dict["sample_mask_metrics"].
- test_advantage_stage.py: classify the new AdvantageOutcome field.
- test_utils.py: use the reward_partials/advantage_partials parameter
  names from #4326.

Signed-off-by: Peter Jin <[email protected]>
hemildesai added a commit to hemildesai/RL that referenced this pull request Nov 5, 2026
Main's grpo.masked_reward_policy (NVIDIA-NeMo#4160) now decides which masked rows vote
in the group baseline/std, so drop grpo.masked_sample_rewards_in_baseline and
baseline_valid_mask; the masking/rollout stats read the estimator's
advantage_valid_mask instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
hemildesai added a commit to hemildesai/RL that referenced this pull request Nov 6, 2026
Main's grpo.masked_reward_policy (NVIDIA-NeMo#4160) now decides which masked rows vote
in the group baseline/std, so drop grpo.masked_sample_rewards_in_baseline and
baseline_valid_mask; the masking/rollout stats read the estimator's
advantage_valid_mask instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
hemildesai added a commit to hemildesai/RL that referenced this pull request Nov 6, 2026
Main's grpo.masked_reward_policy (NVIDIA-NeMo#4160) now decides which masked rows vote
in the group baseline/std, so drop grpo.masked_sample_rewards_in_baseline and
baseline_valid_mask; the masking/rollout stats read the estimator's
advantage_valid_mask instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
bg51717 pushed a commit to hemildesai/RL that referenced this pull request Nov 11, 2026
Main's grpo.masked_reward_policy (NVIDIA-NeMo#4160) now decides which masked rows vote
in the group baseline/std, so drop grpo.masked_sample_rewards_in_baseline and
baseline_valid_mask; the masking/rollout stats read the estimator's
advantage_valid_mask instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
bg51717 pushed a commit to hemildesai/RL that referenced this pull request Nov 19, 2026
Main's grpo.masked_reward_policy (NVIDIA-NeMo#4160) now decides which masked rows vote
in the group baseline/std, so drop grpo.masked_sample_rewards_in_baseline and
baseline_valid_mask; the masking/rollout stats read the estimator's
advantage_valid_mask instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
bg51717 pushed a commit to hemildesai/RL that referenced this pull request Nov 19, 2026
Main's grpo.masked_reward_policy (NVIDIA-NeMo#4160) now decides which masked rows vote
in the group baseline/std, so drop grpo.masked_sample_rewards_in_baseline and
baseline_valid_mask; the masking/rollout stats read the estimator's
advantage_valid_mask instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
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 Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants