Skip to content

fix(grpo): group advantages by prompt identity, not prompt tokens - #4495

Closed
linj-glitch wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/grpo-group-by-prompt-id
Closed

linj-glitch wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/grpo-group-by-prompt-id

Conversation

@linj-glitch

Copy link
Copy Markdown
Contributor

Stacked PR. Depends on:

This branch contains those commits too; only the last commit is new here. Review/merge the dependency first.

What does this PR do ?

grpo_train and async_grpo_train now group rows for the GRPO baseline/std, and for the dynamic-sampling checks, by the prompt each row was generated from. Previously they grouped by the first-prompt tokens read back from the rollout.

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 only, CPU; see below)
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs. (N/A: no user-facing change)

Additional Information

Depends on: linj/grpo-baseline-valid-mask (it edits the same lines).

Root cause. Both legacy loops derive the group of each row with torch.unique(prompt_rows, dim=0) inside calculate_baseline_and_std_per_prompt. In grpo_train, the prompt rows for dynamic sampling are the rollout's input_ids; for the advantage they are the first-prompt messages extracted with extract_initial_prompt_messages. In async_grpo_train they are the extracted first-prompt messages. For multi-turn NeMo-Gym rollouts, these rows come from the rollout output, not from the dataset prompt. When an agent harness rewrites or compacts its history, the first message of one rollout can differ from its siblings', even though all of them were generated from the same prompt.

How it manifests.

  • Such a row becomes a singleton group. Its baseline equals its own reward, so it trains with advantage 0, and its real group shrinks by one.
  • Dynamic sampling sees a zero-std singleton and can drop the row while keeping the rest of its group.
  • In the other direction, identical prompts drawn twice into one batch were merged into a single group of 2G rollouts.

Fix. The group is now named explicitly instead of being inferred from tokens:

  • Sync: grpo_train builds a [B, 1] id from each row's position in the repeat_interleaved batch (_prompt_group_ids) before the rollout. Every rollout path returns rows in input order, and an assertion checks the row count. The ids are offset per generation batch, so groups cached by dynamic sampling never collide with groups from a later batch of the same step. The ids are carried in the batch as prompt_group_ids, so they survive dynamic-sampling filtering, slicing, and caching. They are used for the dynamic-sampling baseline/std, calculate_trivial_reward_distributions, and compute_advantage(prompt_ids=...).
  • Async: async_grpo_train uses the position of each replay-buffer entry (_trajectory_group_ids). Each entry holds exactly one prompt group.

For single-turn batches without duplicate prompts, the groups are identical to before. calculate_baseline_and_std_per_prompt and the estimators are unchanged; they already accept any [B, k] id tensor.

Behavior change to flag. Duplicate prompts in one batch are now separate groups. I believe this matches the GRPO definition (one group per sampled prompt) and the SingleController path, which groups by group id.

Not covered. The TransferQueue path (grpo_sync.py) still groups by prompt tokens.

Tests. New tests in tests/unit/algorithms/test_grpo.py:

  • TestPromptGroupIds: id shape and dtype, disjoint ids across generation batches, rejection of partial groups, trajectory ids, and a rewritten-first-message row that stays in its group (singleton under token grouping).
  • test_grpo_train_groups_by_prompt_not_by_returned_prompt_tokens: inside grpo_train with dynamic sampling, a rollout whose first message was rewritten still shares its group.
  • test_grpo_train_passes_prompt_group_ids_to_advantage_estimator: grpo_train and async_grpo_train.

Commands run (CPU only):

python -m pytest tests/unit/algorithms/test_grpo.py tests/unit/algorithms/test_advantage_estimator.py  -> 242 passed
ruff check / ruff check --select I / ruff format --check (v0.9.9) on touched files                      -> clean

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

@linj-glitch
linj-glitch marked this pull request as draft October 5, 2026 06:10
linj-glitch and others added 2 commits October 7, 2026 16:53
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]>
grpo_train and async_grpo_train grouped rows for the baseline/std (and for
the dynamic-sampling std and trivial-group check) with torch.unique over
the first-prompt token rows read back from the rollout. A multi-turn
rollout whose first message differs from its siblings' (agent harnesses
that rewrite or compact the history) became a singleton group: its
baseline equals its reward, so it trains with advantage 0, and its real
group shrinks. Identical prompts drawn twice into one batch were also
merged into a single group.

Name the group explicitly instead. The sync loop builds a [B, 1] id from
each row's position in the repeat_interleave'd batch (offset per
generation batch so dynamic-sampling caches never collide) before the
rollout and carries it in the batch as prompt_group_ids; the async loop
uses the position of each replay-buffer entry, which holds exactly one
prompt group. Single-turn batches without duplicate prompts group exactly
as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch
linj-glitch force-pushed the linj/grpo-group-by-prompt-id branch from 7bc1c69 to 8cd2a5e Compare October 8, 2026 00:15
@aroshanghias-nvd

aroshanghias-nvd commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for putting this together. #3882 is the broader fix for grouping GRPO advantages by rollout identity rather than prompt-token equality.

To avoid maintaining two competing implementations of the same fix, please close this PR in favor of #3882. The separate valid-mask work in #4490 can continue independently.

aroshanghias-nvd added a commit that referenced this pull request Oct 8, 2026
Keep independent prompt draws and rewritten rollout histories in their original GRPO groups. Carry stable keys through legacy dynamic sampling and async replay, and reuse explicit TQ group tags in sync advantage consumers.

Adapt the identity regression tests from PR #4495 while keeping its separate valid-mask dependency out of scope.

Co-authored-by: Lin Jia <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
@linj-glitch

Copy link
Copy Markdown
Contributor Author

Agreed, thanks for landing #3882 (724344f). It does everything this PR set out to do and more: the sync loop mints prompt_group_ids before the rollout and carries them through dynamic sampling, the async loop names groups by replay entry, and the TransferQueue and single-controller paths key on GROUP_ID_TAG, which this PR had left uncovered. Closing this one in favour of #3882.

For the record, this PR's regression tests already live on main, so nothing needs to be ported: the _prompt_group_ids / _trajectory_group_ids unit cases, the rewritten-first-message case, and the sync/async compute_advantage(prompt_ids=...) checks are in tests/unit/algorithms/test_grpo_group_identity.py (plus the duplicate-prompt and cross-batch cache cases this PR did not have), and the TQ/SC side is covered in tests/unit/experience/test_sync_rollout_actor.py, tests/unit/data_plane/test_sync_one_hop.py and tests/unit/single_controller/test_advantage_stage.py. All of those pass on current main.

The valid-mask change (_baseline_valid_mask: masked rows excluded from the group baseline/std and from the dynamic-sampling std) was never part of this PR's own commit and is not addressed by #3882. It stays in #4490, which I will rebase onto main's group-id key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants