Repository navigation
fix(grpo): exclude masked rows from the GRPO baseline/std - #4490
linj-glitch wants to merge 5 commits into
Conversation
|
We hit the same defect on our fork and arrived at the same fix: a
Related: #4435 (first-class |
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]>
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]>
… 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]>
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]>
…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]>
3c54d75 to
a2c4296
Compare
…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]>
|
Dependents: #4160 (configurable masked-reward participation) is stacked on this branch and should merge after it. |
|
/ok to test a2c4296 |
aroshanghias-nvd
left a comment
There was a problem hiding this comment.
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_sampleandloss_multiplierat both call sites, dynamic-sampling row alignment for the recompute atgrpo.py#L3676, row alignment ofbaseline_for_log/env_baseline_for_logwith 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-existingn=2path does — no NaN/inf reaches training. - The helper's shape stacks onto #4160 unchanged (its diff wraps
_baseline_valid_maskrather 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
|
@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? |
…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]>
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]>
… 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]>
…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]>
|
Closing as incorporated into merged #4160 (67bc3495). Independently checked stable patch IDs for all five commits here against their #4160 counterparts: #4160 includes and extends these changes with configurable |
What does this PR do ?
In
grpo_trainandasync_grpo_train, rows withmask_sampleorloss_multiplier == 0no longer vote in their group's baseline/std, in the dynamic-sampling uniform-group check, or in theenv_baselinekept for thepct_*diagnostics, and thebaseline_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:
docs/guides/grpo.mdalready 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 tocalculate_baseline_and_std_per_promptandcalculate_trivial_reward_distributions, and calledadv_estimator.compute_advantage(...)withoutvalid_mask, although the GRPO, GDPO and Reinforce++ estimators accept one and the SingleControlleradvantage_stagepasses its final sample mask._apply_mask_sample_filterzeroes the loss weight of masked rows, but their rewards still entered the per-prompt statistics.Since #4553/#4620,
mainhas a fourth all-ones site: theenv_baselinecomputed fromenv_rewardwhengrpo.length_penaltyrewritestotal_reward.How it manifests
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 issum(valid rewards) / (n_valid - 1), which is neither 0 nor 1, so counting it reports a pure group as "mixed" ([1, 1, 1, masked]gavepct_1 75 / pct_mixed 25instead of100 / 0).Fix
_baseline_valid_mask(repeated_batch, rewards)returns a binary[B]mask: 0 for rows flaggedmask_sampleand for rows that already carryloss_multiplier == 0, 1 otherwise. The mask is passed to every statistics site in the two loops:grpo_train: the dynamic-samplingcalculate_trivial_reward_distributionscall, bothcalculate_baseline_and_std_per_promptcalls (GPU and CPU branches), theenv_baselinecall, andcompute_advantage(valid_mask=...)(recomputed on the batch after dynamic-sampling filtering).async_grpo_train:compute_advantage(valid_mask=...)._log_mixed_rewards_and_advantages_informationtakes an optionalvalid_mask;grpo_trainpasses the same mask, so thepct_*diagnostics and thetrain/baseline_reward/histogramcover 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
calculate_baseline_and_std_per_promptmultiplies rewards by the mask and divides by its sum, so a fractional mask would mis-weight the group. A nonzero fractionalloss_multipliertherefore keeps the row voting with full weight; the fraction stays a training loss weight only, andrepeated_batchis never modified by the helper.overlong_filtering. The mask is taken before overlong filtering rewritesloss_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 thatcompute_and_apply_seq_logprob_error_maskingmasks later in the step (seq_logprob_error_threshold) also keep voting: that masking runs after the mask is taken. The SingleControlleradvantage_stage(single_controller_utils/advantage_stage.py) foldstruncatedand the seq-logprob-error mask into itsvalid_mask(final_sample_mask), so the two paths differ on those two row classes today (unchanged by this PR;mainalready let them vote). Amask_samplerow'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_sampleis not carried in the batch, so only rows withloss_multiplier == 0are excluded.Scope, dependencies and stacking
masked_reward_policy: includethe default (excludeexplicit; unusable token-capture placeholders excluded under both), so after both merge ordinary masked rows vote again by default and this PR's population becomes theexcludepolicy plus the placeholder rule. Between the two mergesmainexcludes all masked rows; if that interim default is unwanted, these commits can land inside feat(grpo): configurable masked-reward participation across the four trainers #4160 instead (they are already its base).main(fe1d97ce2b82); the statistics are keyed onrepeated_batch[PROMPT_GROUP_IDS_KEY]/_trajectory_group_ids(...)exactly as onmain, and this PR only replaces the third positional argument. fix(grpo): group advantages by prompt identity, not prompt tokens #4495 (duplicate grouping) is being retired in favour of fix(grpo): group advantages by rollout identity #3882; the valid-mask work lives only here.mask_samplereader) is what lets a nested-only environment set the flag this mask reads.grpo_sync.py) still passes an all-ones mask (including its ownenv_baselinesite and itspct_*call) and does not applymask_sample; it is outside the two legacy loops and belongs to the feat(grpo): configurable masked-reward participation across the four trainers #4160 mask-semantics discussion.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 while0.0does not, the mask is binary andloss_multiplieris 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 insidegrpo_trainsees[1, 1, 1, 0]and reports the group as trivial.test_grpo_train_every_baseline_site_excludes_masked_rows: in onegrpo_trainstep withenv_rewardpresent and dynamic sampling on, the trivial check, the CPU baseline/std and theenv_baselinecalls all receive[1, 1, 1, 0], and the real rows' env baseline is0(it would be> 0with an all-ones mask). Counterfactual verified: reverting only theenv_baselineline 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_advantagereceives 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 frompct_*and the histogram (100 / 0with the mask,75 / 25without); theenv_baselinepath uses the same population; a batch with no voting row reports 0, not NaN.test_grpo_train_pct_diagnostics_exclude_masked_rows: onegrpo_trainstep with[1, 1, 1, masked]anduse_leave_one_out_baseline: true: the logging call receivesvalid_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_advantagereceives the expectedvalid_mask, and thesample_maskforwarded topolicy.trainkeeps the original loss weight (0.5stays0.5).test_grpo_train_truncated_rows_vote_in_baseline_but_not_in_loss[grpo_train, async_grpo_train](2): withoverlong_filtering=True, a truncated row reachescompute_advantagewithvalid_mask == 1whilepolicy.trainreceivessample_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.pyalready 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_maskdivergences (two reviewers, one docstring edit,6a989fdb7); thepct_*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 toinclude(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'sinit_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 viaRAY_ADDRESS; no test, fixture or source was changed for that.Remaining gaps
grpo.calculate_advantages_on_gpu: true) is not exercised by a unit test; it passesvalid_mask.cuda(device_id), the same tensor as the CPU branch.mcorecannot run in this environment.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